babylon.max.js 3.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305
  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. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8598. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8599. this._gl.DEPTH24_STENCIL8 = 35056;
  8600. // Extensions
  8601. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8602. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8603. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8604. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8605. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8606. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8607. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8608. 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');
  8609. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8610. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8611. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8612. this._caps.highPrecisionShaderSupported = true;
  8613. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8614. if (this._caps.timerQuery) {
  8615. if (this._webGLVersion === 1) {
  8616. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8617. }
  8618. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8619. }
  8620. // Checks if some of the format renders first to allow the use of webgl inspector.
  8621. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8622. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8623. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8624. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8625. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8626. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8627. if (this._webGLVersion > 1) {
  8628. this._gl.HALF_FLOAT_OES = 0x140B;
  8629. }
  8630. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8631. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8632. // Draw buffers
  8633. if (this._webGLVersion > 1) {
  8634. this._caps.drawBuffersExtension = true;
  8635. }
  8636. else {
  8637. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8638. if (drawBuffersExtension !== null) {
  8639. this._caps.drawBuffersExtension = true;
  8640. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8641. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8642. for (var i = 0; i < 16; i++) {
  8643. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8644. }
  8645. }
  8646. else {
  8647. this._caps.drawBuffersExtension = false;
  8648. }
  8649. }
  8650. // Depth Texture
  8651. if (this._webGLVersion > 1) {
  8652. this._caps.depthTextureExtension = true;
  8653. }
  8654. else {
  8655. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8656. if (depthTextureExtension != null) {
  8657. this._caps.depthTextureExtension = true;
  8658. }
  8659. }
  8660. // Vertex array object
  8661. if (this._webGLVersion > 1) {
  8662. this._caps.vertexArrayObject = true;
  8663. }
  8664. else {
  8665. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8666. if (vertexArrayObjectExtension != null) {
  8667. this._caps.vertexArrayObject = true;
  8668. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8669. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8670. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8671. }
  8672. else {
  8673. this._caps.vertexArrayObject = false;
  8674. }
  8675. }
  8676. // Instances count
  8677. if (this._webGLVersion > 1) {
  8678. this._caps.instancedArrays = true;
  8679. }
  8680. else {
  8681. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8682. if (instanceExtension != null) {
  8683. this._caps.instancedArrays = true;
  8684. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8685. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8686. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8687. }
  8688. else {
  8689. this._caps.instancedArrays = false;
  8690. }
  8691. }
  8692. // Intelligently add supported compressed formats in order to check for.
  8693. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8694. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8695. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8696. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8697. if (this._caps.astc)
  8698. this.texturesSupported.push('-astc.ktx');
  8699. if (this._caps.s3tc)
  8700. this.texturesSupported.push('-dxt.ktx');
  8701. if (this._caps.pvrtc)
  8702. this.texturesSupported.push('-pvrtc.ktx');
  8703. if (this._caps.etc2)
  8704. this.texturesSupported.push('-etc2.ktx');
  8705. if (this._caps.etc1)
  8706. this.texturesSupported.push('-etc1.ktx');
  8707. if (this._gl.getShaderPrecisionFormat) {
  8708. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8709. if (highp) {
  8710. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8711. }
  8712. }
  8713. // Depth buffer
  8714. this.setDepthBuffer(true);
  8715. this.setDepthFunctionToLessOrEqual();
  8716. this.setDepthWrite(true);
  8717. };
  8718. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8719. get: function () {
  8720. return this._webGLVersion;
  8721. },
  8722. enumerable: true,
  8723. configurable: true
  8724. });
  8725. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8726. /**
  8727. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8728. */
  8729. get: function () {
  8730. return this._isStencilEnable;
  8731. },
  8732. enumerable: true,
  8733. configurable: true
  8734. });
  8735. Engine.prototype._prepareWorkingCanvas = function () {
  8736. if (this._workingCanvas) {
  8737. return;
  8738. }
  8739. this._workingCanvas = document.createElement("canvas");
  8740. var context = this._workingCanvas.getContext("2d");
  8741. if (context) {
  8742. this._workingContext = context;
  8743. }
  8744. };
  8745. Engine.prototype.resetTextureCache = function () {
  8746. for (var key in this._activeTexturesCache) {
  8747. this._activeTexturesCache[key] = null;
  8748. }
  8749. };
  8750. Engine.prototype.isDeterministicLockStep = function () {
  8751. return this._deterministicLockstep;
  8752. };
  8753. Engine.prototype.getLockstepMaxSteps = function () {
  8754. return this._lockstepMaxSteps;
  8755. };
  8756. Engine.prototype.getGlInfo = function () {
  8757. return {
  8758. vendor: this._glVendor,
  8759. renderer: this._glRenderer,
  8760. version: this._glVersion
  8761. };
  8762. };
  8763. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8764. if (useScreen === void 0) { useScreen = false; }
  8765. var viewport = camera.viewport;
  8766. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8767. };
  8768. Engine.prototype.getRenderWidth = function (useScreen) {
  8769. if (useScreen === void 0) { useScreen = false; }
  8770. if (!useScreen && this._currentRenderTarget) {
  8771. return this._currentRenderTarget.width;
  8772. }
  8773. return this._gl.drawingBufferWidth;
  8774. };
  8775. Engine.prototype.getRenderHeight = function (useScreen) {
  8776. if (useScreen === void 0) { useScreen = false; }
  8777. if (!useScreen && this._currentRenderTarget) {
  8778. return this._currentRenderTarget.height;
  8779. }
  8780. return this._gl.drawingBufferHeight;
  8781. };
  8782. Engine.prototype.getRenderingCanvas = function () {
  8783. return this._renderingCanvas;
  8784. };
  8785. Engine.prototype.getRenderingCanvasClientRect = function () {
  8786. if (!this._renderingCanvas) {
  8787. return null;
  8788. }
  8789. return this._renderingCanvas.getBoundingClientRect();
  8790. };
  8791. Engine.prototype.setHardwareScalingLevel = function (level) {
  8792. this._hardwareScalingLevel = level;
  8793. this.resize();
  8794. };
  8795. Engine.prototype.getHardwareScalingLevel = function () {
  8796. return this._hardwareScalingLevel;
  8797. };
  8798. Engine.prototype.getLoadedTexturesCache = function () {
  8799. return this._internalTexturesCache;
  8800. };
  8801. Engine.prototype.getCaps = function () {
  8802. return this._caps;
  8803. };
  8804. Object.defineProperty(Engine.prototype, "drawCalls", {
  8805. /** The number of draw calls submitted last frame */
  8806. get: function () {
  8807. return this._drawCalls.current;
  8808. },
  8809. enumerable: true,
  8810. configurable: true
  8811. });
  8812. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8813. get: function () {
  8814. return this._drawCalls;
  8815. },
  8816. enumerable: true,
  8817. configurable: true
  8818. });
  8819. Engine.prototype.getDepthFunction = function () {
  8820. return this._depthCullingState.depthFunc;
  8821. };
  8822. Engine.prototype.setDepthFunction = function (depthFunc) {
  8823. this._depthCullingState.depthFunc = depthFunc;
  8824. };
  8825. Engine.prototype.setDepthFunctionToGreater = function () {
  8826. this._depthCullingState.depthFunc = this._gl.GREATER;
  8827. };
  8828. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8829. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8830. };
  8831. Engine.prototype.setDepthFunctionToLess = function () {
  8832. this._depthCullingState.depthFunc = this._gl.LESS;
  8833. };
  8834. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8835. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8836. };
  8837. Engine.prototype.getStencilBuffer = function () {
  8838. return this._stencilState.stencilTest;
  8839. };
  8840. Engine.prototype.setStencilBuffer = function (enable) {
  8841. this._stencilState.stencilTest = enable;
  8842. };
  8843. Engine.prototype.getStencilMask = function () {
  8844. return this._stencilState.stencilMask;
  8845. };
  8846. Engine.prototype.setStencilMask = function (mask) {
  8847. this._stencilState.stencilMask = mask;
  8848. };
  8849. Engine.prototype.getStencilFunction = function () {
  8850. return this._stencilState.stencilFunc;
  8851. };
  8852. Engine.prototype.getStencilFunctionReference = function () {
  8853. return this._stencilState.stencilFuncRef;
  8854. };
  8855. Engine.prototype.getStencilFunctionMask = function () {
  8856. return this._stencilState.stencilFuncMask;
  8857. };
  8858. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8859. this._stencilState.stencilFunc = stencilFunc;
  8860. };
  8861. Engine.prototype.setStencilFunctionReference = function (reference) {
  8862. this._stencilState.stencilFuncRef = reference;
  8863. };
  8864. Engine.prototype.setStencilFunctionMask = function (mask) {
  8865. this._stencilState.stencilFuncMask = mask;
  8866. };
  8867. Engine.prototype.getStencilOperationFail = function () {
  8868. return this._stencilState.stencilOpStencilFail;
  8869. };
  8870. Engine.prototype.getStencilOperationDepthFail = function () {
  8871. return this._stencilState.stencilOpDepthFail;
  8872. };
  8873. Engine.prototype.getStencilOperationPass = function () {
  8874. return this._stencilState.stencilOpStencilDepthPass;
  8875. };
  8876. Engine.prototype.setStencilOperationFail = function (operation) {
  8877. this._stencilState.stencilOpStencilFail = operation;
  8878. };
  8879. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8880. this._stencilState.stencilOpDepthFail = operation;
  8881. };
  8882. Engine.prototype.setStencilOperationPass = function (operation) {
  8883. this._stencilState.stencilOpStencilDepthPass = operation;
  8884. };
  8885. Engine.prototype.setDitheringState = function (value) {
  8886. if (value) {
  8887. this._gl.enable(this._gl.DITHER);
  8888. }
  8889. else {
  8890. this._gl.disable(this._gl.DITHER);
  8891. }
  8892. };
  8893. /**
  8894. * stop executing a render loop function and remove it from the execution array
  8895. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8896. */
  8897. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8898. if (!renderFunction) {
  8899. this._activeRenderLoops = [];
  8900. return;
  8901. }
  8902. var index = this._activeRenderLoops.indexOf(renderFunction);
  8903. if (index >= 0) {
  8904. this._activeRenderLoops.splice(index, 1);
  8905. }
  8906. };
  8907. Engine.prototype._renderLoop = function () {
  8908. if (!this._contextWasLost) {
  8909. var shouldRender = true;
  8910. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8911. shouldRender = false;
  8912. }
  8913. if (shouldRender) {
  8914. // Start new frame
  8915. this.beginFrame();
  8916. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8917. var renderFunction = this._activeRenderLoops[index];
  8918. renderFunction();
  8919. }
  8920. // Present
  8921. this.endFrame();
  8922. }
  8923. }
  8924. if (this._activeRenderLoops.length > 0) {
  8925. // Register new frame
  8926. var requester = null;
  8927. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8928. requester = this._vrDisplay;
  8929. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8930. }
  8931. else {
  8932. this._renderingQueueLaunched = false;
  8933. }
  8934. };
  8935. /**
  8936. * Register and execute a render loop. The engine can have more than one render function.
  8937. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8938. * @example
  8939. * engine.runRenderLoop(function () {
  8940. * scene.render()
  8941. * })
  8942. */
  8943. Engine.prototype.runRenderLoop = function (renderFunction) {
  8944. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8945. return;
  8946. }
  8947. this._activeRenderLoops.push(renderFunction);
  8948. if (!this._renderingQueueLaunched) {
  8949. this._renderingQueueLaunched = true;
  8950. this._bindedRenderFunction = this._renderLoop.bind(this);
  8951. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8952. }
  8953. };
  8954. /**
  8955. * Toggle full screen mode.
  8956. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8957. * @param {any} options - an options object to be sent to the requestFullscreen function
  8958. */
  8959. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8960. if (this.isFullscreen) {
  8961. BABYLON.Tools.ExitFullscreen();
  8962. }
  8963. else {
  8964. this._pointerLockRequested = requestPointerLock;
  8965. if (this._renderingCanvas) {
  8966. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8967. }
  8968. }
  8969. };
  8970. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8971. if (stencil === void 0) { stencil = false; }
  8972. this.applyStates();
  8973. var mode = 0;
  8974. if (backBuffer && color) {
  8975. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8976. mode |= this._gl.COLOR_BUFFER_BIT;
  8977. }
  8978. if (depth) {
  8979. this._gl.clearDepth(1.0);
  8980. mode |= this._gl.DEPTH_BUFFER_BIT;
  8981. }
  8982. if (stencil) {
  8983. this._gl.clearStencil(0);
  8984. mode |= this._gl.STENCIL_BUFFER_BIT;
  8985. }
  8986. this._gl.clear(mode);
  8987. };
  8988. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8989. var gl = this._gl;
  8990. // Save state
  8991. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8992. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8993. // Change state
  8994. gl.enable(gl.SCISSOR_TEST);
  8995. gl.scissor(x, y, width, height);
  8996. // Clear
  8997. this.clear(clearColor, true, true, true);
  8998. // Restore state
  8999. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9000. if (curScissor === true) {
  9001. gl.enable(gl.SCISSOR_TEST);
  9002. }
  9003. else {
  9004. gl.disable(gl.SCISSOR_TEST);
  9005. }
  9006. };
  9007. /**
  9008. * Set the WebGL's viewport
  9009. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9010. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9011. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9012. */
  9013. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9014. var width = requiredWidth || this.getRenderWidth();
  9015. var height = requiredHeight || this.getRenderHeight();
  9016. var x = viewport.x || 0;
  9017. var y = viewport.y || 0;
  9018. this._cachedViewport = viewport;
  9019. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9020. };
  9021. /**
  9022. * Directly set the WebGL Viewport
  9023. * The x, y, width & height are directly passed to the WebGL call
  9024. * @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.
  9025. */
  9026. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9027. var currentViewport = this._cachedViewport;
  9028. this._cachedViewport = null;
  9029. this._gl.viewport(x, y, width, height);
  9030. return currentViewport;
  9031. };
  9032. Engine.prototype.beginFrame = function () {
  9033. this.onBeginFrameObservable.notifyObservers(this);
  9034. this._measureFps();
  9035. };
  9036. Engine.prototype.endFrame = function () {
  9037. //force a flush in case we are using a bad OS.
  9038. if (this._badOS) {
  9039. this.flushFramebuffer();
  9040. }
  9041. //submit frame to the vr device, if enabled
  9042. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9043. // TODO: We should only submit the frame if we read frameData successfully.
  9044. this._vrDisplay.submitFrame();
  9045. }
  9046. this.onEndFrameObservable.notifyObservers(this);
  9047. };
  9048. /**
  9049. * resize the view according to the canvas' size.
  9050. * @example
  9051. * window.addEventListener("resize", function () {
  9052. * engine.resize();
  9053. * });
  9054. */
  9055. Engine.prototype.resize = function () {
  9056. // We're not resizing the size of the canvas while in VR mode & presenting
  9057. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9058. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9059. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9060. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9061. }
  9062. };
  9063. /**
  9064. * force a specific size of the canvas
  9065. * @param {number} width - the new canvas' width
  9066. * @param {number} height - the new canvas' height
  9067. */
  9068. Engine.prototype.setSize = function (width, height) {
  9069. if (!this._renderingCanvas) {
  9070. return;
  9071. }
  9072. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9073. return;
  9074. }
  9075. this._renderingCanvas.width = width;
  9076. this._renderingCanvas.height = height;
  9077. for (var index = 0; index < this.scenes.length; index++) {
  9078. var scene = this.scenes[index];
  9079. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9080. var cam = scene.cameras[camIndex];
  9081. cam._currentRenderId = 0;
  9082. }
  9083. }
  9084. if (this.onResizeObservable.hasObservers) {
  9085. this.onResizeObservable.notifyObservers(this);
  9086. }
  9087. };
  9088. // WebVR functions
  9089. Engine.prototype.isVRDevicePresent = function () {
  9090. return !!this._vrDisplay;
  9091. };
  9092. Engine.prototype.getVRDevice = function () {
  9093. return this._vrDisplay;
  9094. };
  9095. Engine.prototype.initWebVR = function () {
  9096. var _this = this;
  9097. var notifyObservers = function () {
  9098. var eventArgs = {
  9099. vrDisplay: _this._vrDisplay,
  9100. vrSupported: _this._vrSupported
  9101. };
  9102. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9103. };
  9104. if (!this._onVrDisplayConnect) {
  9105. this._onVrDisplayConnect = function (event) {
  9106. _this._vrDisplay = event.display;
  9107. notifyObservers();
  9108. };
  9109. this._onVrDisplayDisconnect = function () {
  9110. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9111. _this._vrDisplay = undefined;
  9112. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9113. notifyObservers();
  9114. };
  9115. this._onVrDisplayPresentChange = function () {
  9116. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9117. };
  9118. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9119. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9120. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9121. }
  9122. this._getVRDisplays(notifyObservers);
  9123. return this.onVRDisplayChangedObservable;
  9124. };
  9125. Engine.prototype.enableVR = function () {
  9126. var _this = this;
  9127. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9128. var onResolved = function () {
  9129. _this.onVRRequestPresentComplete.notifyObservers(true);
  9130. _this._onVRFullScreenTriggered();
  9131. };
  9132. var onRejected = function () {
  9133. _this.onVRRequestPresentComplete.notifyObservers(false);
  9134. };
  9135. this.onVRRequestPresentStart.notifyObservers(this);
  9136. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9137. }
  9138. };
  9139. Engine.prototype.disableVR = function () {
  9140. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9141. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9142. }
  9143. };
  9144. Engine.prototype._getVRDisplays = function (callback) {
  9145. var _this = this;
  9146. var getWebVRDevices = function (devices) {
  9147. _this._vrSupported = true;
  9148. // note that devices may actually be an empty array. This is fine;
  9149. // we expect this._vrDisplay to be undefined in this case.
  9150. return _this._vrDisplay = devices[0];
  9151. };
  9152. if (navigator.getVRDisplays) {
  9153. // TODO: Backwards compatible for 1.0?
  9154. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9155. // TODO: System CANNOT support WebVR, despite API presence.
  9156. _this._vrSupported = false;
  9157. callback();
  9158. });
  9159. }
  9160. else {
  9161. // TODO: Browser does not support WebVR
  9162. this._vrDisplay = undefined;
  9163. this._vrSupported = false;
  9164. callback();
  9165. }
  9166. };
  9167. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9168. if (this._currentRenderTarget) {
  9169. this.unBindFramebuffer(this._currentRenderTarget);
  9170. }
  9171. this._currentRenderTarget = texture;
  9172. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9173. var gl = this._gl;
  9174. if (texture.isCube) {
  9175. if (faceIndex === undefined) {
  9176. faceIndex = 0;
  9177. }
  9178. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9179. }
  9180. if (this._cachedViewport && !forceFullscreenViewport) {
  9181. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9182. }
  9183. else {
  9184. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9185. }
  9186. this.wipeCaches();
  9187. };
  9188. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9189. if (this._currentFramebuffer !== framebuffer) {
  9190. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9191. this._currentFramebuffer = framebuffer;
  9192. }
  9193. };
  9194. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9195. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9196. this._currentRenderTarget = null;
  9197. // If MSAA, we need to bitblt back to main texture
  9198. var gl = this._gl;
  9199. if (texture._MSAAFramebuffer) {
  9200. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9201. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9202. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9203. }
  9204. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9205. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9206. gl.generateMipmap(gl.TEXTURE_2D);
  9207. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9208. }
  9209. if (onBeforeUnbind) {
  9210. if (texture._MSAAFramebuffer) {
  9211. // Bind the correct framebuffer
  9212. this.bindUnboundFramebuffer(texture._framebuffer);
  9213. }
  9214. onBeforeUnbind();
  9215. }
  9216. this.bindUnboundFramebuffer(null);
  9217. };
  9218. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9219. if (texture.generateMipMaps) {
  9220. var gl = this._gl;
  9221. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9222. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9223. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9224. }
  9225. };
  9226. Engine.prototype.flushFramebuffer = function () {
  9227. this._gl.flush();
  9228. };
  9229. Engine.prototype.restoreDefaultFramebuffer = function () {
  9230. if (this._currentRenderTarget) {
  9231. this.unBindFramebuffer(this._currentRenderTarget);
  9232. }
  9233. else {
  9234. this.bindUnboundFramebuffer(null);
  9235. }
  9236. if (this._cachedViewport) {
  9237. this.setViewport(this._cachedViewport);
  9238. }
  9239. this.wipeCaches();
  9240. };
  9241. // UBOs
  9242. Engine.prototype.createUniformBuffer = function (elements) {
  9243. var ubo = this._gl.createBuffer();
  9244. if (!ubo) {
  9245. throw new Error("Unable to create uniform buffer");
  9246. }
  9247. this.bindUniformBuffer(ubo);
  9248. if (elements instanceof Float32Array) {
  9249. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9250. }
  9251. else {
  9252. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9253. }
  9254. this.bindUniformBuffer(null);
  9255. ubo.references = 1;
  9256. return ubo;
  9257. };
  9258. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9259. var ubo = this._gl.createBuffer();
  9260. if (!ubo) {
  9261. throw new Error("Unable to create dynamic uniform buffer");
  9262. }
  9263. this.bindUniformBuffer(ubo);
  9264. if (elements instanceof Float32Array) {
  9265. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9266. }
  9267. else {
  9268. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9269. }
  9270. this.bindUniformBuffer(null);
  9271. ubo.references = 1;
  9272. return ubo;
  9273. };
  9274. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9275. this.bindUniformBuffer(uniformBuffer);
  9276. if (offset === undefined) {
  9277. offset = 0;
  9278. }
  9279. if (count === undefined) {
  9280. if (elements instanceof Float32Array) {
  9281. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9282. }
  9283. else {
  9284. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9285. }
  9286. }
  9287. else {
  9288. if (elements instanceof Float32Array) {
  9289. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9290. }
  9291. else {
  9292. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9293. }
  9294. }
  9295. this.bindUniformBuffer(null);
  9296. };
  9297. // VBOs
  9298. Engine.prototype._resetVertexBufferBinding = function () {
  9299. this.bindArrayBuffer(null);
  9300. this._cachedVertexBuffers = null;
  9301. };
  9302. Engine.prototype.createVertexBuffer = function (vertices) {
  9303. var vbo = this._gl.createBuffer();
  9304. if (!vbo) {
  9305. throw new Error("Unable to create vertex buffer");
  9306. }
  9307. this.bindArrayBuffer(vbo);
  9308. if (vertices instanceof Float32Array) {
  9309. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9310. }
  9311. else {
  9312. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9313. }
  9314. this._resetVertexBufferBinding();
  9315. vbo.references = 1;
  9316. return vbo;
  9317. };
  9318. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9319. var vbo = this._gl.createBuffer();
  9320. if (!vbo) {
  9321. throw new Error("Unable to create dynamic vertex buffer");
  9322. }
  9323. this.bindArrayBuffer(vbo);
  9324. if (vertices instanceof Float32Array) {
  9325. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9326. }
  9327. else {
  9328. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9329. }
  9330. this._resetVertexBufferBinding();
  9331. vbo.references = 1;
  9332. return vbo;
  9333. };
  9334. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9335. if (offset === void 0) { offset = 0; }
  9336. // Force cache update
  9337. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9338. this.bindIndexBuffer(indexBuffer);
  9339. var arrayBuffer;
  9340. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9341. arrayBuffer = indices;
  9342. }
  9343. else {
  9344. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9345. }
  9346. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9347. this._resetIndexBufferBinding();
  9348. };
  9349. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9350. this.bindArrayBuffer(vertexBuffer);
  9351. if (offset === undefined) {
  9352. offset = 0;
  9353. }
  9354. if (count === undefined) {
  9355. if (vertices instanceof Float32Array) {
  9356. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9357. }
  9358. else {
  9359. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9360. }
  9361. }
  9362. else {
  9363. if (vertices instanceof Float32Array) {
  9364. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9365. }
  9366. else {
  9367. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9368. }
  9369. }
  9370. this._resetVertexBufferBinding();
  9371. };
  9372. Engine.prototype._resetIndexBufferBinding = function () {
  9373. this.bindIndexBuffer(null);
  9374. this._cachedIndexBuffer = null;
  9375. };
  9376. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9377. var vbo = this._gl.createBuffer();
  9378. if (!vbo) {
  9379. throw new Error("Unable to create index buffer");
  9380. }
  9381. this.bindIndexBuffer(vbo);
  9382. // Check for 32 bits indices
  9383. var arrayBuffer;
  9384. var need32Bits = false;
  9385. if (indices instanceof Uint16Array) {
  9386. arrayBuffer = indices;
  9387. }
  9388. else {
  9389. //check 32 bit support
  9390. if (this._caps.uintIndices) {
  9391. if (indices instanceof Uint32Array) {
  9392. arrayBuffer = indices;
  9393. need32Bits = true;
  9394. }
  9395. else {
  9396. //number[] or Int32Array, check if 32 bit is necessary
  9397. for (var index = 0; index < indices.length; index++) {
  9398. if (indices[index] > 65535) {
  9399. need32Bits = true;
  9400. break;
  9401. }
  9402. }
  9403. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9404. }
  9405. }
  9406. else {
  9407. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9408. arrayBuffer = new Uint16Array(indices);
  9409. }
  9410. }
  9411. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9412. this._resetIndexBufferBinding();
  9413. vbo.references = 1;
  9414. vbo.is32Bits = need32Bits;
  9415. return vbo;
  9416. };
  9417. Engine.prototype.bindArrayBuffer = function (buffer) {
  9418. if (!this._vaoRecordInProgress) {
  9419. this._unbindVertexArrayObject();
  9420. }
  9421. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9422. };
  9423. Engine.prototype.bindUniformBuffer = function (buffer) {
  9424. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9425. };
  9426. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9427. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9428. };
  9429. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9430. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9431. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9432. };
  9433. ;
  9434. Engine.prototype.bindIndexBuffer = function (buffer) {
  9435. if (!this._vaoRecordInProgress) {
  9436. this._unbindVertexArrayObject();
  9437. }
  9438. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9439. };
  9440. Engine.prototype.bindBuffer = function (buffer, target) {
  9441. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9442. this._gl.bindBuffer(target, buffer);
  9443. this._currentBoundBuffer[target] = buffer;
  9444. }
  9445. };
  9446. Engine.prototype.updateArrayBuffer = function (data) {
  9447. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9448. };
  9449. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9450. var pointer = this._currentBufferPointers[indx];
  9451. var changed = false;
  9452. if (!pointer.active) {
  9453. changed = true;
  9454. pointer.active = true;
  9455. pointer.index = indx;
  9456. pointer.size = size;
  9457. pointer.type = type;
  9458. pointer.normalized = normalized;
  9459. pointer.stride = stride;
  9460. pointer.offset = offset;
  9461. pointer.buffer = buffer;
  9462. }
  9463. else {
  9464. if (pointer.buffer !== buffer) {
  9465. pointer.buffer = buffer;
  9466. changed = true;
  9467. }
  9468. if (pointer.size !== size) {
  9469. pointer.size = size;
  9470. changed = true;
  9471. }
  9472. if (pointer.type !== type) {
  9473. pointer.type = type;
  9474. changed = true;
  9475. }
  9476. if (pointer.normalized !== normalized) {
  9477. pointer.normalized = normalized;
  9478. changed = true;
  9479. }
  9480. if (pointer.stride !== stride) {
  9481. pointer.stride = stride;
  9482. changed = true;
  9483. }
  9484. if (pointer.offset !== offset) {
  9485. pointer.offset = offset;
  9486. changed = true;
  9487. }
  9488. }
  9489. if (changed || this._vaoRecordInProgress) {
  9490. this.bindArrayBuffer(buffer);
  9491. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9492. }
  9493. };
  9494. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9495. if (indexBuffer == null) {
  9496. return;
  9497. }
  9498. if (this._cachedIndexBuffer !== indexBuffer) {
  9499. this._cachedIndexBuffer = indexBuffer;
  9500. this.bindIndexBuffer(indexBuffer);
  9501. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9502. }
  9503. };
  9504. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9505. var attributes = effect.getAttributesNames();
  9506. if (!this._vaoRecordInProgress) {
  9507. this._unbindVertexArrayObject();
  9508. }
  9509. this.unbindAllAttributes();
  9510. for (var index = 0; index < attributes.length; index++) {
  9511. var order = effect.getAttributeLocation(index);
  9512. if (order >= 0) {
  9513. var vertexBuffer = vertexBuffers[attributes[index]];
  9514. if (!vertexBuffer) {
  9515. continue;
  9516. }
  9517. this._gl.enableVertexAttribArray(order);
  9518. if (!this._vaoRecordInProgress) {
  9519. this._vertexAttribArraysEnabled[order] = true;
  9520. }
  9521. var buffer = vertexBuffer.getBuffer();
  9522. if (buffer) {
  9523. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9524. if (vertexBuffer.getIsInstanced()) {
  9525. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9526. if (!this._vaoRecordInProgress) {
  9527. this._currentInstanceLocations.push(order);
  9528. this._currentInstanceBuffers.push(buffer);
  9529. }
  9530. }
  9531. }
  9532. }
  9533. }
  9534. };
  9535. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9536. var vao = this._gl.createVertexArray();
  9537. this._vaoRecordInProgress = true;
  9538. this._gl.bindVertexArray(vao);
  9539. this._mustWipeVertexAttributes = true;
  9540. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9541. this.bindIndexBuffer(indexBuffer);
  9542. this._vaoRecordInProgress = false;
  9543. this._gl.bindVertexArray(null);
  9544. return vao;
  9545. };
  9546. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9547. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9548. this._cachedVertexArrayObject = vertexArrayObject;
  9549. this._gl.bindVertexArray(vertexArrayObject);
  9550. this._cachedVertexBuffers = null;
  9551. this._cachedIndexBuffer = null;
  9552. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9553. this._mustWipeVertexAttributes = true;
  9554. }
  9555. };
  9556. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9557. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9558. this._cachedVertexBuffers = vertexBuffer;
  9559. this._cachedEffectForVertexBuffers = effect;
  9560. var attributesCount = effect.getAttributesCount();
  9561. this._unbindVertexArrayObject();
  9562. this.unbindAllAttributes();
  9563. var offset = 0;
  9564. for (var index = 0; index < attributesCount; index++) {
  9565. if (index < vertexDeclaration.length) {
  9566. var order = effect.getAttributeLocation(index);
  9567. if (order >= 0) {
  9568. this._gl.enableVertexAttribArray(order);
  9569. this._vertexAttribArraysEnabled[order] = true;
  9570. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9571. }
  9572. offset += vertexDeclaration[index] * 4;
  9573. }
  9574. }
  9575. }
  9576. this._bindIndexBufferWithCache(indexBuffer);
  9577. };
  9578. Engine.prototype._unbindVertexArrayObject = function () {
  9579. if (!this._cachedVertexArrayObject) {
  9580. return;
  9581. }
  9582. this._cachedVertexArrayObject = null;
  9583. this._gl.bindVertexArray(null);
  9584. };
  9585. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9586. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9587. this._cachedVertexBuffers = vertexBuffers;
  9588. this._cachedEffectForVertexBuffers = effect;
  9589. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9590. }
  9591. this._bindIndexBufferWithCache(indexBuffer);
  9592. };
  9593. Engine.prototype.unbindInstanceAttributes = function () {
  9594. var boundBuffer;
  9595. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9596. var instancesBuffer = this._currentInstanceBuffers[i];
  9597. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9598. boundBuffer = instancesBuffer;
  9599. this.bindArrayBuffer(instancesBuffer);
  9600. }
  9601. var offsetLocation = this._currentInstanceLocations[i];
  9602. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9603. }
  9604. this._currentInstanceBuffers.length = 0;
  9605. this._currentInstanceLocations.length = 0;
  9606. };
  9607. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9608. this._gl.deleteVertexArray(vao);
  9609. };
  9610. Engine.prototype._releaseBuffer = function (buffer) {
  9611. buffer.references--;
  9612. if (buffer.references === 0) {
  9613. this._gl.deleteBuffer(buffer);
  9614. return true;
  9615. }
  9616. return false;
  9617. };
  9618. Engine.prototype.createInstancesBuffer = function (capacity) {
  9619. var buffer = this._gl.createBuffer();
  9620. if (!buffer) {
  9621. throw new Error("Unable to create instance buffer");
  9622. }
  9623. buffer.capacity = capacity;
  9624. this.bindArrayBuffer(buffer);
  9625. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9626. return buffer;
  9627. };
  9628. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9629. this._gl.deleteBuffer(buffer);
  9630. };
  9631. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9632. this.bindArrayBuffer(instancesBuffer);
  9633. if (data) {
  9634. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9635. }
  9636. if (offsetLocations[0].index !== undefined) {
  9637. var stride = 0;
  9638. for (var i = 0; i < offsetLocations.length; i++) {
  9639. var ai = offsetLocations[i];
  9640. stride += ai.attributeSize * 4;
  9641. }
  9642. for (var i = 0; i < offsetLocations.length; i++) {
  9643. var ai = offsetLocations[i];
  9644. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9645. this._gl.enableVertexAttribArray(ai.index);
  9646. this._vertexAttribArraysEnabled[ai.index] = true;
  9647. }
  9648. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9649. this._gl.vertexAttribDivisor(ai.index, 1);
  9650. this._currentInstanceLocations.push(ai.index);
  9651. this._currentInstanceBuffers.push(instancesBuffer);
  9652. }
  9653. }
  9654. else {
  9655. for (var index = 0; index < 4; index++) {
  9656. var offsetLocation = offsetLocations[index];
  9657. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9658. this._gl.enableVertexAttribArray(offsetLocation);
  9659. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9660. }
  9661. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9662. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9663. this._currentInstanceLocations.push(offsetLocation);
  9664. this._currentInstanceBuffers.push(instancesBuffer);
  9665. }
  9666. }
  9667. };
  9668. Engine.prototype.applyStates = function () {
  9669. this._depthCullingState.apply(this._gl);
  9670. this._stencilState.apply(this._gl);
  9671. this._alphaState.apply(this._gl);
  9672. };
  9673. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9674. // Apply states
  9675. this.applyStates();
  9676. this._drawCalls.addCount(1, false);
  9677. // Render
  9678. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9679. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9680. if (instancesCount) {
  9681. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9682. return;
  9683. }
  9684. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9685. };
  9686. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9687. // Apply states
  9688. this.applyStates();
  9689. this._drawCalls.addCount(1, false);
  9690. if (instancesCount) {
  9691. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9692. return;
  9693. }
  9694. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9695. };
  9696. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9697. // Apply states
  9698. this.applyStates();
  9699. this._drawCalls.addCount(1, false);
  9700. if (instancesCount) {
  9701. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9702. return;
  9703. }
  9704. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9705. };
  9706. // Shaders
  9707. Engine.prototype._releaseEffect = function (effect) {
  9708. if (this._compiledEffects[effect._key]) {
  9709. delete this._compiledEffects[effect._key];
  9710. this._deleteProgram(effect.getProgram());
  9711. }
  9712. };
  9713. Engine.prototype._deleteProgram = function (program) {
  9714. if (program) {
  9715. program.__SPECTOR_rebuildProgram = null;
  9716. this._gl.deleteProgram(program);
  9717. }
  9718. };
  9719. /**
  9720. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9721. * @param samplers An array of string used to represent textures
  9722. */
  9723. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9724. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9725. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9726. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9727. if (this._compiledEffects[name]) {
  9728. var compiledEffect = this._compiledEffects[name];
  9729. if (onCompiled && compiledEffect.isReady()) {
  9730. onCompiled(compiledEffect);
  9731. }
  9732. return compiledEffect;
  9733. }
  9734. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9735. effect._key = name;
  9736. this._compiledEffects[name] = effect;
  9737. return effect;
  9738. };
  9739. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9740. if (uniformsNames === void 0) { uniformsNames = []; }
  9741. if (samplers === void 0) { samplers = []; }
  9742. if (defines === void 0) { defines = ""; }
  9743. return this.createEffect({
  9744. vertex: "particles",
  9745. fragmentElement: fragmentName
  9746. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9747. };
  9748. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context) {
  9749. context = context || this._gl;
  9750. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9751. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9752. return this._createShaderProgram(vertexShader, fragmentShader, context);
  9753. };
  9754. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9755. context = context || this._gl;
  9756. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9757. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9758. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9759. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9760. var program = this._createShaderProgram(vertexShader, fragmentShader, context);
  9761. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9762. return program;
  9763. };
  9764. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context) {
  9765. var shaderProgram = context.createProgram();
  9766. if (!shaderProgram) {
  9767. throw new Error("Unable to create program");
  9768. }
  9769. context.attachShader(shaderProgram, vertexShader);
  9770. context.attachShader(shaderProgram, fragmentShader);
  9771. context.linkProgram(shaderProgram);
  9772. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9773. if (!linked) {
  9774. context.validateProgram(shaderProgram);
  9775. var error = context.getProgramInfoLog(shaderProgram);
  9776. if (error) {
  9777. throw new Error(error);
  9778. }
  9779. }
  9780. context.deleteShader(vertexShader);
  9781. context.deleteShader(fragmentShader);
  9782. return shaderProgram;
  9783. };
  9784. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9785. var results = new Array();
  9786. for (var index = 0; index < uniformsNames.length; index++) {
  9787. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9788. }
  9789. return results;
  9790. };
  9791. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9792. var results = [];
  9793. for (var index = 0; index < attributesNames.length; index++) {
  9794. try {
  9795. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9796. }
  9797. catch (e) {
  9798. results.push(-1);
  9799. }
  9800. }
  9801. return results;
  9802. };
  9803. Engine.prototype.enableEffect = function (effect) {
  9804. if (!effect) {
  9805. return;
  9806. }
  9807. // Use program
  9808. this.setProgram(effect.getProgram());
  9809. this._currentEffect = effect;
  9810. if (effect.onBind) {
  9811. effect.onBind(effect);
  9812. }
  9813. effect.onBindObservable.notifyObservers(effect);
  9814. };
  9815. Engine.prototype.setIntArray = function (uniform, array) {
  9816. if (!uniform)
  9817. return;
  9818. this._gl.uniform1iv(uniform, array);
  9819. };
  9820. Engine.prototype.setIntArray2 = function (uniform, array) {
  9821. if (!uniform || array.length % 2 !== 0)
  9822. return;
  9823. this._gl.uniform2iv(uniform, array);
  9824. };
  9825. Engine.prototype.setIntArray3 = function (uniform, array) {
  9826. if (!uniform || array.length % 3 !== 0)
  9827. return;
  9828. this._gl.uniform3iv(uniform, array);
  9829. };
  9830. Engine.prototype.setIntArray4 = function (uniform, array) {
  9831. if (!uniform || array.length % 4 !== 0)
  9832. return;
  9833. this._gl.uniform4iv(uniform, array);
  9834. };
  9835. Engine.prototype.setFloatArray = function (uniform, array) {
  9836. if (!uniform)
  9837. return;
  9838. this._gl.uniform1fv(uniform, array);
  9839. };
  9840. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9841. if (!uniform || array.length % 2 !== 0)
  9842. return;
  9843. this._gl.uniform2fv(uniform, array);
  9844. };
  9845. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9846. if (!uniform || array.length % 3 !== 0)
  9847. return;
  9848. this._gl.uniform3fv(uniform, array);
  9849. };
  9850. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9851. if (!uniform || array.length % 4 !== 0)
  9852. return;
  9853. this._gl.uniform4fv(uniform, array);
  9854. };
  9855. Engine.prototype.setArray = function (uniform, array) {
  9856. if (!uniform)
  9857. return;
  9858. this._gl.uniform1fv(uniform, array);
  9859. };
  9860. Engine.prototype.setArray2 = function (uniform, array) {
  9861. if (!uniform || array.length % 2 !== 0)
  9862. return;
  9863. this._gl.uniform2fv(uniform, array);
  9864. };
  9865. Engine.prototype.setArray3 = function (uniform, array) {
  9866. if (!uniform || array.length % 3 !== 0)
  9867. return;
  9868. this._gl.uniform3fv(uniform, array);
  9869. };
  9870. Engine.prototype.setArray4 = function (uniform, array) {
  9871. if (!uniform || array.length % 4 !== 0)
  9872. return;
  9873. this._gl.uniform4fv(uniform, array);
  9874. };
  9875. Engine.prototype.setMatrices = function (uniform, matrices) {
  9876. if (!uniform)
  9877. return;
  9878. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9879. };
  9880. Engine.prototype.setMatrix = function (uniform, matrix) {
  9881. if (!uniform)
  9882. return;
  9883. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9884. };
  9885. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9886. if (!uniform)
  9887. return;
  9888. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9889. };
  9890. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9891. if (!uniform)
  9892. return;
  9893. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9894. };
  9895. Engine.prototype.setFloat = function (uniform, value) {
  9896. if (!uniform)
  9897. return;
  9898. this._gl.uniform1f(uniform, value);
  9899. };
  9900. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9901. if (!uniform)
  9902. return;
  9903. this._gl.uniform2f(uniform, x, y);
  9904. };
  9905. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9906. if (!uniform)
  9907. return;
  9908. this._gl.uniform3f(uniform, x, y, z);
  9909. };
  9910. Engine.prototype.setBool = function (uniform, bool) {
  9911. if (!uniform)
  9912. return;
  9913. this._gl.uniform1i(uniform, bool);
  9914. };
  9915. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9916. if (!uniform)
  9917. return;
  9918. this._gl.uniform4f(uniform, x, y, z, w);
  9919. };
  9920. Engine.prototype.setColor3 = function (uniform, color3) {
  9921. if (!uniform)
  9922. return;
  9923. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9924. };
  9925. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9926. if (!uniform)
  9927. return;
  9928. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9929. };
  9930. // States
  9931. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9932. if (zOffset === void 0) { zOffset = 0; }
  9933. if (reverseSide === void 0) { reverseSide = false; }
  9934. // Culling
  9935. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9936. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9937. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9938. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9939. if (culling) {
  9940. this._depthCullingState.cullFace = cullFace;
  9941. this._depthCullingState.cull = true;
  9942. }
  9943. else {
  9944. this._depthCullingState.cull = false;
  9945. }
  9946. }
  9947. // Z offset
  9948. this.setZOffset(zOffset);
  9949. };
  9950. Engine.prototype.setZOffset = function (value) {
  9951. this._depthCullingState.zOffset = value;
  9952. };
  9953. Engine.prototype.getZOffset = function () {
  9954. return this._depthCullingState.zOffset;
  9955. };
  9956. Engine.prototype.setDepthBuffer = function (enable) {
  9957. this._depthCullingState.depthTest = enable;
  9958. };
  9959. Engine.prototype.getDepthWrite = function () {
  9960. return this._depthCullingState.depthMask;
  9961. };
  9962. Engine.prototype.setDepthWrite = function (enable) {
  9963. this._depthCullingState.depthMask = enable;
  9964. };
  9965. Engine.prototype.setColorWrite = function (enable) {
  9966. this._gl.colorMask(enable, enable, enable, enable);
  9967. this._colorWrite = enable;
  9968. };
  9969. Engine.prototype.getColorWrite = function () {
  9970. return this._colorWrite;
  9971. };
  9972. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9973. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9974. };
  9975. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9976. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9977. if (this._alphaMode === mode) {
  9978. return;
  9979. }
  9980. switch (mode) {
  9981. case Engine.ALPHA_DISABLE:
  9982. this._alphaState.alphaBlend = false;
  9983. break;
  9984. case Engine.ALPHA_PREMULTIPLIED:
  9985. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9986. this._alphaState.alphaBlend = true;
  9987. break;
  9988. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9989. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9990. this._alphaState.alphaBlend = true;
  9991. break;
  9992. case Engine.ALPHA_COMBINE:
  9993. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9994. this._alphaState.alphaBlend = true;
  9995. break;
  9996. case Engine.ALPHA_ONEONE:
  9997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9998. this._alphaState.alphaBlend = true;
  9999. break;
  10000. case Engine.ALPHA_ADD:
  10001. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10002. this._alphaState.alphaBlend = true;
  10003. break;
  10004. case Engine.ALPHA_SUBTRACT:
  10005. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10006. this._alphaState.alphaBlend = true;
  10007. break;
  10008. case Engine.ALPHA_MULTIPLY:
  10009. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10010. this._alphaState.alphaBlend = true;
  10011. break;
  10012. case Engine.ALPHA_MAXIMIZED:
  10013. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10014. this._alphaState.alphaBlend = true;
  10015. break;
  10016. case Engine.ALPHA_INTERPOLATE:
  10017. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10018. this._alphaState.alphaBlend = true;
  10019. break;
  10020. case Engine.ALPHA_SCREENMODE:
  10021. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10022. this._alphaState.alphaBlend = true;
  10023. break;
  10024. }
  10025. if (!noDepthWriteChange) {
  10026. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10027. }
  10028. this._alphaMode = mode;
  10029. };
  10030. Engine.prototype.getAlphaMode = function () {
  10031. return this._alphaMode;
  10032. };
  10033. Engine.prototype.setAlphaTesting = function (enable) {
  10034. this._alphaTest = enable;
  10035. };
  10036. Engine.prototype.getAlphaTesting = function () {
  10037. return !!this._alphaTest;
  10038. };
  10039. // Textures
  10040. Engine.prototype.wipeCaches = function (bruteForce) {
  10041. if (this.preventCacheWipeBetweenFrames) {
  10042. return;
  10043. }
  10044. this.resetTextureCache();
  10045. this._currentEffect = null;
  10046. // 6/8/2017: deltakosh: Should not be required anymore.
  10047. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10048. if (bruteForce) {
  10049. this._currentProgram = null;
  10050. this._stencilState.reset();
  10051. this._depthCullingState.reset();
  10052. this.setDepthFunctionToLessOrEqual();
  10053. this._alphaState.reset();
  10054. }
  10055. this._cachedVertexBuffers = null;
  10056. this._cachedIndexBuffer = null;
  10057. this._cachedEffectForVertexBuffers = null;
  10058. this._unbindVertexArrayObject();
  10059. this.bindIndexBuffer(null);
  10060. this.bindArrayBuffer(null);
  10061. };
  10062. /**
  10063. * Set the compressed texture format to use, based on the formats you have, and the formats
  10064. * supported by the hardware / browser.
  10065. *
  10066. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10067. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10068. * to API arguments needed to compressed textures. This puts the burden on the container
  10069. * generator to house the arcane code for determining these for current & future formats.
  10070. *
  10071. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10072. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10073. *
  10074. * Note: The result of this call is not taken into account when a texture is base64.
  10075. *
  10076. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10077. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10078. *
  10079. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10080. * @returns The extension selected.
  10081. */
  10082. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10083. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10084. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10085. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10086. return this._textureFormatInUse = this._texturesSupported[i];
  10087. }
  10088. }
  10089. }
  10090. // actively set format to nothing, to allow this to be called more than once
  10091. // and possibly fail the 2nd time
  10092. this._textureFormatInUse = null;
  10093. return null;
  10094. };
  10095. Engine.prototype._createTexture = function () {
  10096. var texture = this._gl.createTexture();
  10097. if (!texture) {
  10098. throw new Error("Unable to create texture");
  10099. }
  10100. return texture;
  10101. };
  10102. /**
  10103. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10104. * @param {string} urlArg- This contains one of the following:
  10105. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10106. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10107. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10108. *
  10109. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10110. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10111. * @param {Scene} scene- Needed for loading to the correct scene.
  10112. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10113. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10114. * @param {callback} onError- Optional callback to be called upon failure.
  10115. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10116. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10117. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10118. *
  10119. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10120. */
  10121. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10122. var _this = this;
  10123. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10124. if (onLoad === void 0) { onLoad = null; }
  10125. if (onError === void 0) { onError = null; }
  10126. if (buffer === void 0) { buffer = null; }
  10127. if (fallBack === void 0) { fallBack = null; }
  10128. if (format === void 0) { format = null; }
  10129. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10130. var fromData = url.substr(0, 5) === "data:";
  10131. var fromBlob = url.substr(0, 5) === "blob:";
  10132. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10133. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10134. // establish the file extension, if possible
  10135. var lastDot = url.lastIndexOf('.');
  10136. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10137. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10138. var isTGA = (extension === ".tga");
  10139. // determine if a ktx file should be substituted
  10140. var isKTX = false;
  10141. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10142. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10143. isKTX = true;
  10144. }
  10145. if (scene) {
  10146. scene._addPendingData(texture);
  10147. }
  10148. texture.url = url;
  10149. texture.generateMipMaps = !noMipmap;
  10150. texture.samplingMode = samplingMode;
  10151. texture.invertY = invertY;
  10152. if (!this._doNotHandleContextLost) {
  10153. // Keep a link to the buffer only if we plan to handle context lost
  10154. texture._buffer = buffer;
  10155. }
  10156. if (onLoad) {
  10157. texture.onLoadedObservable.add(onLoad);
  10158. }
  10159. if (!fallBack)
  10160. this._internalTexturesCache.push(texture);
  10161. var onerror = function () {
  10162. if (scene) {
  10163. scene._removePendingData(texture);
  10164. }
  10165. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10166. if (isKTX) {
  10167. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10168. }
  10169. else if (onError) {
  10170. onError();
  10171. }
  10172. };
  10173. var callback = null;
  10174. // processing for non-image formats
  10175. if (isKTX || isTGA || isDDS) {
  10176. if (isKTX) {
  10177. callback = function (data) {
  10178. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10179. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10180. ktx.uploadLevels(_this._gl, !noMipmap);
  10181. return false;
  10182. }, samplingMode);
  10183. };
  10184. }
  10185. else if (isTGA) {
  10186. callback = function (arrayBuffer) {
  10187. var data = new Uint8Array(arrayBuffer);
  10188. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10189. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10190. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10191. return false;
  10192. }, samplingMode);
  10193. };
  10194. }
  10195. else if (isDDS) {
  10196. callback = function (data) {
  10197. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10198. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10199. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10200. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10201. return false;
  10202. }, samplingMode);
  10203. };
  10204. }
  10205. if (!buffer) {
  10206. BABYLON.Tools.LoadFile(url, function (data) {
  10207. if (callback) {
  10208. callback(data);
  10209. }
  10210. }, undefined, scene ? scene.database : undefined, true, onerror);
  10211. }
  10212. else {
  10213. if (callback) {
  10214. callback(buffer);
  10215. }
  10216. }
  10217. // image format processing
  10218. }
  10219. else {
  10220. var onload = function (img) {
  10221. if (fromBlob && !_this._doNotHandleContextLost) {
  10222. // We need to store the image if we need to rebuild the texture
  10223. // in case of a webgl context lost
  10224. texture._buffer = img;
  10225. }
  10226. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10227. var gl = _this._gl;
  10228. var isPot = (img.width === potWidth && img.height === potHeight);
  10229. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10230. if (isPot) {
  10231. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10232. return false;
  10233. }
  10234. // Using shaders to rescale because canvas.drawImage is lossy
  10235. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10236. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10237. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10242. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10243. _this._releaseTexture(source);
  10244. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10245. continuationCallback();
  10246. });
  10247. return true;
  10248. }, samplingMode);
  10249. };
  10250. if (!fromData || isBase64)
  10251. if (buffer instanceof HTMLImageElement) {
  10252. onload(buffer);
  10253. }
  10254. else {
  10255. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10256. }
  10257. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10258. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10259. else
  10260. onload(buffer);
  10261. }
  10262. return texture;
  10263. };
  10264. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10265. var _this = this;
  10266. var rtt = this.createRenderTargetTexture({
  10267. width: destination.width,
  10268. height: destination.height,
  10269. }, {
  10270. generateMipMaps: false,
  10271. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10272. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10273. generateDepthBuffer: false,
  10274. generateStencilBuffer: false
  10275. });
  10276. if (!this._rescalePostProcess) {
  10277. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10278. }
  10279. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10280. _this._rescalePostProcess.onApply = function (effect) {
  10281. effect._bindTexture("textureSampler", source);
  10282. };
  10283. var hostingScene = scene;
  10284. if (!hostingScene) {
  10285. hostingScene = _this.scenes[_this.scenes.length - 1];
  10286. }
  10287. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10288. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10289. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10290. _this.unBindFramebuffer(rtt);
  10291. _this._releaseTexture(rtt);
  10292. if (onComplete) {
  10293. onComplete();
  10294. }
  10295. });
  10296. };
  10297. Engine.prototype._getInternalFormat = function (format) {
  10298. var internalFormat = this._gl.RGBA;
  10299. switch (format) {
  10300. case Engine.TEXTUREFORMAT_ALPHA:
  10301. internalFormat = this._gl.ALPHA;
  10302. break;
  10303. case Engine.TEXTUREFORMAT_LUMINANCE:
  10304. internalFormat = this._gl.LUMINANCE;
  10305. break;
  10306. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10307. internalFormat = this._gl.LUMINANCE_ALPHA;
  10308. break;
  10309. case Engine.TEXTUREFORMAT_RGB:
  10310. internalFormat = this._gl.RGB;
  10311. break;
  10312. case Engine.TEXTUREFORMAT_RGBA:
  10313. internalFormat = this._gl.RGBA;
  10314. break;
  10315. }
  10316. return internalFormat;
  10317. };
  10318. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10319. if (compression === void 0) { compression = null; }
  10320. if (!texture) {
  10321. return;
  10322. }
  10323. var internalFormat = this._getInternalFormat(format);
  10324. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10325. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10326. if (!this._doNotHandleContextLost) {
  10327. texture._bufferView = data;
  10328. texture.format = format;
  10329. texture.invertY = invertY;
  10330. texture._compression = compression;
  10331. }
  10332. if (texture.width % 4 !== 0) {
  10333. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10334. }
  10335. if (compression && data) {
  10336. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10337. }
  10338. else {
  10339. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10340. }
  10341. if (texture.generateMipMaps) {
  10342. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10343. }
  10344. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10345. this.resetTextureCache();
  10346. texture.isReady = true;
  10347. };
  10348. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10349. if (compression === void 0) { compression = null; }
  10350. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10351. texture.baseWidth = width;
  10352. texture.baseHeight = height;
  10353. texture.width = width;
  10354. texture.height = height;
  10355. texture.format = format;
  10356. texture.generateMipMaps = generateMipMaps;
  10357. texture.samplingMode = samplingMode;
  10358. texture.invertY = invertY;
  10359. texture._compression = compression;
  10360. if (!this._doNotHandleContextLost) {
  10361. texture._bufferView = data;
  10362. }
  10363. this.updateRawTexture(texture, data, format, invertY, compression);
  10364. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10365. // Filters
  10366. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10367. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10368. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10369. if (generateMipMaps) {
  10370. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10371. }
  10372. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10373. this._internalTexturesCache.push(texture);
  10374. return texture;
  10375. };
  10376. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10377. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10378. texture.baseWidth = width;
  10379. texture.baseHeight = height;
  10380. if (generateMipMaps) {
  10381. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10382. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10383. }
  10384. this.resetTextureCache();
  10385. texture.width = width;
  10386. texture.height = height;
  10387. texture.isReady = false;
  10388. texture.generateMipMaps = generateMipMaps;
  10389. texture.samplingMode = samplingMode;
  10390. this.updateTextureSamplingMode(samplingMode, texture);
  10391. this._internalTexturesCache.push(texture);
  10392. return texture;
  10393. };
  10394. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10395. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10396. if (texture.isCube) {
  10397. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10398. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10399. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10400. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10401. }
  10402. else if (texture.is3D) {
  10403. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10404. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10405. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10406. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10407. }
  10408. else {
  10409. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10410. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10411. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10412. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10413. }
  10414. texture.samplingMode = samplingMode;
  10415. };
  10416. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10417. if (premulAlpha === void 0) { premulAlpha = false; }
  10418. if (!texture) {
  10419. return;
  10420. }
  10421. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10422. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10423. if (premulAlpha) {
  10424. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10425. }
  10426. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10427. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10428. if (texture.generateMipMaps) {
  10429. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10430. }
  10431. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10432. if (premulAlpha) {
  10433. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10434. }
  10435. this.resetTextureCache();
  10436. texture.isReady = true;
  10437. };
  10438. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10439. if (!texture || texture._isDisabled) {
  10440. return;
  10441. }
  10442. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10443. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10444. try {
  10445. // Testing video texture support
  10446. if (this._videoTextureSupported === undefined) {
  10447. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10448. if (this._gl.getError() !== 0) {
  10449. this._videoTextureSupported = false;
  10450. }
  10451. else {
  10452. this._videoTextureSupported = true;
  10453. }
  10454. }
  10455. // Copy video through the current working canvas if video texture is not supported
  10456. if (!this._videoTextureSupported) {
  10457. if (!texture._workingCanvas) {
  10458. texture._workingCanvas = document.createElement("canvas");
  10459. var context = texture._workingCanvas.getContext("2d");
  10460. if (!context) {
  10461. throw new Error("Unable to get 2d context");
  10462. }
  10463. texture._workingContext = context;
  10464. texture._workingCanvas.width = texture.width;
  10465. texture._workingCanvas.height = texture.height;
  10466. }
  10467. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10468. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10469. }
  10470. else {
  10471. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10472. }
  10473. if (texture.generateMipMaps) {
  10474. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10475. }
  10476. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10477. this.resetTextureCache();
  10478. texture.isReady = true;
  10479. }
  10480. catch (ex) {
  10481. // Something unexpected
  10482. // Let's disable the texture
  10483. texture._isDisabled = true;
  10484. }
  10485. };
  10486. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10487. var fullOptions = new RenderTargetCreationOptions();
  10488. if (options !== undefined && typeof options === "object") {
  10489. fullOptions.generateMipMaps = options.generateMipMaps;
  10490. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10491. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10492. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10493. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10494. }
  10495. else {
  10496. fullOptions.generateMipMaps = options;
  10497. fullOptions.generateDepthBuffer = true;
  10498. fullOptions.generateStencilBuffer = false;
  10499. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10500. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10501. }
  10502. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10503. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10504. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10505. }
  10506. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10507. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10508. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10509. }
  10510. var gl = this._gl;
  10511. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10512. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10513. var width = size.width || size;
  10514. var height = size.height || size;
  10515. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10516. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10517. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10518. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10519. }
  10520. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10521. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10522. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10523. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10524. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10525. // Create the framebuffer
  10526. var framebuffer = gl.createFramebuffer();
  10527. this.bindUnboundFramebuffer(framebuffer);
  10528. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10529. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10530. if (fullOptions.generateMipMaps) {
  10531. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10532. }
  10533. // Unbind
  10534. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10535. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10536. this.bindUnboundFramebuffer(null);
  10537. texture._framebuffer = framebuffer;
  10538. texture.baseWidth = width;
  10539. texture.baseHeight = height;
  10540. texture.width = width;
  10541. texture.height = height;
  10542. texture.isReady = true;
  10543. texture.samples = 1;
  10544. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10545. texture.samplingMode = fullOptions.samplingMode;
  10546. texture.type = fullOptions.type;
  10547. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10548. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10549. this.resetTextureCache();
  10550. this._internalTexturesCache.push(texture);
  10551. return texture;
  10552. };
  10553. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10554. var generateMipMaps = false;
  10555. var generateDepthBuffer = true;
  10556. var generateStencilBuffer = false;
  10557. var generateDepthTexture = false;
  10558. var textureCount = 1;
  10559. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10560. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10561. var types = [], samplingModes = [];
  10562. if (options !== undefined) {
  10563. generateMipMaps = options.generateMipMaps;
  10564. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10565. generateStencilBuffer = options.generateStencilBuffer;
  10566. generateDepthTexture = options.generateDepthTexture;
  10567. textureCount = options.textureCount || 1;
  10568. if (options.types) {
  10569. types = options.types;
  10570. }
  10571. if (options.samplingModes) {
  10572. samplingModes = options.samplingModes;
  10573. }
  10574. }
  10575. var gl = this._gl;
  10576. // Create the framebuffer
  10577. var framebuffer = gl.createFramebuffer();
  10578. this.bindUnboundFramebuffer(framebuffer);
  10579. var width = size.width || size;
  10580. var height = size.height || size;
  10581. var textures = [];
  10582. var attachments = [];
  10583. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10584. for (var i = 0; i < textureCount; i++) {
  10585. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10586. var type = types[i] || defaultType;
  10587. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10588. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10589. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10590. }
  10591. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10592. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10593. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10594. }
  10595. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10596. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10597. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10598. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10599. }
  10600. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10601. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10602. textures.push(texture);
  10603. attachments.push(attachment);
  10604. gl.activeTexture(gl["TEXTURE" + i]);
  10605. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10606. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10607. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10608. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10610. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10611. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10612. if (generateMipMaps) {
  10613. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10614. }
  10615. // Unbind
  10616. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10617. texture._framebuffer = framebuffer;
  10618. texture._depthStencilBuffer = depthStencilBuffer;
  10619. texture.baseWidth = width;
  10620. texture.baseHeight = height;
  10621. texture.width = width;
  10622. texture.height = height;
  10623. texture.isReady = true;
  10624. texture.samples = 1;
  10625. texture.generateMipMaps = generateMipMaps;
  10626. texture.samplingMode = samplingMode;
  10627. texture.type = type;
  10628. texture._generateDepthBuffer = generateDepthBuffer;
  10629. texture._generateStencilBuffer = generateStencilBuffer;
  10630. this._internalTexturesCache.push(texture);
  10631. }
  10632. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10633. // Depth texture
  10634. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10635. gl.activeTexture(gl.TEXTURE0);
  10636. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10637. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10638. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10639. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10640. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10641. 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);
  10642. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10643. depthTexture._framebuffer = framebuffer;
  10644. depthTexture.baseWidth = width;
  10645. depthTexture.baseHeight = height;
  10646. depthTexture.width = width;
  10647. depthTexture.height = height;
  10648. depthTexture.isReady = true;
  10649. depthTexture.samples = 1;
  10650. depthTexture.generateMipMaps = generateMipMaps;
  10651. depthTexture.samplingMode = gl.NEAREST;
  10652. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10653. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10654. textures.push(depthTexture);
  10655. this._internalTexturesCache.push(depthTexture);
  10656. }
  10657. gl.drawBuffers(attachments);
  10658. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10659. this.bindUnboundFramebuffer(null);
  10660. this.resetTextureCache();
  10661. return textures;
  10662. };
  10663. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10664. if (samples === void 0) { samples = 1; }
  10665. var depthStencilBuffer = null;
  10666. var gl = this._gl;
  10667. // Create the depth/stencil buffer
  10668. if (generateStencilBuffer) {
  10669. depthStencilBuffer = gl.createRenderbuffer();
  10670. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10671. if (samples > 1) {
  10672. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10673. }
  10674. else {
  10675. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10676. }
  10677. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10678. }
  10679. else if (generateDepthBuffer) {
  10680. depthStencilBuffer = gl.createRenderbuffer();
  10681. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10682. if (samples > 1) {
  10683. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10684. }
  10685. else {
  10686. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10687. }
  10688. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10689. }
  10690. return depthStencilBuffer;
  10691. };
  10692. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10693. if (this.webGLVersion < 2 || !texture) {
  10694. return 1;
  10695. }
  10696. if (texture.samples === samples) {
  10697. return samples;
  10698. }
  10699. var gl = this._gl;
  10700. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10701. // Dispose previous render buffers
  10702. if (texture._depthStencilBuffer) {
  10703. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10704. }
  10705. if (texture._MSAAFramebuffer) {
  10706. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10707. }
  10708. if (texture._MSAARenderBuffer) {
  10709. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10710. }
  10711. if (samples > 1) {
  10712. var framebuffer = gl.createFramebuffer();
  10713. if (!framebuffer) {
  10714. throw new Error("Unable to create multi sampled framebuffer");
  10715. }
  10716. texture._MSAAFramebuffer = framebuffer;
  10717. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10718. var colorRenderbuffer = gl.createRenderbuffer();
  10719. if (!colorRenderbuffer) {
  10720. throw new Error("Unable to create multi sampled framebuffer");
  10721. }
  10722. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10723. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10724. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10725. texture._MSAARenderBuffer = colorRenderbuffer;
  10726. }
  10727. else {
  10728. this.bindUnboundFramebuffer(texture._framebuffer);
  10729. }
  10730. texture.samples = samples;
  10731. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10732. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10733. this.bindUnboundFramebuffer(null);
  10734. return samples;
  10735. };
  10736. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10737. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10738. };
  10739. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10740. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10741. };
  10742. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10743. var gl = this._gl;
  10744. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10745. var generateMipMaps = true;
  10746. var generateDepthBuffer = true;
  10747. var generateStencilBuffer = false;
  10748. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10749. if (options !== undefined) {
  10750. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10751. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10752. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10753. if (options.samplingMode !== undefined) {
  10754. samplingMode = options.samplingMode;
  10755. }
  10756. }
  10757. texture.isCube = true;
  10758. texture.generateMipMaps = generateMipMaps;
  10759. texture.samples = 1;
  10760. texture.samplingMode = samplingMode;
  10761. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10762. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10763. for (var face = 0; face < 6; face++) {
  10764. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10765. }
  10766. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10767. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10768. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10770. // Create the framebuffer
  10771. var framebuffer = gl.createFramebuffer();
  10772. this.bindUnboundFramebuffer(framebuffer);
  10773. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10774. // Mipmaps
  10775. if (texture.generateMipMaps) {
  10776. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10777. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10778. }
  10779. // Unbind
  10780. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10781. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10782. this.bindUnboundFramebuffer(null);
  10783. texture._framebuffer = framebuffer;
  10784. texture.width = size;
  10785. texture.height = size;
  10786. texture.isReady = true;
  10787. this.resetTextureCache();
  10788. this._internalTexturesCache.push(texture);
  10789. return texture;
  10790. };
  10791. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10792. var _this = this;
  10793. if (onLoad === void 0) { onLoad = null; }
  10794. if (onError === void 0) { onError = null; }
  10795. if (forcedExtension === void 0) { forcedExtension = null; }
  10796. var callback = function (loadData) {
  10797. if (!loadData) {
  10798. if (onLoad) {
  10799. onLoad(null);
  10800. }
  10801. return;
  10802. }
  10803. var texture = loadData.texture;
  10804. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10805. texture._lodGenerationScale = scale;
  10806. texture._lodGenerationOffset = offset;
  10807. if (_this._caps.textureLOD) {
  10808. // Do not add extra process if texture lod is supported.
  10809. if (onLoad) {
  10810. onLoad(texture);
  10811. }
  10812. return;
  10813. }
  10814. var mipSlices = 3;
  10815. var gl = _this._gl;
  10816. var width = loadData.width;
  10817. if (!width) {
  10818. return;
  10819. }
  10820. var textures = [];
  10821. for (var i = 0; i < mipSlices; i++) {
  10822. //compute LOD from even spacing in smoothness (matching shader calculation)
  10823. var smoothness = i / (mipSlices - 1);
  10824. var roughness = 1 - smoothness;
  10825. var minLODIndex = offset; // roughness = 0
  10826. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10827. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10828. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10829. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10830. glTextureFromLod.isCube = true;
  10831. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10832. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10833. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10836. if (loadData.isDDS) {
  10837. var info = loadData.info;
  10838. var data = loadData.data;
  10839. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10840. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10841. }
  10842. else {
  10843. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10844. }
  10845. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10846. // Wrap in a base texture for easy binding.
  10847. var lodTexture = new BABYLON.BaseTexture(scene);
  10848. lodTexture.isCube = true;
  10849. lodTexture._texture = glTextureFromLod;
  10850. glTextureFromLod.isReady = true;
  10851. textures.push(lodTexture);
  10852. }
  10853. texture._lodTextureHigh = textures[2];
  10854. texture._lodTextureMid = textures[1];
  10855. texture._lodTextureLow = textures[0];
  10856. if (onLoad) {
  10857. onLoad(texture);
  10858. }
  10859. };
  10860. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10861. };
  10862. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10863. var _this = this;
  10864. if (onLoad === void 0) { onLoad = null; }
  10865. if (onError === void 0) { onError = null; }
  10866. if (forcedExtension === void 0) { forcedExtension = null; }
  10867. var gl = this._gl;
  10868. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10869. texture.isCube = true;
  10870. texture.url = rootUrl;
  10871. texture.generateMipMaps = !noMipmap;
  10872. if (!this._doNotHandleContextLost) {
  10873. texture._extension = forcedExtension;
  10874. texture._files = files;
  10875. }
  10876. var isKTX = false;
  10877. var isDDS = false;
  10878. var lastDot = rootUrl.lastIndexOf('.');
  10879. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  10880. if (this._textureFormatInUse) {
  10881. extension = this._textureFormatInUse;
  10882. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  10883. isKTX = true;
  10884. }
  10885. else {
  10886. isDDS = (extension === ".dds");
  10887. }
  10888. var onerror = function (request, exception) {
  10889. if (onError) {
  10890. onError(request.status + " " + request.statusText, exception);
  10891. }
  10892. };
  10893. if (isKTX) {
  10894. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10895. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10896. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10897. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10898. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10899. ktx.uploadLevels(_this._gl, !noMipmap);
  10900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10903. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10904. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10905. _this.resetTextureCache();
  10906. texture.width = ktx.pixelWidth;
  10907. texture.height = ktx.pixelHeight;
  10908. texture.isReady = true;
  10909. }, undefined, undefined, true, onerror);
  10910. }
  10911. else if (isDDS) {
  10912. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10913. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10914. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10915. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10916. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10917. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10918. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10919. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10920. }
  10921. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10922. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10923. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10924. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10925. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10926. _this.resetTextureCache();
  10927. texture.width = info.width;
  10928. texture.height = info.height;
  10929. texture.isReady = true;
  10930. texture.type = info.textureType;
  10931. if (onLoad) {
  10932. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10933. }
  10934. }, undefined, undefined, true, onerror);
  10935. }
  10936. else {
  10937. if (!files) {
  10938. throw new Error("Cannot load cubemap because files were not defined");
  10939. }
  10940. cascadeLoad(rootUrl, scene, function (imgs) {
  10941. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10942. var height = width;
  10943. _this._prepareWorkingCanvas();
  10944. if (!_this._workingCanvas || !_this._workingContext) {
  10945. return;
  10946. }
  10947. _this._workingCanvas.width = width;
  10948. _this._workingCanvas.height = height;
  10949. var faces = [
  10950. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10951. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10952. ];
  10953. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10954. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10955. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10956. for (var index = 0; index < faces.length; index++) {
  10957. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10958. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10959. }
  10960. if (!noMipmap) {
  10961. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10962. }
  10963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10965. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10966. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10967. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10968. _this.resetTextureCache();
  10969. texture.width = width;
  10970. texture.height = height;
  10971. texture.isReady = true;
  10972. if (format) {
  10973. texture.format = format;
  10974. }
  10975. texture.onLoadedObservable.notifyObservers(texture);
  10976. texture.onLoadedObservable.clear();
  10977. if (onLoad) {
  10978. onLoad();
  10979. }
  10980. }, files, onError);
  10981. }
  10982. this._internalTexturesCache.push(texture);
  10983. return texture;
  10984. };
  10985. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10986. if (compression === void 0) { compression = null; }
  10987. if (level === void 0) { level = 0; }
  10988. texture._bufferViewArray = data;
  10989. texture.format = format;
  10990. texture.type = type;
  10991. texture.invertY = invertY;
  10992. texture._compression = compression;
  10993. var gl = this._gl;
  10994. var textureType = this._getWebGLTextureType(type);
  10995. var internalFormat = this._getInternalFormat(format);
  10996. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10997. var needConversion = false;
  10998. if (internalFormat === gl.RGB) {
  10999. internalFormat = gl.RGBA;
  11000. needConversion = true;
  11001. }
  11002. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11003. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11004. if (texture.width % 4 !== 0) {
  11005. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11006. }
  11007. // Data are known to be in +X +Y +Z -X -Y -Z
  11008. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11009. var faceData = data[faceIndex];
  11010. if (compression) {
  11011. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11012. }
  11013. else {
  11014. if (needConversion) {
  11015. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11016. }
  11017. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11018. }
  11019. }
  11020. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11021. if (isPot && texture.generateMipMaps && level === 0) {
  11022. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11023. }
  11024. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11025. this.resetTextureCache();
  11026. texture.isReady = true;
  11027. };
  11028. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11029. if (compression === void 0) { compression = null; }
  11030. var gl = this._gl;
  11031. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11032. texture.isCube = true;
  11033. texture.generateMipMaps = generateMipMaps;
  11034. texture.format = format;
  11035. texture.type = type;
  11036. if (!this._doNotHandleContextLost) {
  11037. texture._bufferViewArray = data;
  11038. }
  11039. var textureType = this._getWebGLTextureType(type);
  11040. var internalFormat = this._getInternalFormat(format);
  11041. var needConversion = false;
  11042. if (internalFormat === gl.RGB) {
  11043. internalFormat = gl.RGBA;
  11044. needConversion = true;
  11045. }
  11046. var width = size;
  11047. var height = width;
  11048. texture.width = width;
  11049. texture.height = height;
  11050. // Double check on POT to generate Mips.
  11051. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11052. if (!isPot) {
  11053. generateMipMaps = false;
  11054. }
  11055. // Upload data if needed. The texture won't be ready until then.
  11056. if (data) {
  11057. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11058. }
  11059. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11060. // Filters
  11061. if (data && generateMipMaps) {
  11062. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11063. }
  11064. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11065. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11067. }
  11068. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11070. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11071. }
  11072. else {
  11073. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11076. }
  11077. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11078. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11079. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11080. return texture;
  11081. };
  11082. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11083. var _this = this;
  11084. if (onLoad === void 0) { onLoad = null; }
  11085. if (onError === void 0) { onError = null; }
  11086. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11087. if (invertY === void 0) { invertY = false; }
  11088. var gl = this._gl;
  11089. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11090. scene._addPendingData(texture);
  11091. texture.url = url;
  11092. this._internalTexturesCache.push(texture);
  11093. var onerror = function (request, exception) {
  11094. scene._removePendingData(texture);
  11095. if (onError) {
  11096. onError(request.status + " " + request.statusText, exception);
  11097. }
  11098. };
  11099. var internalCallback = function (data) {
  11100. var width = texture.width;
  11101. var faceDataArrays = callback(data);
  11102. if (!faceDataArrays) {
  11103. return;
  11104. }
  11105. if (mipmmapGenerator) {
  11106. var textureType = _this._getWebGLTextureType(type);
  11107. var internalFormat = _this._getInternalFormat(format);
  11108. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11109. var needConversion = false;
  11110. if (internalFormat === gl.RGB) {
  11111. internalFormat = gl.RGBA;
  11112. needConversion = true;
  11113. }
  11114. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11115. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11116. var mipData = mipmmapGenerator(faceDataArrays);
  11117. for (var level = 0; level < mipData.length; level++) {
  11118. var mipSize = width >> level;
  11119. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11120. var mipFaceData = mipData[level][faceIndex];
  11121. if (needConversion) {
  11122. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11123. }
  11124. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11125. }
  11126. }
  11127. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11128. }
  11129. else {
  11130. texture.generateMipMaps = !noMipmap;
  11131. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11132. }
  11133. texture.isReady = true;
  11134. _this.resetTextureCache();
  11135. scene._removePendingData(texture);
  11136. if (onLoad) {
  11137. onLoad();
  11138. }
  11139. };
  11140. BABYLON.Tools.LoadFile(url, function (data) {
  11141. internalCallback(data);
  11142. }, undefined, scene.database, true, onerror);
  11143. return texture;
  11144. };
  11145. ;
  11146. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11147. if (compression === void 0) { compression = null; }
  11148. var internalFormat = this._getInternalFormat(format);
  11149. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11150. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11151. if (!this._doNotHandleContextLost) {
  11152. texture._bufferView = data;
  11153. texture.format = format;
  11154. texture.invertY = invertY;
  11155. texture._compression = compression;
  11156. }
  11157. if (texture.width % 4 !== 0) {
  11158. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11159. }
  11160. if (compression && data) {
  11161. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11162. }
  11163. else {
  11164. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11165. }
  11166. if (texture.generateMipMaps) {
  11167. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11168. }
  11169. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11170. this.resetTextureCache();
  11171. texture.isReady = true;
  11172. };
  11173. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11174. if (compression === void 0) { compression = null; }
  11175. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11176. texture.baseWidth = width;
  11177. texture.baseHeight = height;
  11178. texture.baseDepth = depth;
  11179. texture.width = width;
  11180. texture.height = height;
  11181. texture.depth = depth;
  11182. texture.format = format;
  11183. texture.generateMipMaps = generateMipMaps;
  11184. texture.samplingMode = samplingMode;
  11185. texture.is3D = true;
  11186. if (!this._doNotHandleContextLost) {
  11187. texture._bufferView = data;
  11188. }
  11189. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11190. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11191. // Filters
  11192. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11193. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11194. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11195. if (generateMipMaps) {
  11196. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11197. }
  11198. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11199. this._internalTexturesCache.push(texture);
  11200. return texture;
  11201. };
  11202. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11203. var gl = this._gl;
  11204. if (!gl) {
  11205. return;
  11206. }
  11207. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11208. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11209. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11210. if (!noMipmap && !isCompressed) {
  11211. gl.generateMipmap(gl.TEXTURE_2D);
  11212. }
  11213. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11214. this.resetTextureCache();
  11215. if (scene) {
  11216. scene._removePendingData(texture);
  11217. }
  11218. texture.onLoadedObservable.notifyObservers(texture);
  11219. texture.onLoadedObservable.clear();
  11220. };
  11221. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11222. var _this = this;
  11223. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11224. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11225. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11226. var gl = this._gl;
  11227. if (!gl) {
  11228. return;
  11229. }
  11230. if (!texture._webGLTexture) {
  11231. this.resetTextureCache();
  11232. if (scene) {
  11233. scene._removePendingData(texture);
  11234. }
  11235. return;
  11236. }
  11237. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11238. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11239. texture.baseWidth = width;
  11240. texture.baseHeight = height;
  11241. texture.width = potWidth;
  11242. texture.height = potHeight;
  11243. texture.isReady = true;
  11244. if (processFunction(potWidth, potHeight, function () {
  11245. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11246. })) {
  11247. // Returning as texture needs extra async steps
  11248. return;
  11249. }
  11250. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11251. };
  11252. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11253. // Create new RGBA data container.
  11254. var rgbaData;
  11255. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11256. rgbaData = new Float32Array(width * height * 4);
  11257. }
  11258. else {
  11259. rgbaData = new Uint32Array(width * height * 4);
  11260. }
  11261. // Convert each pixel.
  11262. for (var x = 0; x < width; x++) {
  11263. for (var y = 0; y < height; y++) {
  11264. var index = (y * width + x) * 3;
  11265. var newIndex = (y * width + x) * 4;
  11266. // Map Old Value to new value.
  11267. rgbaData[newIndex + 0] = rgbData[index + 0];
  11268. rgbaData[newIndex + 1] = rgbData[index + 1];
  11269. rgbaData[newIndex + 2] = rgbData[index + 2];
  11270. // Add fully opaque alpha channel.
  11271. rgbaData[newIndex + 3] = 1;
  11272. }
  11273. }
  11274. return rgbaData;
  11275. };
  11276. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11277. var gl = this._gl;
  11278. if (texture._framebuffer) {
  11279. gl.deleteFramebuffer(texture._framebuffer);
  11280. texture._framebuffer = null;
  11281. }
  11282. if (texture._depthStencilBuffer) {
  11283. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11284. texture._depthStencilBuffer = null;
  11285. }
  11286. if (texture._MSAAFramebuffer) {
  11287. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11288. texture._MSAAFramebuffer = null;
  11289. }
  11290. if (texture._MSAARenderBuffer) {
  11291. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11292. texture._MSAARenderBuffer = null;
  11293. }
  11294. };
  11295. Engine.prototype._releaseTexture = function (texture) {
  11296. var gl = this._gl;
  11297. this._releaseFramebufferObjects(texture);
  11298. gl.deleteTexture(texture._webGLTexture);
  11299. // Unbind channels
  11300. this.unbindAllTextures();
  11301. var index = this._internalTexturesCache.indexOf(texture);
  11302. if (index !== -1) {
  11303. this._internalTexturesCache.splice(index, 1);
  11304. }
  11305. // Integrated fixed lod samplers.
  11306. if (texture._lodTextureHigh) {
  11307. texture._lodTextureHigh.dispose();
  11308. }
  11309. if (texture._lodTextureMid) {
  11310. texture._lodTextureMid.dispose();
  11311. }
  11312. if (texture._lodTextureLow) {
  11313. texture._lodTextureLow.dispose();
  11314. }
  11315. };
  11316. Engine.prototype.setProgram = function (program) {
  11317. if (this._currentProgram !== program) {
  11318. this._gl.useProgram(program);
  11319. this._currentProgram = program;
  11320. }
  11321. };
  11322. Engine.prototype.bindSamplers = function (effect) {
  11323. this.setProgram(effect.getProgram());
  11324. var samplers = effect.getSamplers();
  11325. for (var index = 0; index < samplers.length; index++) {
  11326. var uniform = effect.getUniform(samplers[index]);
  11327. this._gl.uniform1i(uniform, index);
  11328. }
  11329. this._currentEffect = null;
  11330. };
  11331. Engine.prototype.activateTexture = function (texture) {
  11332. if (this._activeTexture !== texture) {
  11333. this._gl.activeTexture(texture);
  11334. this._activeTexture = texture;
  11335. }
  11336. };
  11337. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11338. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  11339. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11340. this._activeTexturesCache[this._activeTexture] = texture;
  11341. }
  11342. };
  11343. Engine.prototype._bindTexture = function (channel, texture) {
  11344. if (channel < 0) {
  11345. return;
  11346. }
  11347. this.activateTexture(this._gl.TEXTURE0 + channel);
  11348. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11349. };
  11350. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11351. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11352. };
  11353. Engine.prototype.unbindAllTextures = function () {
  11354. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11355. this.activateTexture(this._gl["TEXTURE" + channel]);
  11356. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11357. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11358. if (this.webGLVersion > 1) {
  11359. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11360. }
  11361. }
  11362. };
  11363. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11364. if (channel < 0) {
  11365. return;
  11366. }
  11367. this._gl.uniform1i(uniform, channel);
  11368. this._setTexture(channel, texture);
  11369. };
  11370. Engine.prototype._setTexture = function (channel, texture) {
  11371. // Not ready?
  11372. if (!texture) {
  11373. if (this._activeTexturesCache[channel] != null) {
  11374. this.activateTexture(this._gl["TEXTURE" + channel]);
  11375. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11376. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11377. if (this.webGLVersion > 1) {
  11378. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11379. }
  11380. }
  11381. return;
  11382. }
  11383. // Video
  11384. var alreadyActivated = false;
  11385. if (texture.video) {
  11386. this.activateTexture(this._gl["TEXTURE" + channel]);
  11387. alreadyActivated = true;
  11388. texture.update();
  11389. }
  11390. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11391. texture.delayLoad();
  11392. return;
  11393. }
  11394. var internalTexture;
  11395. if (texture.isReady()) {
  11396. internalTexture = texture.getInternalTexture();
  11397. }
  11398. else if (texture.isCube) {
  11399. internalTexture = this.emptyCubeTexture;
  11400. }
  11401. else if (texture.is3D) {
  11402. internalTexture = this.emptyTexture3D;
  11403. }
  11404. else {
  11405. internalTexture = this.emptyTexture;
  11406. }
  11407. if (this._activeTexturesCache[channel] === internalTexture) {
  11408. return;
  11409. }
  11410. if (!alreadyActivated) {
  11411. this.activateTexture(this._gl["TEXTURE" + channel]);
  11412. }
  11413. if (internalTexture && internalTexture.is3D) {
  11414. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11415. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11416. internalTexture._cachedWrapU = texture.wrapU;
  11417. switch (texture.wrapU) {
  11418. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11419. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11420. break;
  11421. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11422. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11423. break;
  11424. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11425. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11426. break;
  11427. }
  11428. }
  11429. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11430. internalTexture._cachedWrapV = texture.wrapV;
  11431. switch (texture.wrapV) {
  11432. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11433. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11434. break;
  11435. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11436. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11437. break;
  11438. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11439. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11440. break;
  11441. }
  11442. }
  11443. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11444. internalTexture._cachedWrapR = texture.wrapR;
  11445. switch (texture.wrapV) {
  11446. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11447. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11448. break;
  11449. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11450. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11451. break;
  11452. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11453. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11454. break;
  11455. }
  11456. }
  11457. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11458. }
  11459. else if (internalTexture && internalTexture.isCube) {
  11460. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11461. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11462. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11463. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11464. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11465. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11466. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11467. }
  11468. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11469. }
  11470. else {
  11471. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11472. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11473. internalTexture._cachedWrapU = texture.wrapU;
  11474. switch (texture.wrapU) {
  11475. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11476. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11477. break;
  11478. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11479. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11480. break;
  11481. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11482. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11483. break;
  11484. }
  11485. }
  11486. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11487. internalTexture._cachedWrapV = texture.wrapV;
  11488. switch (texture.wrapV) {
  11489. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11490. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11491. break;
  11492. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11493. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11494. break;
  11495. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11496. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11497. break;
  11498. }
  11499. }
  11500. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11501. }
  11502. };
  11503. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11504. if (channel < 0 || !uniform) {
  11505. return;
  11506. }
  11507. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11508. this._textureUnits = new Int32Array(textures.length);
  11509. }
  11510. for (var i = 0; i < textures.length; i++) {
  11511. this._textureUnits[i] = channel + i;
  11512. }
  11513. this._gl.uniform1iv(uniform, this._textureUnits);
  11514. for (var index = 0; index < textures.length; index++) {
  11515. this._setTexture(channel + index, textures[index]);
  11516. }
  11517. };
  11518. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11519. var internalTexture = texture.getInternalTexture();
  11520. if (!internalTexture) {
  11521. return;
  11522. }
  11523. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11524. var value = texture.anisotropicFilteringLevel;
  11525. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11526. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11527. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11528. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11529. }
  11530. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11531. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11532. internalTexture._cachedAnisotropicFilteringLevel = value;
  11533. }
  11534. };
  11535. Engine.prototype.readPixels = function (x, y, width, height) {
  11536. var data = new Uint8Array(height * width * 4);
  11537. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11538. return data;
  11539. };
  11540. /**
  11541. * Add an externaly attached data from its key.
  11542. * This method call will fail and return false, if such key already exists.
  11543. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11544. * @param key the unique key that identifies the data
  11545. * @param data the data object to associate to the key for this Engine instance
  11546. * @return true if no such key were already present and the data was added successfully, false otherwise
  11547. */
  11548. Engine.prototype.addExternalData = function (key, data) {
  11549. if (!this._externalData) {
  11550. this._externalData = new BABYLON.StringDictionary();
  11551. }
  11552. return this._externalData.add(key, data);
  11553. };
  11554. /**
  11555. * Get an externaly attached data from its key
  11556. * @param key the unique key that identifies the data
  11557. * @return the associated data, if present (can be null), or undefined if not present
  11558. */
  11559. Engine.prototype.getExternalData = function (key) {
  11560. if (!this._externalData) {
  11561. this._externalData = new BABYLON.StringDictionary();
  11562. }
  11563. return this._externalData.get(key);
  11564. };
  11565. /**
  11566. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11567. * @param key the unique key that identifies the data
  11568. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11569. * @return the associated data, can be null if the factory returned null.
  11570. */
  11571. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11572. if (!this._externalData) {
  11573. this._externalData = new BABYLON.StringDictionary();
  11574. }
  11575. return this._externalData.getOrAddWithFactory(key, factory);
  11576. };
  11577. /**
  11578. * Remove an externaly attached data from the Engine instance
  11579. * @param key the unique key that identifies the data
  11580. * @return true if the data was successfully removed, false if it doesn't exist
  11581. */
  11582. Engine.prototype.removeExternalData = function (key) {
  11583. if (!this._externalData) {
  11584. this._externalData = new BABYLON.StringDictionary();
  11585. }
  11586. return this._externalData.remove(key);
  11587. };
  11588. Engine.prototype.unbindAllAttributes = function () {
  11589. if (this._mustWipeVertexAttributes) {
  11590. this._mustWipeVertexAttributes = false;
  11591. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11592. this._gl.disableVertexAttribArray(i);
  11593. this._vertexAttribArraysEnabled[i] = false;
  11594. this._currentBufferPointers[i].active = false;
  11595. }
  11596. return;
  11597. }
  11598. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11599. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11600. continue;
  11601. }
  11602. this._gl.disableVertexAttribArray(i);
  11603. this._vertexAttribArraysEnabled[i] = false;
  11604. this._currentBufferPointers[i].active = false;
  11605. }
  11606. };
  11607. Engine.prototype.releaseEffects = function () {
  11608. for (var name in this._compiledEffects) {
  11609. this._deleteProgram(this._compiledEffects[name]._program);
  11610. }
  11611. this._compiledEffects = {};
  11612. };
  11613. // Dispose
  11614. Engine.prototype.dispose = function () {
  11615. this.hideLoadingUI();
  11616. this.stopRenderLoop();
  11617. // Release postProcesses
  11618. while (this.postProcesses.length) {
  11619. this.postProcesses[0].dispose();
  11620. }
  11621. // Empty texture
  11622. if (this._emptyTexture) {
  11623. this._releaseTexture(this._emptyTexture);
  11624. this._emptyTexture = null;
  11625. }
  11626. if (this._emptyCubeTexture) {
  11627. this._releaseTexture(this._emptyCubeTexture);
  11628. this._emptyCubeTexture = null;
  11629. }
  11630. // Rescale PP
  11631. if (this._rescalePostProcess) {
  11632. this._rescalePostProcess.dispose();
  11633. }
  11634. // Release scenes
  11635. while (this.scenes.length) {
  11636. this.scenes[0].dispose();
  11637. }
  11638. // Release audio engine
  11639. if (Engine.audioEngine) {
  11640. Engine.audioEngine.dispose();
  11641. }
  11642. // Release effects
  11643. this.releaseEffects();
  11644. // Unbind
  11645. this.unbindAllAttributes();
  11646. if (this._dummyFramebuffer) {
  11647. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11648. }
  11649. //WebVR
  11650. this.disableVR();
  11651. // Events
  11652. window.removeEventListener("blur", this._onBlur);
  11653. window.removeEventListener("focus", this._onFocus);
  11654. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11655. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11656. if (this._renderingCanvas) {
  11657. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11658. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11659. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11660. if (!this._doNotHandleContextLost) {
  11661. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11662. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11663. }
  11664. }
  11665. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11666. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11667. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11668. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11669. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11670. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11671. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11672. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11673. if (this._onVrDisplayConnect) {
  11674. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11675. if (this._onVrDisplayDisconnect) {
  11676. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11677. }
  11678. if (this._onVrDisplayPresentChange) {
  11679. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11680. }
  11681. this._onVrDisplayConnect = null;
  11682. this._onVrDisplayDisconnect = null;
  11683. }
  11684. // Remove from Instances
  11685. var index = Engine.Instances.indexOf(this);
  11686. if (index >= 0) {
  11687. Engine.Instances.splice(index, 1);
  11688. }
  11689. this._workingCanvas = null;
  11690. this._workingContext = null;
  11691. this._currentBufferPointers = [];
  11692. this._renderingCanvas = null;
  11693. this._currentProgram = null;
  11694. this.onResizeObservable.clear();
  11695. this.onCanvasBlurObservable.clear();
  11696. this.onCanvasFocusObservable.clear();
  11697. this.onCanvasPointerOutObservable.clear();
  11698. this.onBeginFrameObservable.clear();
  11699. this.onEndFrameObservable.clear();
  11700. BABYLON.Effect.ResetCache();
  11701. };
  11702. // Loading screen
  11703. Engine.prototype.displayLoadingUI = function () {
  11704. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11705. return;
  11706. }
  11707. var loadingScreen = this.loadingScreen;
  11708. if (loadingScreen) {
  11709. loadingScreen.displayLoadingUI();
  11710. }
  11711. };
  11712. Engine.prototype.hideLoadingUI = function () {
  11713. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11714. return;
  11715. }
  11716. var loadingScreen = this.loadingScreen;
  11717. if (loadingScreen) {
  11718. loadingScreen.hideLoadingUI();
  11719. }
  11720. };
  11721. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11722. get: function () {
  11723. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11724. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11725. return this._loadingScreen;
  11726. },
  11727. set: function (loadingScreen) {
  11728. this._loadingScreen = loadingScreen;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11734. set: function (text) {
  11735. this.loadingScreen.loadingUIText = text;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11741. set: function (color) {
  11742. this.loadingScreen.loadingUIBackgroundColor = color;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Engine.prototype.attachContextLostEvent = function (callback) {
  11748. if (this._renderingCanvas) {
  11749. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11750. }
  11751. };
  11752. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11753. if (this._renderingCanvas) {
  11754. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11755. }
  11756. };
  11757. Engine.prototype.getVertexShaderSource = function (program) {
  11758. var shaders = this._gl.getAttachedShaders(program);
  11759. if (!shaders) {
  11760. return null;
  11761. }
  11762. return this._gl.getShaderSource(shaders[0]);
  11763. };
  11764. Engine.prototype.getFragmentShaderSource = function (program) {
  11765. var shaders = this._gl.getAttachedShaders(program);
  11766. if (!shaders) {
  11767. return null;
  11768. }
  11769. return this._gl.getShaderSource(shaders[1]);
  11770. };
  11771. Engine.prototype.getError = function () {
  11772. return this._gl.getError();
  11773. };
  11774. // FPS
  11775. Engine.prototype.getFps = function () {
  11776. return this._fps;
  11777. };
  11778. Engine.prototype.getDeltaTime = function () {
  11779. return this._deltaTime;
  11780. };
  11781. Engine.prototype._measureFps = function () {
  11782. this._performanceMonitor.sampleFrame();
  11783. this._fps = this._performanceMonitor.averageFPS;
  11784. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11785. };
  11786. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11787. if (faceIndex === void 0) { faceIndex = -1; }
  11788. var gl = this._gl;
  11789. if (!this._dummyFramebuffer) {
  11790. var dummy = gl.createFramebuffer();
  11791. if (!dummy) {
  11792. throw new Error("Unable to create dummy framebuffer");
  11793. }
  11794. this._dummyFramebuffer = dummy;
  11795. }
  11796. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11797. if (faceIndex > -1) {
  11798. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11799. }
  11800. else {
  11801. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11802. }
  11803. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11804. var buffer;
  11805. switch (readType) {
  11806. case gl.UNSIGNED_BYTE:
  11807. buffer = new Uint8Array(4 * width * height);
  11808. readType = gl.UNSIGNED_BYTE;
  11809. break;
  11810. default:
  11811. buffer = new Float32Array(4 * width * height);
  11812. readType = gl.FLOAT;
  11813. break;
  11814. }
  11815. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11816. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11817. return buffer;
  11818. };
  11819. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11820. if (this._webGLVersion > 1) {
  11821. return this._caps.colorBufferFloat;
  11822. }
  11823. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11824. };
  11825. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11826. if (this._webGLVersion > 1) {
  11827. return this._caps.colorBufferFloat;
  11828. }
  11829. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11830. };
  11831. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11832. Engine.prototype._canRenderToFramebuffer = function (type) {
  11833. var gl = this._gl;
  11834. //clear existing errors
  11835. while (gl.getError() !== gl.NO_ERROR) { }
  11836. var successful = true;
  11837. var texture = gl.createTexture();
  11838. gl.bindTexture(gl.TEXTURE_2D, texture);
  11839. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11840. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11841. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11842. var fb = gl.createFramebuffer();
  11843. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11844. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11845. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11846. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11847. successful = successful && (gl.getError() === gl.NO_ERROR);
  11848. //try render by clearing frame buffer's color buffer
  11849. if (successful) {
  11850. gl.clear(gl.COLOR_BUFFER_BIT);
  11851. successful = successful && (gl.getError() === gl.NO_ERROR);
  11852. }
  11853. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11854. if (successful) {
  11855. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11856. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11857. var readFormat = gl.RGBA;
  11858. var readType = gl.UNSIGNED_BYTE;
  11859. var buffer = new Uint8Array(4);
  11860. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11861. successful = successful && (gl.getError() === gl.NO_ERROR);
  11862. }
  11863. //clean up
  11864. gl.deleteTexture(texture);
  11865. gl.deleteFramebuffer(fb);
  11866. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11867. //clear accumulated errors
  11868. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11869. return successful;
  11870. };
  11871. Engine.prototype._getWebGLTextureType = function (type) {
  11872. if (type === Engine.TEXTURETYPE_FLOAT) {
  11873. return this._gl.FLOAT;
  11874. }
  11875. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11876. // Add Half Float Constant.
  11877. return this._gl.HALF_FLOAT_OES;
  11878. }
  11879. return this._gl.UNSIGNED_BYTE;
  11880. };
  11881. ;
  11882. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11883. if (this._webGLVersion === 1) {
  11884. return this._gl.RGBA;
  11885. }
  11886. if (type === Engine.TEXTURETYPE_FLOAT) {
  11887. return this._gl.RGBA32F;
  11888. }
  11889. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11890. return this._gl.RGBA16F;
  11891. }
  11892. return this._gl.RGBA;
  11893. };
  11894. ;
  11895. Engine.prototype.createQuery = function () {
  11896. return this._gl.createQuery();
  11897. };
  11898. Engine.prototype.deleteQuery = function (query) {
  11899. this._gl.deleteQuery(query);
  11900. return this;
  11901. };
  11902. Engine.prototype.isQueryResultAvailable = function (query) {
  11903. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11904. };
  11905. Engine.prototype.getQueryResult = function (query) {
  11906. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11907. };
  11908. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  11909. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11910. this._gl.beginQuery(glAlgorithm, query);
  11911. return this;
  11912. };
  11913. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  11914. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11915. this._gl.endQuery(glAlgorithm);
  11916. return this;
  11917. };
  11918. /* Time queries */
  11919. Engine.prototype._createTimeQuery = function () {
  11920. var timerQuery = this._caps.timerQuery;
  11921. if (timerQuery.createQueryEXT) {
  11922. return timerQuery.createQueryEXT();
  11923. }
  11924. return this.createQuery();
  11925. };
  11926. Engine.prototype._deleteTimeQuery = function (query) {
  11927. var timerQuery = this._caps.timerQuery;
  11928. if (timerQuery.deleteQueryEXT) {
  11929. timerQuery.deleteQueryEXT(query);
  11930. return;
  11931. }
  11932. this.deleteQuery(query);
  11933. };
  11934. Engine.prototype._getTimeQueryResult = function (query) {
  11935. var timerQuery = this._caps.timerQuery;
  11936. if (timerQuery.getQueryObjectEXT) {
  11937. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  11938. }
  11939. return this.getQueryResult(query);
  11940. };
  11941. Engine.prototype._getTimeQueryAvailability = function (query) {
  11942. var timerQuery = this._caps.timerQuery;
  11943. if (timerQuery.getQueryObjectEXT) {
  11944. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  11945. }
  11946. return this.isQueryResultAvailable(query);
  11947. };
  11948. Engine.prototype.startTimeQuery = function () {
  11949. var timerQuery = this._caps.timerQuery;
  11950. if (!timerQuery) {
  11951. return null;
  11952. }
  11953. var token = new BABYLON._TimeToken();
  11954. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  11955. if (this._caps.canUseTimestampForTimerQuery) {
  11956. token._startTimeQuery = this._createTimeQuery();
  11957. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  11958. }
  11959. else {
  11960. token._timeElapsedQuery = this._createTimeQuery();
  11961. if (timerQuery.beginQueryEXT) {
  11962. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  11963. }
  11964. else {
  11965. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  11966. }
  11967. }
  11968. return token;
  11969. };
  11970. Engine.prototype.endTimeQuery = function (token) {
  11971. var timerQuery = this._caps.timerQuery;
  11972. if (!timerQuery || !token) {
  11973. return -1;
  11974. }
  11975. if (this._caps.canUseTimestampForTimerQuery) {
  11976. if (!token._startTimeQuery) {
  11977. return -1;
  11978. }
  11979. if (!token._endTimeQuery) {
  11980. token._endTimeQuery = this._createTimeQuery();
  11981. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  11982. }
  11983. }
  11984. else if (!token._timeElapsedQueryEnded) {
  11985. if (!token._timeElapsedQuery) {
  11986. return -1;
  11987. }
  11988. if (timerQuery.endQueryEXT) {
  11989. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  11990. }
  11991. else {
  11992. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  11993. }
  11994. token._timeElapsedQueryEnded = true;
  11995. }
  11996. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  11997. var available = false;
  11998. if (token._endTimeQuery) {
  11999. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12000. }
  12001. else if (token._timeElapsedQuery) {
  12002. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12003. }
  12004. if (available && !disjoint) {
  12005. var result = 0;
  12006. if (this._caps.canUseTimestampForTimerQuery) {
  12007. if (!token._startTimeQuery || !token._endTimeQuery) {
  12008. return -1;
  12009. }
  12010. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12011. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12012. result = timeEnd - timeStart;
  12013. this._deleteTimeQuery(token._startTimeQuery);
  12014. this._deleteTimeQuery(token._endTimeQuery);
  12015. token._startTimeQuery = null;
  12016. token._endTimeQuery = null;
  12017. }
  12018. else {
  12019. if (!token._timeElapsedQuery) {
  12020. return -1;
  12021. }
  12022. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12023. this._deleteTimeQuery(token._timeElapsedQuery);
  12024. token._timeElapsedQuery = null;
  12025. token._timeElapsedQueryEnded = false;
  12026. }
  12027. return result;
  12028. }
  12029. return -1;
  12030. };
  12031. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12032. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12033. };
  12034. // Statics
  12035. Engine.isSupported = function () {
  12036. try {
  12037. var tempcanvas = document.createElement("canvas");
  12038. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12039. return gl != null && !!window.WebGLRenderingContext;
  12040. }
  12041. catch (e) {
  12042. return false;
  12043. }
  12044. };
  12045. Engine.Instances = new Array();
  12046. // Const statics
  12047. Engine._ALPHA_DISABLE = 0;
  12048. Engine._ALPHA_ADD = 1;
  12049. Engine._ALPHA_COMBINE = 2;
  12050. Engine._ALPHA_SUBTRACT = 3;
  12051. Engine._ALPHA_MULTIPLY = 4;
  12052. Engine._ALPHA_MAXIMIZED = 5;
  12053. Engine._ALPHA_ONEONE = 6;
  12054. Engine._ALPHA_PREMULTIPLIED = 7;
  12055. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12056. Engine._ALPHA_INTERPOLATE = 9;
  12057. Engine._ALPHA_SCREENMODE = 10;
  12058. Engine._DELAYLOADSTATE_NONE = 0;
  12059. Engine._DELAYLOADSTATE_LOADED = 1;
  12060. Engine._DELAYLOADSTATE_LOADING = 2;
  12061. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12062. Engine._TEXTUREFORMAT_ALPHA = 0;
  12063. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12064. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12065. Engine._TEXTUREFORMAT_RGB = 4;
  12066. Engine._TEXTUREFORMAT_RGBA = 5;
  12067. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12068. Engine._TEXTURETYPE_FLOAT = 1;
  12069. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12070. // Depht or Stencil test Constants.
  12071. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12072. 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.
  12073. 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.
  12074. 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.
  12075. 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.
  12076. 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.
  12077. 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.
  12078. 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.
  12079. // Stencil Actions Constants.
  12080. Engine._KEEP = 0x1E00;
  12081. Engine._REPLACE = 0x1E01;
  12082. Engine._INCR = 0x1E02;
  12083. Engine._DECR = 0x1E03;
  12084. Engine._INVERT = 0x150A;
  12085. Engine._INCR_WRAP = 0x8507;
  12086. Engine._DECR_WRAP = 0x8508;
  12087. // Texture rescaling mode
  12088. Engine._SCALEMODE_FLOOR = 1;
  12089. Engine._SCALEMODE_NEAREST = 2;
  12090. Engine._SCALEMODE_CEILING = 3;
  12091. // Updatable statics so stick with vars here
  12092. Engine.CollisionsEpsilon = 0.001;
  12093. Engine.CodeRepository = "src/";
  12094. Engine.ShadersRepository = "src/Shaders/";
  12095. return Engine;
  12096. }());
  12097. BABYLON.Engine = Engine;
  12098. })(BABYLON || (BABYLON = {}));
  12099. //# sourceMappingURL=babylon.engine.js.map
  12100. var BABYLON;
  12101. (function (BABYLON) {
  12102. /**
  12103. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12104. */
  12105. var Node = /** @class */ (function () {
  12106. /**
  12107. * @constructor
  12108. * @param {string} name - the name and id to be given to this node
  12109. * @param {BABYLON.Scene} the scene this node will be added to
  12110. */
  12111. function Node(name, scene) {
  12112. if (scene === void 0) { scene = null; }
  12113. this.state = "";
  12114. this.metadata = null;
  12115. this.doNotSerialize = false;
  12116. this.animations = new Array();
  12117. this._ranges = {};
  12118. this._isEnabled = true;
  12119. this._isReady = true;
  12120. this._currentRenderId = -1;
  12121. this._parentRenderId = -1;
  12122. /**
  12123. * An event triggered when the mesh is disposed.
  12124. * @type {BABYLON.Observable}
  12125. */
  12126. this.onDisposeObservable = new BABYLON.Observable();
  12127. // Behaviors
  12128. this._behaviors = new Array();
  12129. this.name = name;
  12130. this.id = name;
  12131. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12132. this.uniqueId = this._scene.getUniqueId();
  12133. this._initCache();
  12134. }
  12135. Object.defineProperty(Node.prototype, "parent", {
  12136. get: function () {
  12137. return this._parentNode;
  12138. },
  12139. set: function (parent) {
  12140. if (this._parentNode === parent) {
  12141. return;
  12142. }
  12143. if (this._parentNode) {
  12144. var index = this._parentNode._children.indexOf(this);
  12145. if (index !== -1) {
  12146. this._parentNode._children.splice(index, 1);
  12147. }
  12148. }
  12149. this._parentNode = parent;
  12150. if (this._parentNode) {
  12151. if (!this._parentNode._children) {
  12152. this._parentNode._children = new Array();
  12153. }
  12154. this._parentNode._children.push(this);
  12155. }
  12156. },
  12157. enumerable: true,
  12158. configurable: true
  12159. });
  12160. Node.prototype.getClassName = function () {
  12161. return "Node";
  12162. };
  12163. Object.defineProperty(Node.prototype, "onDispose", {
  12164. set: function (callback) {
  12165. if (this._onDisposeObserver) {
  12166. this.onDisposeObservable.remove(this._onDisposeObserver);
  12167. }
  12168. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12169. },
  12170. enumerable: true,
  12171. configurable: true
  12172. });
  12173. Node.prototype.getScene = function () {
  12174. return this._scene;
  12175. };
  12176. Node.prototype.getEngine = function () {
  12177. return this._scene.getEngine();
  12178. };
  12179. Node.prototype.addBehavior = function (behavior) {
  12180. var index = this._behaviors.indexOf(behavior);
  12181. if (index !== -1) {
  12182. return this;
  12183. }
  12184. behavior.attach(this);
  12185. this._behaviors.push(behavior);
  12186. return this;
  12187. };
  12188. Node.prototype.removeBehavior = function (behavior) {
  12189. var index = this._behaviors.indexOf(behavior);
  12190. if (index === -1) {
  12191. return this;
  12192. }
  12193. this._behaviors[index].detach();
  12194. this._behaviors.splice(index, 1);
  12195. return this;
  12196. };
  12197. Object.defineProperty(Node.prototype, "behaviors", {
  12198. get: function () {
  12199. return this._behaviors;
  12200. },
  12201. enumerable: true,
  12202. configurable: true
  12203. });
  12204. Node.prototype.getBehaviorByName = function (name) {
  12205. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12206. var behavior = _a[_i];
  12207. if (behavior.name === name) {
  12208. return behavior;
  12209. }
  12210. }
  12211. return null;
  12212. };
  12213. // override it in derived class
  12214. Node.prototype.getWorldMatrix = function () {
  12215. return BABYLON.Matrix.Identity();
  12216. };
  12217. // override it in derived class if you add new variables to the cache
  12218. // and call the parent class method
  12219. Node.prototype._initCache = function () {
  12220. this._cache = {};
  12221. this._cache.parent = undefined;
  12222. };
  12223. Node.prototype.updateCache = function (force) {
  12224. if (!force && this.isSynchronized())
  12225. return;
  12226. this._cache.parent = this.parent;
  12227. this._updateCache();
  12228. };
  12229. // override it in derived class if you add new variables to the cache
  12230. // and call the parent class method if !ignoreParentClass
  12231. Node.prototype._updateCache = function (ignoreParentClass) {
  12232. };
  12233. // override it in derived class if you add new variables to the cache
  12234. Node.prototype._isSynchronized = function () {
  12235. return true;
  12236. };
  12237. Node.prototype._markSyncedWithParent = function () {
  12238. if (this.parent) {
  12239. this._parentRenderId = this.parent._currentRenderId;
  12240. }
  12241. };
  12242. Node.prototype.isSynchronizedWithParent = function () {
  12243. if (!this.parent) {
  12244. return true;
  12245. }
  12246. if (this._parentRenderId !== this.parent._currentRenderId) {
  12247. return false;
  12248. }
  12249. return this.parent.isSynchronized();
  12250. };
  12251. Node.prototype.isSynchronized = function (updateCache) {
  12252. var check = this.hasNewParent();
  12253. check = check || !this.isSynchronizedWithParent();
  12254. check = check || !this._isSynchronized();
  12255. if (updateCache)
  12256. this.updateCache(true);
  12257. return !check;
  12258. };
  12259. Node.prototype.hasNewParent = function (update) {
  12260. if (this._cache.parent === this.parent)
  12261. return false;
  12262. if (update)
  12263. this._cache.parent = this.parent;
  12264. return true;
  12265. };
  12266. /**
  12267. * Is this node ready to be used/rendered
  12268. * @return {boolean} is it ready
  12269. */
  12270. Node.prototype.isReady = function () {
  12271. return this._isReady;
  12272. };
  12273. /**
  12274. * Is this node enabled.
  12275. * If the node has a parent and is enabled, the parent will be inspected as well.
  12276. * @return {boolean} whether this node (and its parent) is enabled.
  12277. * @see setEnabled
  12278. */
  12279. Node.prototype.isEnabled = function () {
  12280. if (!this._isEnabled) {
  12281. return false;
  12282. }
  12283. if (this.parent) {
  12284. return this.parent.isEnabled();
  12285. }
  12286. return true;
  12287. };
  12288. /**
  12289. * Set the enabled state of this node.
  12290. * @param {boolean} value - the new enabled state
  12291. * @see isEnabled
  12292. */
  12293. Node.prototype.setEnabled = function (value) {
  12294. this._isEnabled = value;
  12295. };
  12296. /**
  12297. * Is this node a descendant of the given node.
  12298. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12299. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12300. * @see parent
  12301. */
  12302. Node.prototype.isDescendantOf = function (ancestor) {
  12303. if (this.parent) {
  12304. if (this.parent === ancestor) {
  12305. return true;
  12306. }
  12307. return this.parent.isDescendantOf(ancestor);
  12308. }
  12309. return false;
  12310. };
  12311. /**
  12312. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12313. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12314. * @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.
  12315. * @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.
  12316. */
  12317. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12318. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12319. if (!this._children) {
  12320. return;
  12321. }
  12322. for (var index = 0; index < this._children.length; index++) {
  12323. var item = this._children[index];
  12324. if (!predicate || predicate(item)) {
  12325. results.push(item);
  12326. }
  12327. if (!directDescendantsOnly) {
  12328. item._getDescendants(results, false, predicate);
  12329. }
  12330. }
  12331. };
  12332. /**
  12333. * Will return all nodes that have this node as ascendant.
  12334. * @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.
  12335. * @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.
  12336. * @return {BABYLON.Node[]} all children nodes of all types.
  12337. */
  12338. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12339. var results = new Array();
  12340. this._getDescendants(results, directDescendantsOnly, predicate);
  12341. return results;
  12342. };
  12343. /**
  12344. * Get all child-meshes of this node.
  12345. */
  12346. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12347. var results = [];
  12348. this._getDescendants(results, directDecendantsOnly, function (node) {
  12349. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12350. });
  12351. return results;
  12352. };
  12353. /**
  12354. * Get all direct children of this node.
  12355. */
  12356. Node.prototype.getChildren = function (predicate) {
  12357. return this.getDescendants(true, predicate);
  12358. };
  12359. Node.prototype._setReady = function (state) {
  12360. if (state === this._isReady) {
  12361. return;
  12362. }
  12363. if (!state) {
  12364. this._isReady = false;
  12365. return;
  12366. }
  12367. this._isReady = true;
  12368. if (this.onReady) {
  12369. this.onReady(this);
  12370. }
  12371. };
  12372. Node.prototype.getAnimationByName = function (name) {
  12373. for (var i = 0; i < this.animations.length; i++) {
  12374. var animation = this.animations[i];
  12375. if (animation.name === name) {
  12376. return animation;
  12377. }
  12378. }
  12379. return null;
  12380. };
  12381. Node.prototype.createAnimationRange = function (name, from, to) {
  12382. // check name not already in use
  12383. if (!this._ranges[name]) {
  12384. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12385. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12386. if (this.animations[i]) {
  12387. this.animations[i].createRange(name, from, to);
  12388. }
  12389. }
  12390. }
  12391. };
  12392. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12393. if (deleteFrames === void 0) { deleteFrames = true; }
  12394. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12395. if (this.animations[i]) {
  12396. this.animations[i].deleteRange(name, deleteFrames);
  12397. }
  12398. }
  12399. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12400. };
  12401. Node.prototype.getAnimationRange = function (name) {
  12402. return this._ranges[name];
  12403. };
  12404. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12405. var range = this.getAnimationRange(name);
  12406. if (!range) {
  12407. return;
  12408. }
  12409. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12410. };
  12411. Node.prototype.serializeAnimationRanges = function () {
  12412. var serializationRanges = [];
  12413. for (var name in this._ranges) {
  12414. var localRange = this._ranges[name];
  12415. if (!localRange) {
  12416. continue;
  12417. }
  12418. var range = {};
  12419. range.name = name;
  12420. range.from = localRange.from;
  12421. range.to = localRange.to;
  12422. serializationRanges.push(range);
  12423. }
  12424. return serializationRanges;
  12425. };
  12426. Node.prototype.dispose = function () {
  12427. this.parent = null;
  12428. // Callback
  12429. this.onDisposeObservable.notifyObservers(this);
  12430. this.onDisposeObservable.clear();
  12431. // Behaviors
  12432. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12433. var behavior = _a[_i];
  12434. behavior.detach();
  12435. }
  12436. this._behaviors = [];
  12437. };
  12438. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12439. if (parsedNode.ranges) {
  12440. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12441. var data = parsedNode.ranges[index];
  12442. node.createAnimationRange(data.name, data.from, data.to);
  12443. }
  12444. }
  12445. };
  12446. __decorate([
  12447. BABYLON.serialize()
  12448. ], Node.prototype, "name", void 0);
  12449. __decorate([
  12450. BABYLON.serialize()
  12451. ], Node.prototype, "id", void 0);
  12452. __decorate([
  12453. BABYLON.serialize()
  12454. ], Node.prototype, "uniqueId", void 0);
  12455. __decorate([
  12456. BABYLON.serialize()
  12457. ], Node.prototype, "state", void 0);
  12458. __decorate([
  12459. BABYLON.serialize()
  12460. ], Node.prototype, "metadata", void 0);
  12461. return Node;
  12462. }());
  12463. BABYLON.Node = Node;
  12464. })(BABYLON || (BABYLON = {}));
  12465. //# sourceMappingURL=babylon.node.js.map
  12466. var BABYLON;
  12467. (function (BABYLON) {
  12468. var BoundingSphere = /** @class */ (function () {
  12469. function BoundingSphere(minimum, maximum) {
  12470. this.minimum = minimum;
  12471. this.maximum = maximum;
  12472. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12473. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12474. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12475. this.radius = distance * 0.5;
  12476. this.centerWorld = BABYLON.Vector3.Zero();
  12477. this._update(BABYLON.Matrix.Identity());
  12478. }
  12479. // Methods
  12480. BoundingSphere.prototype._update = function (world) {
  12481. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12482. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12483. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12484. };
  12485. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12486. for (var i = 0; i < 6; i++) {
  12487. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12488. return false;
  12489. }
  12490. return true;
  12491. };
  12492. BoundingSphere.prototype.intersectsPoint = function (point) {
  12493. var x = this.centerWorld.x - point.x;
  12494. var y = this.centerWorld.y - point.y;
  12495. var z = this.centerWorld.z - point.z;
  12496. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12497. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12498. return false;
  12499. return true;
  12500. };
  12501. // Statics
  12502. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12503. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12504. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12505. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12506. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12507. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12508. return false;
  12509. return true;
  12510. };
  12511. return BoundingSphere;
  12512. }());
  12513. BABYLON.BoundingSphere = BoundingSphere;
  12514. })(BABYLON || (BABYLON = {}));
  12515. //# sourceMappingURL=babylon.boundingSphere.js.map
  12516. var BABYLON;
  12517. (function (BABYLON) {
  12518. var BoundingBox = /** @class */ (function () {
  12519. function BoundingBox(minimum, maximum) {
  12520. this.minimum = minimum;
  12521. this.maximum = maximum;
  12522. this.vectors = new Array();
  12523. this.vectorsWorld = new Array();
  12524. // Bounding vectors
  12525. this.vectors.push(this.minimum.clone());
  12526. this.vectors.push(this.maximum.clone());
  12527. this.vectors.push(this.minimum.clone());
  12528. this.vectors[2].x = this.maximum.x;
  12529. this.vectors.push(this.minimum.clone());
  12530. this.vectors[3].y = this.maximum.y;
  12531. this.vectors.push(this.minimum.clone());
  12532. this.vectors[4].z = this.maximum.z;
  12533. this.vectors.push(this.maximum.clone());
  12534. this.vectors[5].z = this.minimum.z;
  12535. this.vectors.push(this.maximum.clone());
  12536. this.vectors[6].x = this.minimum.x;
  12537. this.vectors.push(this.maximum.clone());
  12538. this.vectors[7].y = this.minimum.y;
  12539. // OBB
  12540. this.center = this.maximum.add(this.minimum).scale(0.5);
  12541. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12542. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12543. // World
  12544. for (var index = 0; index < this.vectors.length; index++) {
  12545. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12546. }
  12547. this.minimumWorld = BABYLON.Vector3.Zero();
  12548. this.maximumWorld = BABYLON.Vector3.Zero();
  12549. this.centerWorld = BABYLON.Vector3.Zero();
  12550. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12551. this._update(BABYLON.Matrix.Identity());
  12552. }
  12553. // Methods
  12554. BoundingBox.prototype.getWorldMatrix = function () {
  12555. return this._worldMatrix;
  12556. };
  12557. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12558. this._worldMatrix.copyFrom(matrix);
  12559. return this;
  12560. };
  12561. BoundingBox.prototype._update = function (world) {
  12562. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12563. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12564. for (var index = 0; index < this.vectors.length; index++) {
  12565. var v = this.vectorsWorld[index];
  12566. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12567. if (v.x < this.minimumWorld.x)
  12568. this.minimumWorld.x = v.x;
  12569. if (v.y < this.minimumWorld.y)
  12570. this.minimumWorld.y = v.y;
  12571. if (v.z < this.minimumWorld.z)
  12572. this.minimumWorld.z = v.z;
  12573. if (v.x > this.maximumWorld.x)
  12574. this.maximumWorld.x = v.x;
  12575. if (v.y > this.maximumWorld.y)
  12576. this.maximumWorld.y = v.y;
  12577. if (v.z > this.maximumWorld.z)
  12578. this.maximumWorld.z = v.z;
  12579. }
  12580. // Extend
  12581. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12582. this.extendSizeWorld.scaleInPlace(0.5);
  12583. // OBB
  12584. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12585. this.centerWorld.scaleInPlace(0.5);
  12586. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12587. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12588. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12589. this._worldMatrix = world;
  12590. };
  12591. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12592. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12593. };
  12594. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12595. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12596. };
  12597. BoundingBox.prototype.intersectsPoint = function (point) {
  12598. var delta = -BABYLON.Epsilon;
  12599. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12600. return false;
  12601. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12602. return false;
  12603. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12604. return false;
  12605. return true;
  12606. };
  12607. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12608. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12609. };
  12610. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12611. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12612. return false;
  12613. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12614. return false;
  12615. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12616. return false;
  12617. return true;
  12618. };
  12619. // Statics
  12620. BoundingBox.Intersects = function (box0, box1) {
  12621. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12622. return false;
  12623. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12624. return false;
  12625. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12626. return false;
  12627. return true;
  12628. };
  12629. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12630. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12631. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12632. return (num <= (sphereRadius * sphereRadius));
  12633. };
  12634. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12635. for (var p = 0; p < 6; p++) {
  12636. for (var i = 0; i < 8; i++) {
  12637. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12638. return false;
  12639. }
  12640. }
  12641. }
  12642. return true;
  12643. };
  12644. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12645. for (var p = 0; p < 6; p++) {
  12646. var inCount = 8;
  12647. for (var i = 0; i < 8; i++) {
  12648. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12649. --inCount;
  12650. }
  12651. else {
  12652. break;
  12653. }
  12654. }
  12655. if (inCount === 0)
  12656. return false;
  12657. }
  12658. return true;
  12659. };
  12660. return BoundingBox;
  12661. }());
  12662. BABYLON.BoundingBox = BoundingBox;
  12663. })(BABYLON || (BABYLON = {}));
  12664. //# sourceMappingURL=babylon.boundingBox.js.map
  12665. var BABYLON;
  12666. (function (BABYLON) {
  12667. var computeBoxExtents = function (axis, box) {
  12668. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12669. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12670. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12671. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12672. var r = r0 + r1 + r2;
  12673. return {
  12674. min: p - r,
  12675. max: p + r
  12676. };
  12677. };
  12678. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12679. var axisOverlap = function (axis, box0, box1) {
  12680. var result0 = computeBoxExtents(axis, box0);
  12681. var result1 = computeBoxExtents(axis, box1);
  12682. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12683. };
  12684. var BoundingInfo = /** @class */ (function () {
  12685. function BoundingInfo(minimum, maximum) {
  12686. this.minimum = minimum;
  12687. this.maximum = maximum;
  12688. this._isLocked = false;
  12689. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12690. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12691. }
  12692. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12693. get: function () {
  12694. return this._isLocked;
  12695. },
  12696. set: function (value) {
  12697. this._isLocked = value;
  12698. },
  12699. enumerable: true,
  12700. configurable: true
  12701. });
  12702. // Methods
  12703. BoundingInfo.prototype.update = function (world) {
  12704. if (this._isLocked) {
  12705. return;
  12706. }
  12707. this.boundingBox._update(world);
  12708. this.boundingSphere._update(world);
  12709. };
  12710. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12711. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12712. return false;
  12713. return this.boundingBox.isInFrustum(frustumPlanes);
  12714. };
  12715. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12716. /**
  12717. * Gets the world distance between the min and max points of the bounding box
  12718. */
  12719. get: function () {
  12720. var boundingBox = this.boundingBox;
  12721. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12722. return size.length();
  12723. },
  12724. enumerable: true,
  12725. configurable: true
  12726. });
  12727. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12728. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12729. };
  12730. BoundingInfo.prototype._checkCollision = function (collider) {
  12731. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12732. };
  12733. BoundingInfo.prototype.intersectsPoint = function (point) {
  12734. if (!this.boundingSphere.centerWorld) {
  12735. return false;
  12736. }
  12737. if (!this.boundingSphere.intersectsPoint(point)) {
  12738. return false;
  12739. }
  12740. if (!this.boundingBox.intersectsPoint(point)) {
  12741. return false;
  12742. }
  12743. return true;
  12744. };
  12745. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12746. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12747. return false;
  12748. }
  12749. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12750. return false;
  12751. }
  12752. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12753. return false;
  12754. }
  12755. if (!precise) {
  12756. return true;
  12757. }
  12758. var box0 = this.boundingBox;
  12759. var box1 = boundingInfo.boundingBox;
  12760. if (!axisOverlap(box0.directions[0], box0, box1))
  12761. return false;
  12762. if (!axisOverlap(box0.directions[1], box0, box1))
  12763. return false;
  12764. if (!axisOverlap(box0.directions[2], box0, box1))
  12765. return false;
  12766. if (!axisOverlap(box1.directions[0], box0, box1))
  12767. return false;
  12768. if (!axisOverlap(box1.directions[1], box0, box1))
  12769. return false;
  12770. if (!axisOverlap(box1.directions[2], box0, box1))
  12771. return false;
  12772. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12773. return false;
  12774. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12775. return false;
  12776. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12777. return false;
  12778. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12779. return false;
  12780. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12781. return false;
  12782. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12783. return false;
  12784. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12785. return false;
  12786. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12787. return false;
  12788. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12789. return false;
  12790. return true;
  12791. };
  12792. return BoundingInfo;
  12793. }());
  12794. BABYLON.BoundingInfo = BoundingInfo;
  12795. })(BABYLON || (BABYLON = {}));
  12796. //# sourceMappingURL=babylon.boundingInfo.js.map
  12797. var BABYLON;
  12798. (function (BABYLON) {
  12799. var AbstractMesh = /** @class */ (function (_super) {
  12800. __extends(AbstractMesh, _super);
  12801. // Constructor
  12802. function AbstractMesh(name, scene) {
  12803. if (scene === void 0) { scene = null; }
  12804. var _this = _super.call(this, name, scene) || this;
  12805. _this._facetNb = 0; // facet number
  12806. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12807. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12808. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12809. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12810. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12811. _this._subDiv = {
  12812. max: 1,
  12813. X: 1,
  12814. Y: 1,
  12815. Z: 1
  12816. };
  12817. // Normal matrix
  12818. _this._nonUniformScaling = false;
  12819. // Events
  12820. /**
  12821. * An event triggered when this mesh collides with another one
  12822. * @type {BABYLON.Observable}
  12823. */
  12824. _this.onCollideObservable = new BABYLON.Observable();
  12825. /**
  12826. * An event triggered when the collision's position changes
  12827. * @type {BABYLON.Observable}
  12828. */
  12829. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12830. /**
  12831. * An event triggered after the world matrix is updated
  12832. * @type {BABYLON.Observable}
  12833. */
  12834. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12835. /**
  12836. * An event triggered when material is changed
  12837. * @type {BABYLON.Observable}
  12838. */
  12839. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12840. // Properties
  12841. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12842. _this.position = BABYLON.Vector3.Zero();
  12843. /**
  12844. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12845. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12846. * or
  12847. * 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.
  12848. * for more info check WebGl documentations
  12849. */
  12850. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12851. /**
  12852. * 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:
  12853. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12854. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12855. * 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.
  12856. */
  12857. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12858. /**
  12859. * 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.
  12860. * The default value is -1 which means don't break the query and wait till the result.
  12861. */
  12862. _this.occlusionRetryCount = -1;
  12863. _this._occlusionInternalRetryCounter = 0;
  12864. _this._isOccluded = false;
  12865. _this._isOcclusionQueryInProgress = false;
  12866. _this._rotation = BABYLON.Vector3.Zero();
  12867. _this._scaling = BABYLON.Vector3.One();
  12868. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12869. _this.visibility = 1.0;
  12870. _this.alphaIndex = Number.MAX_VALUE;
  12871. _this.infiniteDistance = false;
  12872. _this.isVisible = true;
  12873. _this.isPickable = true;
  12874. _this.showBoundingBox = false;
  12875. _this.showSubMeshesBoundingBox = false;
  12876. _this.isBlocker = false;
  12877. _this.enablePointerMoveEvents = false;
  12878. _this.renderingGroupId = 0;
  12879. _this._receiveShadows = false;
  12880. _this.renderOutline = false;
  12881. _this.outlineColor = BABYLON.Color3.Red();
  12882. _this.outlineWidth = 0.02;
  12883. _this.renderOverlay = false;
  12884. _this.overlayColor = BABYLON.Color3.Red();
  12885. _this.overlayAlpha = 0.5;
  12886. _this._hasVertexAlpha = false;
  12887. _this._useVertexColors = true;
  12888. _this._computeBonesUsingShaders = true;
  12889. _this._numBoneInfluencers = 4;
  12890. _this._applyFog = true;
  12891. _this.scalingDeterminant = 1;
  12892. _this.useOctreeForRenderingSelection = true;
  12893. _this.useOctreeForPicking = true;
  12894. _this.useOctreeForCollisions = true;
  12895. _this._layerMask = 0x0FFFFFFF;
  12896. /**
  12897. * True if the mesh must be rendered in any case.
  12898. */
  12899. _this.alwaysSelectAsActiveMesh = false;
  12900. // Collisions
  12901. _this._checkCollisions = false;
  12902. _this._collisionMask = -1;
  12903. _this._collisionGroup = -1;
  12904. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12905. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12906. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12907. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12908. // Edges
  12909. _this.edgesWidth = 1;
  12910. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12911. // Cache
  12912. _this._localWorld = BABYLON.Matrix.Zero();
  12913. _this._worldMatrix = BABYLON.Matrix.Zero();
  12914. _this._absolutePosition = BABYLON.Vector3.Zero();
  12915. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12916. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12917. _this._isDirty = false;
  12918. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12919. _this._postMultiplyPivotMatrix = false;
  12920. _this._isDisposed = false;
  12921. _this._renderId = 0;
  12922. _this._intersectionsInProgress = new Array();
  12923. _this._isWorldMatrixFrozen = false;
  12924. _this._unIndexed = false;
  12925. _this._lightSources = new Array();
  12926. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12927. if (collidedMesh === void 0) { collidedMesh = null; }
  12928. //TODO move this to the collision coordinator!
  12929. if (_this.getScene().workerCollisions)
  12930. newPosition.multiplyInPlace(_this._collider.radius);
  12931. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12932. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12933. _this.position.addInPlace(_this._diffPositionForCollisions);
  12934. }
  12935. if (collidedMesh) {
  12936. _this.onCollideObservable.notifyObservers(collidedMesh);
  12937. }
  12938. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12939. };
  12940. _this.getScene().addMesh(_this);
  12941. _this._resyncLightSources();
  12942. return _this;
  12943. }
  12944. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12945. get: function () {
  12946. return AbstractMesh._BILLBOARDMODE_NONE;
  12947. },
  12948. enumerable: true,
  12949. configurable: true
  12950. });
  12951. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12952. get: function () {
  12953. return AbstractMesh._BILLBOARDMODE_X;
  12954. },
  12955. enumerable: true,
  12956. configurable: true
  12957. });
  12958. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12959. get: function () {
  12960. return AbstractMesh._BILLBOARDMODE_Y;
  12961. },
  12962. enumerable: true,
  12963. configurable: true
  12964. });
  12965. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12966. get: function () {
  12967. return AbstractMesh._BILLBOARDMODE_Z;
  12968. },
  12969. enumerable: true,
  12970. configurable: true
  12971. });
  12972. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12973. get: function () {
  12974. return AbstractMesh._BILLBOARDMODE_ALL;
  12975. },
  12976. enumerable: true,
  12977. configurable: true
  12978. });
  12979. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12980. /**
  12981. * Read-only : the number of facets in the mesh
  12982. */
  12983. get: function () {
  12984. return this._facetNb;
  12985. },
  12986. enumerable: true,
  12987. configurable: true
  12988. });
  12989. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12990. /**
  12991. * The number (integer) of subdivisions per axis in the partioning space
  12992. */
  12993. get: function () {
  12994. return this._partitioningSubdivisions;
  12995. },
  12996. set: function (nb) {
  12997. this._partitioningSubdivisions = nb;
  12998. },
  12999. enumerable: true,
  13000. configurable: true
  13001. });
  13002. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  13003. /**
  13004. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  13005. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  13006. */
  13007. get: function () {
  13008. return this._partitioningBBoxRatio;
  13009. },
  13010. set: function (ratio) {
  13011. this._partitioningBBoxRatio = ratio;
  13012. },
  13013. enumerable: true,
  13014. configurable: true
  13015. });
  13016. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  13017. /**
  13018. * Read-only boolean : is the feature facetData enabled ?
  13019. */
  13020. get: function () {
  13021. return this._facetDataEnabled;
  13022. },
  13023. enumerable: true,
  13024. configurable: true
  13025. });
  13026. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  13027. get: function () {
  13028. return this._nonUniformScaling;
  13029. },
  13030. set: function (value) {
  13031. if (this._nonUniformScaling === value) {
  13032. return;
  13033. }
  13034. this._nonUniformScaling = true;
  13035. this._markSubMeshesAsMiscDirty();
  13036. },
  13037. enumerable: true,
  13038. configurable: true
  13039. });
  13040. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  13041. set: function (callback) {
  13042. if (this._onCollideObserver) {
  13043. this.onCollideObservable.remove(this._onCollideObserver);
  13044. }
  13045. this._onCollideObserver = this.onCollideObservable.add(callback);
  13046. },
  13047. enumerable: true,
  13048. configurable: true
  13049. });
  13050. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  13051. set: function (callback) {
  13052. if (this._onCollisionPositionChangeObserver) {
  13053. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  13054. }
  13055. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  13056. },
  13057. enumerable: true,
  13058. configurable: true
  13059. });
  13060. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  13061. /**
  13062. * 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.
  13063. */
  13064. get: function () {
  13065. return this._isOccluded;
  13066. },
  13067. set: function (value) {
  13068. this._isOccluded = value;
  13069. },
  13070. enumerable: true,
  13071. configurable: true
  13072. });
  13073. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  13074. /**
  13075. * Flag to check the progress status of the query
  13076. */
  13077. get: function () {
  13078. return this._isOcclusionQueryInProgress;
  13079. },
  13080. enumerable: true,
  13081. configurable: true
  13082. });
  13083. Object.defineProperty(AbstractMesh.prototype, "material", {
  13084. get: function () {
  13085. return this._material;
  13086. },
  13087. set: function (value) {
  13088. if (this._material === value) {
  13089. return;
  13090. }
  13091. this._material = value;
  13092. if (this.onMaterialChangedObservable.hasObservers) {
  13093. this.onMaterialChangedObservable.notifyObservers(this);
  13094. }
  13095. if (!this.subMeshes) {
  13096. return;
  13097. }
  13098. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13099. var subMesh = _a[_i];
  13100. subMesh.setEffect(null);
  13101. }
  13102. },
  13103. enumerable: true,
  13104. configurable: true
  13105. });
  13106. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  13107. get: function () {
  13108. return this._receiveShadows;
  13109. },
  13110. set: function (value) {
  13111. if (this._receiveShadows === value) {
  13112. return;
  13113. }
  13114. this._receiveShadows = value;
  13115. this._markSubMeshesAsLightDirty();
  13116. },
  13117. enumerable: true,
  13118. configurable: true
  13119. });
  13120. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  13121. get: function () {
  13122. return this._hasVertexAlpha;
  13123. },
  13124. set: function (value) {
  13125. if (this._hasVertexAlpha === value) {
  13126. return;
  13127. }
  13128. this._hasVertexAlpha = value;
  13129. this._markSubMeshesAsAttributesDirty();
  13130. },
  13131. enumerable: true,
  13132. configurable: true
  13133. });
  13134. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  13135. get: function () {
  13136. return this._useVertexColors;
  13137. },
  13138. set: function (value) {
  13139. if (this._useVertexColors === value) {
  13140. return;
  13141. }
  13142. this._useVertexColors = value;
  13143. this._markSubMeshesAsAttributesDirty();
  13144. },
  13145. enumerable: true,
  13146. configurable: true
  13147. });
  13148. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  13149. get: function () {
  13150. return this._computeBonesUsingShaders;
  13151. },
  13152. set: function (value) {
  13153. if (this._computeBonesUsingShaders === value) {
  13154. return;
  13155. }
  13156. this._computeBonesUsingShaders = value;
  13157. this._markSubMeshesAsAttributesDirty();
  13158. },
  13159. enumerable: true,
  13160. configurable: true
  13161. });
  13162. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  13163. get: function () {
  13164. return this._numBoneInfluencers;
  13165. },
  13166. set: function (value) {
  13167. if (this._numBoneInfluencers === value) {
  13168. return;
  13169. }
  13170. this._numBoneInfluencers = value;
  13171. this._markSubMeshesAsAttributesDirty();
  13172. },
  13173. enumerable: true,
  13174. configurable: true
  13175. });
  13176. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  13177. get: function () {
  13178. return this._applyFog;
  13179. },
  13180. set: function (value) {
  13181. if (this._applyFog === value) {
  13182. return;
  13183. }
  13184. this._applyFog = value;
  13185. this._markSubMeshesAsMiscDirty();
  13186. },
  13187. enumerable: true,
  13188. configurable: true
  13189. });
  13190. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  13191. get: function () {
  13192. return this._layerMask;
  13193. },
  13194. set: function (value) {
  13195. if (value === this._layerMask) {
  13196. return;
  13197. }
  13198. this._layerMask = value;
  13199. this._resyncLightSources();
  13200. },
  13201. enumerable: true,
  13202. configurable: true
  13203. });
  13204. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  13205. get: function () {
  13206. return this._collisionMask;
  13207. },
  13208. set: function (mask) {
  13209. this._collisionMask = !isNaN(mask) ? mask : -1;
  13210. },
  13211. enumerable: true,
  13212. configurable: true
  13213. });
  13214. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  13215. get: function () {
  13216. return this._collisionGroup;
  13217. },
  13218. set: function (mask) {
  13219. this._collisionGroup = !isNaN(mask) ? mask : -1;
  13220. },
  13221. enumerable: true,
  13222. configurable: true
  13223. });
  13224. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  13225. get: function () {
  13226. return null;
  13227. },
  13228. enumerable: true,
  13229. configurable: true
  13230. });
  13231. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  13232. get: function () {
  13233. return this._skeleton;
  13234. },
  13235. set: function (value) {
  13236. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  13237. this._skeleton._unregisterMeshWithPoseMatrix(this);
  13238. }
  13239. if (value && value.needInitialSkinMatrix) {
  13240. value._registerMeshWithPoseMatrix(this);
  13241. }
  13242. this._skeleton = value;
  13243. if (!this._skeleton) {
  13244. this._bonesTransformMatrices = null;
  13245. }
  13246. this._markSubMeshesAsAttributesDirty();
  13247. },
  13248. enumerable: true,
  13249. configurable: true
  13250. });
  13251. /**
  13252. * Boolean : true if the mesh has been disposed.
  13253. */
  13254. AbstractMesh.prototype.isDisposed = function () {
  13255. return this._isDisposed;
  13256. };
  13257. /**
  13258. * Returns the string "AbstractMesh"
  13259. */
  13260. AbstractMesh.prototype.getClassName = function () {
  13261. return "AbstractMesh";
  13262. };
  13263. /**
  13264. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13265. */
  13266. AbstractMesh.prototype.toString = function (fullDetails) {
  13267. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  13268. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  13269. if (this._skeleton) {
  13270. ret += ", skeleton: " + this._skeleton.name;
  13271. }
  13272. if (fullDetails) {
  13273. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  13274. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  13275. }
  13276. return ret;
  13277. };
  13278. AbstractMesh.prototype._rebuild = function () {
  13279. if (this._occlusionQuery) {
  13280. this._occlusionQuery = null;
  13281. }
  13282. if (this._edgesRenderer) {
  13283. this._edgesRenderer._rebuild();
  13284. }
  13285. if (!this.subMeshes) {
  13286. return;
  13287. }
  13288. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13289. var subMesh = _a[_i];
  13290. subMesh._rebuild();
  13291. }
  13292. };
  13293. AbstractMesh.prototype._resyncLightSources = function () {
  13294. this._lightSources.length = 0;
  13295. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  13296. var light = _a[_i];
  13297. if (!light.isEnabled()) {
  13298. continue;
  13299. }
  13300. if (light.canAffectMesh(this)) {
  13301. this._lightSources.push(light);
  13302. }
  13303. }
  13304. this._markSubMeshesAsLightDirty();
  13305. };
  13306. AbstractMesh.prototype._resyncLighSource = function (light) {
  13307. var isIn = light.isEnabled() && light.canAffectMesh(this);
  13308. var index = this._lightSources.indexOf(light);
  13309. if (index === -1) {
  13310. if (!isIn) {
  13311. return;
  13312. }
  13313. this._lightSources.push(light);
  13314. }
  13315. else {
  13316. if (isIn) {
  13317. return;
  13318. }
  13319. this._lightSources.splice(index, 1);
  13320. }
  13321. this._markSubMeshesAsLightDirty();
  13322. };
  13323. AbstractMesh.prototype._removeLightSource = function (light) {
  13324. var index = this._lightSources.indexOf(light);
  13325. if (index === -1) {
  13326. return;
  13327. }
  13328. this._lightSources.splice(index, 1);
  13329. };
  13330. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  13331. if (!this.subMeshes) {
  13332. return;
  13333. }
  13334. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13335. var subMesh = _a[_i];
  13336. if (subMesh._materialDefines) {
  13337. func(subMesh._materialDefines);
  13338. }
  13339. }
  13340. };
  13341. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13342. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13343. };
  13344. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13345. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13346. };
  13347. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13348. if (!this.subMeshes) {
  13349. return;
  13350. }
  13351. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13352. var subMesh = _a[_i];
  13353. var material = subMesh.getMaterial();
  13354. if (material) {
  13355. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13356. }
  13357. }
  13358. };
  13359. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13360. /**
  13361. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13362. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13363. * Default : (0.0, 0.0, 0.0)
  13364. */
  13365. get: function () {
  13366. return this._rotation;
  13367. },
  13368. set: function (newRotation) {
  13369. this._rotation = newRotation;
  13370. },
  13371. enumerable: true,
  13372. configurable: true
  13373. });
  13374. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13375. /**
  13376. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13377. * Default : (1.0, 1.0, 1.0)
  13378. */
  13379. get: function () {
  13380. return this._scaling;
  13381. },
  13382. set: function (newScaling) {
  13383. this._scaling = newScaling;
  13384. if (this.physicsImpostor) {
  13385. this.physicsImpostor.forceUpdate();
  13386. }
  13387. },
  13388. enumerable: true,
  13389. configurable: true
  13390. });
  13391. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13392. /**
  13393. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13394. * It's null by default.
  13395. * 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)
  13396. */
  13397. get: function () {
  13398. return this._rotationQuaternion;
  13399. },
  13400. set: function (quaternion) {
  13401. this._rotationQuaternion = quaternion;
  13402. //reset the rotation vector.
  13403. if (quaternion && this.rotation.length()) {
  13404. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13405. }
  13406. },
  13407. enumerable: true,
  13408. configurable: true
  13409. });
  13410. // Methods
  13411. /**
  13412. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13413. * Returns the AbstractMesh.
  13414. */
  13415. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13416. this._poseMatrix.copyFrom(matrix);
  13417. return this;
  13418. };
  13419. /**
  13420. * Returns the mesh Pose matrix.
  13421. * Returned object : Matrix
  13422. */
  13423. AbstractMesh.prototype.getPoseMatrix = function () {
  13424. return this._poseMatrix;
  13425. };
  13426. /**
  13427. * Disables the mesh edger rendering mode.
  13428. * Returns the AbstractMesh.
  13429. */
  13430. AbstractMesh.prototype.disableEdgesRendering = function () {
  13431. if (this._edgesRenderer) {
  13432. this._edgesRenderer.dispose();
  13433. this._edgesRenderer = null;
  13434. }
  13435. return this;
  13436. };
  13437. /**
  13438. * Enables the edge rendering mode on the mesh.
  13439. * This mode makes the mesh edges visible.
  13440. * Returns the AbstractMesh.
  13441. */
  13442. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13443. if (epsilon === void 0) { epsilon = 0.95; }
  13444. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13445. this.disableEdgesRendering();
  13446. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13447. return this;
  13448. };
  13449. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13450. /**
  13451. * Returns true if the mesh is blocked. Used by the class Mesh.
  13452. * Returns the boolean `false` by default.
  13453. */
  13454. get: function () {
  13455. return false;
  13456. },
  13457. enumerable: true,
  13458. configurable: true
  13459. });
  13460. /**
  13461. * Returns the mesh itself by default, used by the class Mesh.
  13462. * Returned type : AbstractMesh
  13463. */
  13464. AbstractMesh.prototype.getLOD = function (camera) {
  13465. return this;
  13466. };
  13467. /**
  13468. * Returns 0 by default, used by the class Mesh.
  13469. * Returns an integer.
  13470. */
  13471. AbstractMesh.prototype.getTotalVertices = function () {
  13472. return 0;
  13473. };
  13474. /**
  13475. * Returns null by default, used by the class Mesh.
  13476. * Returned type : integer array
  13477. */
  13478. AbstractMesh.prototype.getIndices = function () {
  13479. return null;
  13480. };
  13481. /**
  13482. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13483. * Returned type : float array or Float32Array
  13484. */
  13485. AbstractMesh.prototype.getVerticesData = function (kind) {
  13486. return null;
  13487. };
  13488. /**
  13489. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13490. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13491. * The `data` are either a numeric array either a Float32Array.
  13492. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13493. * 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).
  13494. * Note that a new underlying VertexBuffer object is created each call.
  13495. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13496. *
  13497. * Possible `kind` values :
  13498. * - BABYLON.VertexBuffer.PositionKind
  13499. * - BABYLON.VertexBuffer.UVKind
  13500. * - BABYLON.VertexBuffer.UV2Kind
  13501. * - BABYLON.VertexBuffer.UV3Kind
  13502. * - BABYLON.VertexBuffer.UV4Kind
  13503. * - BABYLON.VertexBuffer.UV5Kind
  13504. * - BABYLON.VertexBuffer.UV6Kind
  13505. * - BABYLON.VertexBuffer.ColorKind
  13506. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13507. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13508. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13509. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13510. *
  13511. * Returns the Mesh.
  13512. */
  13513. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13514. return this;
  13515. };
  13516. /**
  13517. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13518. * If the mesh has no geometry, it is simply returned as it is.
  13519. * The `data` are either a numeric array either a Float32Array.
  13520. * No new underlying VertexBuffer object is created.
  13521. * 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.
  13522. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13523. *
  13524. * Possible `kind` values :
  13525. * - BABYLON.VertexBuffer.PositionKind
  13526. * - BABYLON.VertexBuffer.UVKind
  13527. * - BABYLON.VertexBuffer.UV2Kind
  13528. * - BABYLON.VertexBuffer.UV3Kind
  13529. * - BABYLON.VertexBuffer.UV4Kind
  13530. * - BABYLON.VertexBuffer.UV5Kind
  13531. * - BABYLON.VertexBuffer.UV6Kind
  13532. * - BABYLON.VertexBuffer.ColorKind
  13533. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13534. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13535. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13536. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13537. *
  13538. * Returns the Mesh.
  13539. */
  13540. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13541. return this;
  13542. };
  13543. /**
  13544. * Sets the mesh indices.
  13545. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13546. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13547. * This method creates a new index buffer each call.
  13548. * Returns the Mesh.
  13549. */
  13550. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13551. return this;
  13552. };
  13553. /** Returns false by default, used by the class Mesh.
  13554. * Returns a boolean
  13555. */
  13556. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13557. return false;
  13558. };
  13559. /**
  13560. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13561. * Returns a BoundingInfo
  13562. */
  13563. AbstractMesh.prototype.getBoundingInfo = function () {
  13564. if (this._masterMesh) {
  13565. return this._masterMesh.getBoundingInfo();
  13566. }
  13567. if (!this._boundingInfo) {
  13568. this._updateBoundingInfo();
  13569. }
  13570. return this._boundingInfo;
  13571. };
  13572. /**
  13573. * Sets a mesh new object BoundingInfo.
  13574. * Returns the AbstractMesh.
  13575. */
  13576. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13577. this._boundingInfo = boundingInfo;
  13578. return this;
  13579. };
  13580. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13581. get: function () {
  13582. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13583. },
  13584. enumerable: true,
  13585. configurable: true
  13586. });
  13587. AbstractMesh.prototype._preActivate = function () {
  13588. };
  13589. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13590. };
  13591. AbstractMesh.prototype._activate = function (renderId) {
  13592. this._renderId = renderId;
  13593. };
  13594. /**
  13595. * Returns the last update of the World matrix
  13596. * Returns a Matrix.
  13597. */
  13598. AbstractMesh.prototype.getWorldMatrix = function () {
  13599. if (this._masterMesh) {
  13600. return this._masterMesh.getWorldMatrix();
  13601. }
  13602. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  13603. this.computeWorldMatrix();
  13604. }
  13605. return this._worldMatrix;
  13606. };
  13607. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13608. /**
  13609. * Returns directly the last state of the mesh World matrix.
  13610. * A Matrix is returned.
  13611. */
  13612. get: function () {
  13613. return this._worldMatrix;
  13614. },
  13615. enumerable: true,
  13616. configurable: true
  13617. });
  13618. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13619. /**
  13620. * Returns the current mesh absolute position.
  13621. * Retuns a Vector3.
  13622. */
  13623. get: function () {
  13624. return this._absolutePosition;
  13625. },
  13626. enumerable: true,
  13627. configurable: true
  13628. });
  13629. /**
  13630. * Prevents the World matrix to be computed any longer.
  13631. * Returns the AbstractMesh.
  13632. */
  13633. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13634. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13635. this.computeWorldMatrix(true);
  13636. this._isWorldMatrixFrozen = true;
  13637. return this;
  13638. };
  13639. /**
  13640. * Allows back the World matrix computation.
  13641. * Returns the AbstractMesh.
  13642. */
  13643. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13644. this._isWorldMatrixFrozen = false;
  13645. this.computeWorldMatrix(true);
  13646. return this;
  13647. };
  13648. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13649. /**
  13650. * True if the World matrix has been frozen.
  13651. * Returns a boolean.
  13652. */
  13653. get: function () {
  13654. return this._isWorldMatrixFrozen;
  13655. },
  13656. enumerable: true,
  13657. configurable: true
  13658. });
  13659. /**
  13660. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13661. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13662. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13663. * The passed axis is also normalized.
  13664. * Returns the AbstractMesh.
  13665. */
  13666. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13667. axis.normalize();
  13668. if (!this.rotationQuaternion) {
  13669. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13670. this.rotation = BABYLON.Vector3.Zero();
  13671. }
  13672. var rotationQuaternion;
  13673. if (!space || space === BABYLON.Space.LOCAL) {
  13674. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13675. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13676. }
  13677. else {
  13678. if (this.parent) {
  13679. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13680. invertParentWorldMatrix.invert();
  13681. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13682. }
  13683. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13684. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13685. }
  13686. return this;
  13687. };
  13688. /**
  13689. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13690. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13691. * The passed axis is also normalized.
  13692. * Returns the AbstractMesh.
  13693. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13694. */
  13695. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13696. axis.normalize();
  13697. if (!this.rotationQuaternion) {
  13698. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13699. this.rotation.copyFromFloats(0, 0, 0);
  13700. }
  13701. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13702. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13703. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13704. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13705. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13706. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13707. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13708. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13709. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13710. return this;
  13711. };
  13712. /**
  13713. * Translates the mesh along the axis vector for the passed distance in the given space.
  13714. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13715. * Returns the AbstractMesh.
  13716. */
  13717. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13718. var displacementVector = axis.scale(distance);
  13719. if (!space || space === BABYLON.Space.LOCAL) {
  13720. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13721. this.setPositionWithLocalVector(tempV3);
  13722. }
  13723. else {
  13724. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13725. }
  13726. return this;
  13727. };
  13728. /**
  13729. * Adds a rotation step to the mesh current rotation.
  13730. * x, y, z are Euler angles expressed in radians.
  13731. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13732. * This means this rotation is made in the mesh local space only.
  13733. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13734. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13735. * ```javascript
  13736. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13737. * ```
  13738. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13739. * 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.
  13740. * Returns the AbstractMesh.
  13741. */
  13742. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13743. var rotationQuaternion;
  13744. if (this.rotationQuaternion) {
  13745. rotationQuaternion = this.rotationQuaternion;
  13746. }
  13747. else {
  13748. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13749. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13750. }
  13751. var accumulation = BABYLON.Tmp.Quaternion[0];
  13752. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13753. rotationQuaternion.multiplyInPlace(accumulation);
  13754. if (!this.rotationQuaternion) {
  13755. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13756. }
  13757. return this;
  13758. };
  13759. /**
  13760. * Retuns the mesh absolute position in the World.
  13761. * Returns a Vector3.
  13762. */
  13763. AbstractMesh.prototype.getAbsolutePosition = function () {
  13764. this.computeWorldMatrix();
  13765. return this._absolutePosition;
  13766. };
  13767. /**
  13768. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13769. * Returns the AbstractMesh.
  13770. */
  13771. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13772. if (!absolutePosition) {
  13773. return this;
  13774. }
  13775. var absolutePositionX;
  13776. var absolutePositionY;
  13777. var absolutePositionZ;
  13778. if (absolutePosition.x === undefined) {
  13779. if (arguments.length < 3) {
  13780. return this;
  13781. }
  13782. absolutePositionX = arguments[0];
  13783. absolutePositionY = arguments[1];
  13784. absolutePositionZ = arguments[2];
  13785. }
  13786. else {
  13787. absolutePositionX = absolutePosition.x;
  13788. absolutePositionY = absolutePosition.y;
  13789. absolutePositionZ = absolutePosition.z;
  13790. }
  13791. if (this.parent) {
  13792. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13793. invertParentWorldMatrix.invert();
  13794. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13795. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13796. }
  13797. else {
  13798. this.position.x = absolutePositionX;
  13799. this.position.y = absolutePositionY;
  13800. this.position.z = absolutePositionZ;
  13801. }
  13802. return this;
  13803. };
  13804. // ================================== Point of View Movement =================================
  13805. /**
  13806. * Perform relative position change from the point of view of behind the front of the mesh.
  13807. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13808. * Supports definition of mesh facing forward or backward.
  13809. * @param {number} amountRight
  13810. * @param {number} amountUp
  13811. * @param {number} amountForward
  13812. *
  13813. * Returns the AbstractMesh.
  13814. */
  13815. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13816. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13817. return this;
  13818. };
  13819. /**
  13820. * Calculate relative position change from the point of view of behind the front of the mesh.
  13821. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13822. * Supports definition of mesh facing forward or backward.
  13823. * @param {number} amountRight
  13824. * @param {number} amountUp
  13825. * @param {number} amountForward
  13826. *
  13827. * Returns a new Vector3.
  13828. */
  13829. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13830. var rotMatrix = new BABYLON.Matrix();
  13831. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13832. rotQuaternion.toRotationMatrix(rotMatrix);
  13833. var translationDelta = BABYLON.Vector3.Zero();
  13834. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13835. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13836. return translationDelta;
  13837. };
  13838. // ================================== Point of View Rotation =================================
  13839. /**
  13840. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13841. * Supports definition of mesh facing forward or backward.
  13842. * @param {number} flipBack
  13843. * @param {number} twirlClockwise
  13844. * @param {number} tiltRight
  13845. *
  13846. * Returns the AbstractMesh.
  13847. */
  13848. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13849. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13850. return this;
  13851. };
  13852. /**
  13853. * Calculate 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 a new Vector3.
  13860. */
  13861. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13862. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13863. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13864. };
  13865. /**
  13866. * Sets a new pivot matrix to the mesh.
  13867. * Returns the AbstractMesh.
  13868. */
  13869. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13870. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13871. this._pivotMatrix = matrix.clone();
  13872. this._cache.pivotMatrixUpdated = true;
  13873. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13874. if (this._postMultiplyPivotMatrix) {
  13875. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13876. }
  13877. return this;
  13878. };
  13879. /**
  13880. * Returns the mesh pivot matrix.
  13881. * Default : Identity.
  13882. * A Matrix is returned.
  13883. */
  13884. AbstractMesh.prototype.getPivotMatrix = function () {
  13885. return this._pivotMatrix;
  13886. };
  13887. AbstractMesh.prototype._isSynchronized = function () {
  13888. if (this._isDirty) {
  13889. return false;
  13890. }
  13891. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13892. return false;
  13893. if (this._cache.pivotMatrixUpdated) {
  13894. return false;
  13895. }
  13896. if (this.infiniteDistance) {
  13897. return false;
  13898. }
  13899. if (!this._cache.position.equals(this.position))
  13900. return false;
  13901. if (this.rotationQuaternion) {
  13902. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13903. return false;
  13904. }
  13905. if (!this._cache.rotation.equals(this.rotation))
  13906. return false;
  13907. if (!this._cache.scaling.equals(this.scaling))
  13908. return false;
  13909. return true;
  13910. };
  13911. AbstractMesh.prototype._initCache = function () {
  13912. _super.prototype._initCache.call(this);
  13913. this._cache.localMatrixUpdated = false;
  13914. this._cache.position = BABYLON.Vector3.Zero();
  13915. this._cache.scaling = BABYLON.Vector3.Zero();
  13916. this._cache.rotation = BABYLON.Vector3.Zero();
  13917. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13918. this._cache.billboardMode = -1;
  13919. };
  13920. AbstractMesh.prototype.markAsDirty = function (property) {
  13921. if (property === "rotation") {
  13922. this.rotationQuaternion = null;
  13923. }
  13924. this._currentRenderId = Number.MAX_VALUE;
  13925. this._isDirty = true;
  13926. return this;
  13927. };
  13928. /**
  13929. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13930. */
  13931. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13932. this.computeWorldMatrix(true);
  13933. var min;
  13934. var max;
  13935. var boundingInfo = this.getBoundingInfo();
  13936. if (!this.subMeshes || !boundingInfo) {
  13937. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13938. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13939. }
  13940. else {
  13941. min = boundingInfo.boundingBox.minimumWorld;
  13942. max = boundingInfo.boundingBox.maximumWorld;
  13943. }
  13944. var descendants = this.getDescendants(false);
  13945. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13946. var descendant = descendants_1[_i];
  13947. var childMesh = descendant;
  13948. childMesh.computeWorldMatrix(true);
  13949. var childBoundingInfo = childMesh.getBoundingInfo();
  13950. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  13951. continue;
  13952. }
  13953. var boundingBox = childBoundingInfo.boundingBox;
  13954. var minBox = boundingBox.minimumWorld;
  13955. var maxBox = boundingBox.maximumWorld;
  13956. BABYLON.Tools.CheckExtends(minBox, min, max);
  13957. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13958. }
  13959. return {
  13960. min: min,
  13961. max: max
  13962. };
  13963. };
  13964. /**
  13965. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13966. * Returns the AbstractMesh.
  13967. */
  13968. AbstractMesh.prototype._updateBoundingInfo = function () {
  13969. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13970. this._boundingInfo.update(this.worldMatrixFromCache);
  13971. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13972. return this;
  13973. };
  13974. /**
  13975. * Update a mesh's children BoundingInfo objects only.
  13976. * Returns the AbstractMesh.
  13977. */
  13978. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13979. if (!this.subMeshes) {
  13980. return this;
  13981. }
  13982. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13983. var subMesh = this.subMeshes[subIndex];
  13984. if (!subMesh.IsGlobal) {
  13985. subMesh.updateBoundingInfo(matrix);
  13986. }
  13987. }
  13988. return this;
  13989. };
  13990. /**
  13991. * Computes the mesh World matrix and returns it.
  13992. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13993. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13994. * If the parameter `force`is set to `true`, the actual computation is done.
  13995. * Returns the mesh World Matrix.
  13996. */
  13997. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13998. if (this._isWorldMatrixFrozen) {
  13999. return this._worldMatrix;
  14000. }
  14001. if (!force && this.isSynchronized(true)) {
  14002. this._currentRenderId = this.getScene().getRenderId();
  14003. return this._worldMatrix;
  14004. }
  14005. this._cache.position.copyFrom(this.position);
  14006. this._cache.scaling.copyFrom(this.scaling);
  14007. this._cache.pivotMatrixUpdated = false;
  14008. this._cache.billboardMode = this.billboardMode;
  14009. this._currentRenderId = this.getScene().getRenderId();
  14010. this._isDirty = false;
  14011. // Scaling
  14012. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14013. // Rotation
  14014. //rotate, if quaternion is set and rotation was used
  14015. if (this.rotationQuaternion) {
  14016. var len = this.rotation.length();
  14017. if (len) {
  14018. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14019. this.rotation.copyFromFloats(0, 0, 0);
  14020. }
  14021. }
  14022. if (this.rotationQuaternion) {
  14023. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14024. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14025. }
  14026. else {
  14027. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14028. this._cache.rotation.copyFrom(this.rotation);
  14029. }
  14030. // Translation
  14031. var camera = this.getScene().activeCamera;
  14032. if (this.infiniteDistance && !this.parent && camera) {
  14033. var cameraWorldMatrix = camera.getWorldMatrix();
  14034. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14035. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14036. }
  14037. else {
  14038. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14039. }
  14040. // Composing transformations
  14041. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14042. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14043. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14044. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14045. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  14046. // Need to decompose each rotation here
  14047. var currentPosition = BABYLON.Tmp.Vector3[3];
  14048. if (this.parent && this.parent.getWorldMatrix) {
  14049. if (this._meshToBoneReferal) {
  14050. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14051. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14052. }
  14053. else {
  14054. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14055. }
  14056. }
  14057. else {
  14058. currentPosition.copyFrom(this.position);
  14059. }
  14060. currentPosition.subtractInPlace(camera.globalPosition);
  14061. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14062. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  14063. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14064. }
  14065. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  14066. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14067. }
  14068. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  14069. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14070. }
  14071. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14072. }
  14073. else {
  14074. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14075. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14076. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14077. }
  14078. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14079. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14080. }
  14081. // Local world
  14082. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14083. // Parent
  14084. if (this.parent && this.parent.getWorldMatrix) {
  14085. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  14086. if (this._meshToBoneReferal) {
  14087. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14088. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14089. }
  14090. else {
  14091. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14092. }
  14093. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14094. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14095. this._worldMatrix.copyFrom(this._localWorld);
  14096. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14097. }
  14098. else {
  14099. if (this._meshToBoneReferal) {
  14100. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14101. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14102. }
  14103. else {
  14104. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14105. }
  14106. }
  14107. this._markSyncedWithParent();
  14108. }
  14109. else {
  14110. this._worldMatrix.copyFrom(this._localWorld);
  14111. }
  14112. // Post multiply inverse of pivotMatrix
  14113. if (this._postMultiplyPivotMatrix) {
  14114. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14115. }
  14116. // Normal matrix
  14117. if (this.scaling.isNonUniform) {
  14118. this.nonUniformScaling = true;
  14119. }
  14120. else if (this.parent && this.parent._nonUniformScaling) {
  14121. this.nonUniformScaling = this.parent._nonUniformScaling;
  14122. }
  14123. else {
  14124. this.nonUniformScaling = false;
  14125. }
  14126. // Bounding info
  14127. this._updateBoundingInfo();
  14128. // Absolute position
  14129. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14130. // Callbacks
  14131. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14132. if (!this._poseMatrix) {
  14133. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14134. }
  14135. return this._worldMatrix;
  14136. };
  14137. /**
  14138. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14139. * @param func: callback function to add
  14140. *
  14141. * Returns the AbstractMesh.
  14142. */
  14143. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14144. this.onAfterWorldMatrixUpdateObservable.add(func);
  14145. return this;
  14146. };
  14147. /**
  14148. * Removes a registered callback function.
  14149. * Returns the AbstractMesh.
  14150. */
  14151. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14152. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14153. return this;
  14154. };
  14155. /**
  14156. * Sets the mesh position in its local space.
  14157. * Returns the AbstractMesh.
  14158. */
  14159. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  14160. this.computeWorldMatrix();
  14161. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14162. return this;
  14163. };
  14164. /**
  14165. * Returns the mesh position in the local space from the current World matrix values.
  14166. * Returns a new Vector3.
  14167. */
  14168. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  14169. this.computeWorldMatrix();
  14170. var invLocalWorldMatrix = this._localWorld.clone();
  14171. invLocalWorldMatrix.invert();
  14172. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14173. };
  14174. /**
  14175. * Translates the mesh along the passed Vector3 in its local space.
  14176. * Returns the AbstractMesh.
  14177. */
  14178. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  14179. this.computeWorldMatrix(true);
  14180. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14181. return this;
  14182. };
  14183. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14184. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  14185. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  14186. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  14187. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  14188. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  14189. /// <returns>Mesh oriented towards targetMesh</returns>
  14190. if (yawCor === void 0) { yawCor = 0; }
  14191. if (pitchCor === void 0) { pitchCor = 0; }
  14192. if (rollCor === void 0) { rollCor = 0; }
  14193. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14194. var dv = AbstractMesh._lookAtVectorCache;
  14195. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14196. targetPoint.subtractToRef(pos, dv);
  14197. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14198. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14199. var pitch = Math.atan2(dv.y, len);
  14200. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  14201. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14202. return this;
  14203. };
  14204. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  14205. this._meshToBoneReferal = affectedMesh;
  14206. this.parent = bone;
  14207. if (bone.getWorldMatrix().determinant() < 0) {
  14208. this.scalingDeterminant *= -1;
  14209. }
  14210. return this;
  14211. };
  14212. AbstractMesh.prototype.detachFromBone = function () {
  14213. if (!this.parent) {
  14214. return this;
  14215. }
  14216. if (this.parent.getWorldMatrix().determinant() < 0) {
  14217. this.scalingDeterminant *= -1;
  14218. }
  14219. this._meshToBoneReferal = null;
  14220. this.parent = null;
  14221. return this;
  14222. };
  14223. /**
  14224. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14225. * A mesh is in the frustum if its bounding box intersects the frustum.
  14226. * Boolean returned.
  14227. */
  14228. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14229. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14230. };
  14231. /**
  14232. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14233. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14234. * Boolean returned.
  14235. */
  14236. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14237. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14238. ;
  14239. };
  14240. /**
  14241. * True if the mesh intersects another mesh or a SolidParticle object.
  14242. * 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)
  14243. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14244. * Returns a boolean.
  14245. */
  14246. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14247. if (precise === void 0) { precise = false; }
  14248. if (!this._boundingInfo || !mesh._boundingInfo) {
  14249. return false;
  14250. }
  14251. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14252. return true;
  14253. }
  14254. if (includeDescendants) {
  14255. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14256. var child = _a[_i];
  14257. if (child.intersectsMesh(mesh, precise, true)) {
  14258. return true;
  14259. }
  14260. }
  14261. }
  14262. return false;
  14263. };
  14264. /**
  14265. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14266. * Returns a boolean.
  14267. */
  14268. AbstractMesh.prototype.intersectsPoint = function (point) {
  14269. if (!this._boundingInfo) {
  14270. return false;
  14271. }
  14272. return this._boundingInfo.intersectsPoint(point);
  14273. };
  14274. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14275. return this.physicsImpostor;
  14276. };
  14277. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14278. if (camera === void 0) { camera = null; }
  14279. if (!camera) {
  14280. camera = this.getScene().activeCamera;
  14281. }
  14282. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14283. };
  14284. /**
  14285. * Returns the distance from the mesh to the active camera.
  14286. * Returns a float.
  14287. */
  14288. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14289. if (camera === void 0) { camera = null; }
  14290. if (!camera) {
  14291. camera = this.getScene().activeCamera;
  14292. }
  14293. return this.absolutePosition.subtract(camera.position).length();
  14294. };
  14295. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14296. if (!this.physicsImpostor) {
  14297. return this;
  14298. }
  14299. this.physicsImpostor.applyImpulse(force, contactPoint);
  14300. return this;
  14301. };
  14302. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14303. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14304. return this;
  14305. }
  14306. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14307. mainPivot: pivot1,
  14308. connectedPivot: pivot2,
  14309. nativeParams: options
  14310. });
  14311. return this;
  14312. };
  14313. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14314. // Collisions
  14315. /**
  14316. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14317. * Default `false`.
  14318. */
  14319. get: function () {
  14320. return this._checkCollisions;
  14321. },
  14322. set: function (collisionEnabled) {
  14323. this._checkCollisions = collisionEnabled;
  14324. if (this.getScene().workerCollisions) {
  14325. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14326. }
  14327. },
  14328. enumerable: true,
  14329. configurable: true
  14330. });
  14331. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14332. var globalPosition = this.getAbsolutePosition();
  14333. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14334. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14335. if (!this._collider) {
  14336. this._collider = new BABYLON.Collider();
  14337. }
  14338. this._collider.radius = this.ellipsoid;
  14339. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14340. return this;
  14341. };
  14342. // Submeshes octree
  14343. /**
  14344. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14345. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14346. * Returns an Octree of submeshes.
  14347. */
  14348. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14349. if (maxCapacity === void 0) { maxCapacity = 64; }
  14350. if (maxDepth === void 0) { maxDepth = 2; }
  14351. if (!this._submeshesOctree) {
  14352. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14353. }
  14354. this.computeWorldMatrix(true);
  14355. var boundingInfo = this.getBoundingInfo();
  14356. // Update octree
  14357. if (boundingInfo) {
  14358. var bbox = boundingInfo.boundingBox;
  14359. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14360. }
  14361. return this._submeshesOctree;
  14362. };
  14363. // Collisions
  14364. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14365. this._generatePointsArray();
  14366. if (!this._positions) {
  14367. return this;
  14368. }
  14369. // Transformation
  14370. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14371. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14372. subMesh._lastColliderWorldVertices = [];
  14373. subMesh._trianglePlanes = [];
  14374. var start = subMesh.verticesStart;
  14375. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14376. for (var i = start; i < end; i++) {
  14377. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14378. }
  14379. }
  14380. // Collide
  14381. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14382. if (collider.collisionFound) {
  14383. collider.collidedMesh = this;
  14384. }
  14385. return this;
  14386. };
  14387. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14388. var subMeshes;
  14389. var len;
  14390. // Octrees
  14391. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14392. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14393. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14394. len = intersections.length;
  14395. subMeshes = intersections.data;
  14396. }
  14397. else {
  14398. subMeshes = this.subMeshes;
  14399. len = subMeshes.length;
  14400. }
  14401. for (var index = 0; index < len; index++) {
  14402. var subMesh = subMeshes[index];
  14403. // Bounding test
  14404. if (len > 1 && !subMesh._checkCollision(collider))
  14405. continue;
  14406. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14407. }
  14408. return this;
  14409. };
  14410. AbstractMesh.prototype._checkCollision = function (collider) {
  14411. // Bounding box test
  14412. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14413. return this;
  14414. // Transformation matrix
  14415. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14416. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14417. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14418. return this;
  14419. };
  14420. // Picking
  14421. AbstractMesh.prototype._generatePointsArray = function () {
  14422. return false;
  14423. };
  14424. /**
  14425. * Checks if the passed Ray intersects with the mesh.
  14426. * Returns an object PickingInfo.
  14427. */
  14428. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14429. var pickingInfo = new BABYLON.PickingInfo();
  14430. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14431. return pickingInfo;
  14432. }
  14433. if (!this._generatePointsArray()) {
  14434. return pickingInfo;
  14435. }
  14436. var intersectInfo = null;
  14437. // Octrees
  14438. var subMeshes;
  14439. var len;
  14440. if (this._submeshesOctree && this.useOctreeForPicking) {
  14441. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14442. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14443. len = intersections.length;
  14444. subMeshes = intersections.data;
  14445. }
  14446. else {
  14447. subMeshes = this.subMeshes;
  14448. len = subMeshes.length;
  14449. }
  14450. for (var index = 0; index < len; index++) {
  14451. var subMesh = subMeshes[index];
  14452. // Bounding test
  14453. if (len > 1 && !subMesh.canIntersects(ray))
  14454. continue;
  14455. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14456. if (currentIntersectInfo) {
  14457. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14458. intersectInfo = currentIntersectInfo;
  14459. intersectInfo.subMeshId = index;
  14460. if (fastCheck) {
  14461. break;
  14462. }
  14463. }
  14464. }
  14465. }
  14466. if (intersectInfo) {
  14467. // Get picked point
  14468. var world = this.getWorldMatrix();
  14469. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14470. var direction = ray.direction.clone();
  14471. direction = direction.scale(intersectInfo.distance);
  14472. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14473. var pickedPoint = worldOrigin.add(worldDirection);
  14474. // Return result
  14475. pickingInfo.hit = true;
  14476. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14477. pickingInfo.pickedPoint = pickedPoint;
  14478. pickingInfo.pickedMesh = this;
  14479. pickingInfo.bu = intersectInfo.bu || 0;
  14480. pickingInfo.bv = intersectInfo.bv || 0;
  14481. pickingInfo.faceId = intersectInfo.faceId;
  14482. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14483. return pickingInfo;
  14484. }
  14485. return pickingInfo;
  14486. };
  14487. /**
  14488. * Clones the mesh, used by the class Mesh.
  14489. * Just returns `null` for an AbstractMesh.
  14490. */
  14491. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14492. return null;
  14493. };
  14494. /**
  14495. * Disposes all the mesh submeshes.
  14496. * Returns the AbstractMesh.
  14497. */
  14498. AbstractMesh.prototype.releaseSubMeshes = function () {
  14499. if (this.subMeshes) {
  14500. while (this.subMeshes.length) {
  14501. this.subMeshes[0].dispose();
  14502. }
  14503. }
  14504. else {
  14505. this.subMeshes = new Array();
  14506. }
  14507. return this;
  14508. };
  14509. /**
  14510. * Disposes the AbstractMesh.
  14511. * Some internal references are kept for further use.
  14512. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14513. * Returns nothing.
  14514. */
  14515. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14516. var _this = this;
  14517. var index;
  14518. // Action manager
  14519. if (this.actionManager) {
  14520. this.actionManager.dispose();
  14521. this.actionManager = null;
  14522. }
  14523. // Skeleton
  14524. this.skeleton = null;
  14525. // Animations
  14526. this.getScene().stopAnimation(this);
  14527. // Physics
  14528. if (this.physicsImpostor) {
  14529. this.physicsImpostor.dispose();
  14530. }
  14531. // Intersections in progress
  14532. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14533. var other = this._intersectionsInProgress[index];
  14534. var pos = other._intersectionsInProgress.indexOf(this);
  14535. other._intersectionsInProgress.splice(pos, 1);
  14536. }
  14537. this._intersectionsInProgress = [];
  14538. // Lights
  14539. var lights = this.getScene().lights;
  14540. lights.forEach(function (light) {
  14541. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14542. if (meshIndex !== -1) {
  14543. light.includedOnlyMeshes.splice(meshIndex, 1);
  14544. }
  14545. meshIndex = light.excludedMeshes.indexOf(_this);
  14546. if (meshIndex !== -1) {
  14547. light.excludedMeshes.splice(meshIndex, 1);
  14548. }
  14549. // Shadow generators
  14550. var generator = light.getShadowGenerator();
  14551. if (generator) {
  14552. var shadowMap = generator.getShadowMap();
  14553. if (shadowMap && shadowMap.renderList) {
  14554. meshIndex = shadowMap.renderList.indexOf(_this);
  14555. if (meshIndex !== -1) {
  14556. shadowMap.renderList.splice(meshIndex, 1);
  14557. }
  14558. }
  14559. }
  14560. });
  14561. // Edges
  14562. if (this._edgesRenderer) {
  14563. this._edgesRenderer.dispose();
  14564. this._edgesRenderer = null;
  14565. }
  14566. // SubMeshes
  14567. if (this.getClassName() !== "InstancedMesh") {
  14568. this.releaseSubMeshes();
  14569. }
  14570. // Octree
  14571. var sceneOctree = this.getScene().selectionOctree;
  14572. if (sceneOctree) {
  14573. var index = sceneOctree.dynamicContent.indexOf(this);
  14574. if (index !== -1) {
  14575. sceneOctree.dynamicContent.splice(index, 1);
  14576. }
  14577. }
  14578. // Query
  14579. var engine = this.getScene().getEngine();
  14580. if (this._occlusionQuery) {
  14581. this._isOcclusionQueryInProgress = false;
  14582. engine.deleteQuery(this._occlusionQuery);
  14583. this._occlusionQuery = null;
  14584. }
  14585. // Engine
  14586. engine.wipeCaches();
  14587. // Remove from scene
  14588. this.getScene().removeMesh(this);
  14589. if (!doNotRecurse) {
  14590. // Particles
  14591. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14592. if (this.getScene().particleSystems[index].emitter === this) {
  14593. this.getScene().particleSystems[index].dispose();
  14594. index--;
  14595. }
  14596. }
  14597. // Children
  14598. var objects = this.getDescendants(true);
  14599. for (index = 0; index < objects.length; index++) {
  14600. objects[index].dispose();
  14601. }
  14602. }
  14603. else {
  14604. var childMeshes = this.getChildMeshes(true);
  14605. for (index = 0; index < childMeshes.length; index++) {
  14606. var child = childMeshes[index];
  14607. child.parent = null;
  14608. child.computeWorldMatrix(true);
  14609. }
  14610. }
  14611. // facet data
  14612. if (this._facetDataEnabled) {
  14613. this.disableFacetData();
  14614. }
  14615. this.onAfterWorldMatrixUpdateObservable.clear();
  14616. this.onCollideObservable.clear();
  14617. this.onCollisionPositionChangeObservable.clear();
  14618. this._isDisposed = true;
  14619. _super.prototype.dispose.call(this);
  14620. };
  14621. /**
  14622. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14623. * This Vector3 is expressed in the World space.
  14624. */
  14625. AbstractMesh.prototype.getDirection = function (localAxis) {
  14626. var result = BABYLON.Vector3.Zero();
  14627. this.getDirectionToRef(localAxis, result);
  14628. return result;
  14629. };
  14630. /**
  14631. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14632. * localAxis is expressed in the mesh local space.
  14633. * result is computed in the Wordl space from the mesh World matrix.
  14634. * Returns the AbstractMesh.
  14635. */
  14636. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14637. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14638. return this;
  14639. };
  14640. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14641. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14642. if (this.getScene().getRenderId() == 0) {
  14643. this.computeWorldMatrix(true);
  14644. }
  14645. var wm = this.getWorldMatrix();
  14646. if (space == BABYLON.Space.WORLD) {
  14647. var tmat = BABYLON.Tmp.Matrix[0];
  14648. wm.invertToRef(tmat);
  14649. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14650. }
  14651. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14652. this._pivotMatrix.m[12] = -point.x;
  14653. this._pivotMatrix.m[13] = -point.y;
  14654. this._pivotMatrix.m[14] = -point.z;
  14655. this._cache.pivotMatrixUpdated = true;
  14656. return this;
  14657. };
  14658. /**
  14659. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14660. */
  14661. AbstractMesh.prototype.getPivotPoint = function () {
  14662. var point = BABYLON.Vector3.Zero();
  14663. this.getPivotPointToRef(point);
  14664. return point;
  14665. };
  14666. /**
  14667. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14668. * Returns the AbstractMesh.
  14669. */
  14670. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14671. result.x = -this._pivotMatrix.m[12];
  14672. result.y = -this._pivotMatrix.m[13];
  14673. result.z = -this._pivotMatrix.m[14];
  14674. return this;
  14675. };
  14676. /**
  14677. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14678. */
  14679. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14680. var point = BABYLON.Vector3.Zero();
  14681. this.getAbsolutePivotPointToRef(point);
  14682. return point;
  14683. };
  14684. /**
  14685. * Defines the passed mesh as the parent of the current mesh.
  14686. * Returns the AbstractMesh.
  14687. */
  14688. AbstractMesh.prototype.setParent = function (mesh) {
  14689. var parent = mesh;
  14690. if (mesh == null) {
  14691. var rotation = BABYLON.Tmp.Quaternion[0];
  14692. var position = BABYLON.Tmp.Vector3[0];
  14693. var scale = BABYLON.Tmp.Vector3[1];
  14694. this.getWorldMatrix().decompose(scale, rotation, position);
  14695. if (this.rotationQuaternion) {
  14696. this.rotationQuaternion.copyFrom(rotation);
  14697. }
  14698. else {
  14699. rotation.toEulerAnglesToRef(this.rotation);
  14700. }
  14701. this.position.x = position.x;
  14702. this.position.y = position.y;
  14703. this.position.z = position.z;
  14704. }
  14705. else {
  14706. var position = BABYLON.Tmp.Vector3[0];
  14707. var m1 = BABYLON.Tmp.Matrix[0];
  14708. parent.getWorldMatrix().invertToRef(m1);
  14709. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  14710. this.position.copyFrom(position);
  14711. }
  14712. this.parent = parent;
  14713. return this;
  14714. };
  14715. /**
  14716. * Adds the passed mesh as a child to the current mesh.
  14717. * Returns the AbstractMesh.
  14718. */
  14719. AbstractMesh.prototype.addChild = function (mesh) {
  14720. mesh.setParent(this);
  14721. return this;
  14722. };
  14723. /**
  14724. * Removes the passed mesh from the current mesh children list.
  14725. * Returns the AbstractMesh.
  14726. */
  14727. AbstractMesh.prototype.removeChild = function (mesh) {
  14728. mesh.setParent(null);
  14729. return this;
  14730. };
  14731. /**
  14732. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14733. * Returns the AbstractMesh.
  14734. */
  14735. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14736. result.x = this._pivotMatrix.m[12];
  14737. result.y = this._pivotMatrix.m[13];
  14738. result.z = this._pivotMatrix.m[14];
  14739. this.getPivotPointToRef(result);
  14740. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14741. return this;
  14742. };
  14743. // Facet data
  14744. /**
  14745. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14746. * Returns the AbstractMesh.
  14747. */
  14748. AbstractMesh.prototype._initFacetData = function () {
  14749. if (!this._facetNormals) {
  14750. this._facetNormals = new Array();
  14751. }
  14752. if (!this._facetPositions) {
  14753. this._facetPositions = new Array();
  14754. }
  14755. if (!this._facetPartitioning) {
  14756. this._facetPartitioning = new Array();
  14757. }
  14758. this._facetNb = this.getIndices().length / 3;
  14759. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14760. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14761. for (var f = 0; f < this._facetNb; f++) {
  14762. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14763. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14764. }
  14765. this._facetDataEnabled = true;
  14766. return this;
  14767. };
  14768. /**
  14769. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14770. * This method can be called within the render loop.
  14771. * 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.
  14772. * Returns the AbstractMesh.
  14773. */
  14774. AbstractMesh.prototype.updateFacetData = function () {
  14775. if (!this._facetDataEnabled) {
  14776. this._initFacetData();
  14777. }
  14778. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14779. var indices = this.getIndices();
  14780. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14781. var bInfo = this.getBoundingInfo();
  14782. if (!bInfo) {
  14783. return this;
  14784. }
  14785. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14786. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14787. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14788. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14789. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14790. this._subDiv.max = this._partitioningSubdivisions;
  14791. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14792. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14793. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14794. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14795. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14796. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14797. // set the parameters for ComputeNormals()
  14798. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14799. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14800. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14801. this._facetParameters.bInfo = bInfo;
  14802. this._facetParameters.bbSize = this._bbSize;
  14803. this._facetParameters.subDiv = this._subDiv;
  14804. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14805. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14806. return this;
  14807. };
  14808. /**
  14809. * Returns the facetLocalNormals array.
  14810. * The normals are expressed in the mesh local space.
  14811. */
  14812. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14813. if (!this._facetNormals) {
  14814. this.updateFacetData();
  14815. }
  14816. return this._facetNormals;
  14817. };
  14818. /**
  14819. * Returns the facetLocalPositions array.
  14820. * The facet positions are expressed in the mesh local space.
  14821. */
  14822. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14823. if (!this._facetPositions) {
  14824. this.updateFacetData();
  14825. }
  14826. return this._facetPositions;
  14827. };
  14828. /**
  14829. * Returns the facetLocalPartioning array.
  14830. */
  14831. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14832. if (!this._facetPartitioning) {
  14833. this.updateFacetData();
  14834. }
  14835. return this._facetPartitioning;
  14836. };
  14837. /**
  14838. * Returns the i-th facet position in the world system.
  14839. * This method allocates a new Vector3 per call.
  14840. */
  14841. AbstractMesh.prototype.getFacetPosition = function (i) {
  14842. var pos = BABYLON.Vector3.Zero();
  14843. this.getFacetPositionToRef(i, pos);
  14844. return pos;
  14845. };
  14846. /**
  14847. * Sets the reference Vector3 with the i-th facet position in the world system.
  14848. * Returns the AbstractMesh.
  14849. */
  14850. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14851. var localPos = (this.getFacetLocalPositions())[i];
  14852. var world = this.getWorldMatrix();
  14853. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14854. return this;
  14855. };
  14856. /**
  14857. * Returns the i-th facet normal in the world system.
  14858. * This method allocates a new Vector3 per call.
  14859. */
  14860. AbstractMesh.prototype.getFacetNormal = function (i) {
  14861. var norm = BABYLON.Vector3.Zero();
  14862. this.getFacetNormalToRef(i, norm);
  14863. return norm;
  14864. };
  14865. /**
  14866. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14867. * Returns the AbstractMesh.
  14868. */
  14869. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14870. var localNorm = (this.getFacetLocalNormals())[i];
  14871. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14872. return this;
  14873. };
  14874. /**
  14875. * 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).
  14876. */
  14877. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14878. var bInfo = this.getBoundingInfo();
  14879. if (!bInfo) {
  14880. return null;
  14881. }
  14882. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14883. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14884. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14885. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14886. return null;
  14887. }
  14888. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14889. };
  14890. /**
  14891. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14892. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14893. * 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.
  14894. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14895. * 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.
  14896. */
  14897. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14898. if (checkFace === void 0) { checkFace = false; }
  14899. if (facing === void 0) { facing = true; }
  14900. var world = this.getWorldMatrix();
  14901. var invMat = BABYLON.Tmp.Matrix[5];
  14902. world.invertToRef(invMat);
  14903. var invVect = BABYLON.Tmp.Vector3[8];
  14904. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14905. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14906. if (projected) {
  14907. // tranform the local computed projected vector to world coordinates
  14908. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14909. }
  14910. return closest;
  14911. };
  14912. /**
  14913. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14914. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14915. * 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.
  14916. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14917. * 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.
  14918. */
  14919. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14920. if (checkFace === void 0) { checkFace = false; }
  14921. if (facing === void 0) { facing = true; }
  14922. var closest = null;
  14923. var tmpx = 0.0;
  14924. var tmpy = 0.0;
  14925. var tmpz = 0.0;
  14926. var d = 0.0; // tmp dot facet normal * facet position
  14927. var t0 = 0.0;
  14928. var projx = 0.0;
  14929. var projy = 0.0;
  14930. var projz = 0.0;
  14931. // Get all the facets in the same partitioning block than (x, y, z)
  14932. var facetPositions = this.getFacetLocalPositions();
  14933. var facetNormals = this.getFacetLocalNormals();
  14934. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14935. if (!facetsInBlock) {
  14936. return null;
  14937. }
  14938. // Get the closest facet to (x, y, z)
  14939. var shortest = Number.MAX_VALUE; // init distance vars
  14940. var tmpDistance = shortest;
  14941. var fib; // current facet in the block
  14942. var norm; // current facet normal
  14943. var p0; // current facet barycenter position
  14944. // loop on all the facets in the current partitioning block
  14945. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14946. fib = facetsInBlock[idx];
  14947. norm = facetNormals[fib];
  14948. p0 = facetPositions[fib];
  14949. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14950. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14951. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14952. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14953. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14954. projx = x + norm.x * t0;
  14955. projy = y + norm.y * t0;
  14956. projz = z + norm.z * t0;
  14957. tmpx = projx - x;
  14958. tmpy = projy - y;
  14959. tmpz = projz - z;
  14960. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14961. if (tmpDistance < shortest) {
  14962. shortest = tmpDistance;
  14963. closest = fib;
  14964. if (projected) {
  14965. projected.x = projx;
  14966. projected.y = projy;
  14967. projected.z = projz;
  14968. }
  14969. }
  14970. }
  14971. }
  14972. return closest;
  14973. };
  14974. /**
  14975. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14976. */
  14977. AbstractMesh.prototype.getFacetDataParameters = function () {
  14978. return this._facetParameters;
  14979. };
  14980. /**
  14981. * Disables the feature FacetData and frees the related memory.
  14982. * Returns the AbstractMesh.
  14983. */
  14984. AbstractMesh.prototype.disableFacetData = function () {
  14985. if (this._facetDataEnabled) {
  14986. this._facetDataEnabled = false;
  14987. this._facetPositions = new Array();
  14988. ;
  14989. this._facetNormals = new Array();
  14990. ;
  14991. this._facetPartitioning = new Array();
  14992. ;
  14993. this._facetParameters = null;
  14994. }
  14995. return this;
  14996. };
  14997. /**
  14998. * Creates new normals data for the mesh.
  14999. * @param updatable.
  15000. */
  15001. AbstractMesh.prototype.createNormals = function (updatable) {
  15002. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15003. var indices = this.getIndices();
  15004. var normals;
  15005. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15006. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15007. }
  15008. else {
  15009. normals = [];
  15010. }
  15011. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15012. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15013. };
  15014. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15015. var engine = this.getEngine();
  15016. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15017. this._isOccluded = false;
  15018. return;
  15019. }
  15020. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15021. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15022. if (isOcclusionQueryAvailable) {
  15023. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15024. this._isOcclusionQueryInProgress = false;
  15025. this._occlusionInternalRetryCounter = 0;
  15026. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15027. }
  15028. else {
  15029. this._occlusionInternalRetryCounter++;
  15030. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15031. this._isOcclusionQueryInProgress = false;
  15032. this._occlusionInternalRetryCounter = 0;
  15033. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15034. // if strict continue the last state of the object.
  15035. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15036. }
  15037. else {
  15038. return;
  15039. }
  15040. }
  15041. }
  15042. var scene = this.getScene();
  15043. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15044. if (!this._occlusionQuery) {
  15045. this._occlusionQuery = engine.createQuery();
  15046. }
  15047. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15048. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15049. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15050. this._isOcclusionQueryInProgress = true;
  15051. };
  15052. // Statics
  15053. AbstractMesh._BILLBOARDMODE_NONE = 0;
  15054. AbstractMesh._BILLBOARDMODE_X = 1;
  15055. AbstractMesh._BILLBOARDMODE_Y = 2;
  15056. AbstractMesh._BILLBOARDMODE_Z = 4;
  15057. AbstractMesh._BILLBOARDMODE_ALL = 7;
  15058. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15059. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15060. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15061. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15062. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15063. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  15064. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15065. return AbstractMesh;
  15066. }(BABYLON.Node));
  15067. BABYLON.AbstractMesh = AbstractMesh;
  15068. })(BABYLON || (BABYLON = {}));
  15069. //# sourceMappingURL=babylon.abstractMesh.js.map
  15070. var BABYLON;
  15071. (function (BABYLON) {
  15072. var Light = /** @class */ (function (_super) {
  15073. __extends(Light, _super);
  15074. /**
  15075. * Creates a Light object in the scene.
  15076. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15077. */
  15078. function Light(name, scene) {
  15079. var _this = _super.call(this, name, scene) || this;
  15080. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15081. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15082. _this.intensity = 1.0;
  15083. _this.range = Number.MAX_VALUE;
  15084. /**
  15085. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15086. * of light.
  15087. */
  15088. _this._photometricScale = 1.0;
  15089. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15090. _this._radius = 0.00001;
  15091. _this.renderPriority = 0;
  15092. /**
  15093. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15094. * the current shadow generator.
  15095. */
  15096. _this.shadowEnabled = true;
  15097. _this._excludeWithLayerMask = 0;
  15098. _this._includeOnlyWithLayerMask = 0;
  15099. _this._lightmapMode = 0;
  15100. _this._excludedMeshesIds = new Array();
  15101. _this._includedOnlyMeshesIds = new Array();
  15102. _this.getScene().addLight(_this);
  15103. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15104. _this._buildUniformLayout();
  15105. _this.includedOnlyMeshes = new Array();
  15106. _this.excludedMeshes = new Array();
  15107. _this._resyncMeshes();
  15108. return _this;
  15109. }
  15110. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15111. /**
  15112. * If every light affecting the material is in this lightmapMode,
  15113. * material.lightmapTexture adds or multiplies
  15114. * (depends on material.useLightmapAsShadowmap)
  15115. * after every other light calculations.
  15116. */
  15117. get: function () {
  15118. return Light._LIGHTMAP_DEFAULT;
  15119. },
  15120. enumerable: true,
  15121. configurable: true
  15122. });
  15123. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15124. /**
  15125. * material.lightmapTexture as only diffuse lighting from this light
  15126. * adds pnly specular lighting from this light
  15127. * adds dynamic shadows
  15128. */
  15129. get: function () {
  15130. return Light._LIGHTMAP_SPECULAR;
  15131. },
  15132. enumerable: true,
  15133. configurable: true
  15134. });
  15135. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15136. /**
  15137. * material.lightmapTexture as only lighting
  15138. * no light calculation from this light
  15139. * only adds dynamic shadows from this light
  15140. */
  15141. get: function () {
  15142. return Light._LIGHTMAP_SHADOWSONLY;
  15143. },
  15144. enumerable: true,
  15145. configurable: true
  15146. });
  15147. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15148. /**
  15149. * Each light type uses the default quantity according to its type:
  15150. * point/spot lights use luminous intensity
  15151. * directional lights use illuminance
  15152. */
  15153. get: function () {
  15154. return Light._INTENSITYMODE_AUTOMATIC;
  15155. },
  15156. enumerable: true,
  15157. configurable: true
  15158. });
  15159. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15160. /**
  15161. * lumen (lm)
  15162. */
  15163. get: function () {
  15164. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15165. },
  15166. enumerable: true,
  15167. configurable: true
  15168. });
  15169. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15170. /**
  15171. * candela (lm/sr)
  15172. */
  15173. get: function () {
  15174. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15175. },
  15176. enumerable: true,
  15177. configurable: true
  15178. });
  15179. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15180. /**
  15181. * lux (lm/m^2)
  15182. */
  15183. get: function () {
  15184. return Light._INTENSITYMODE_ILLUMINANCE;
  15185. },
  15186. enumerable: true,
  15187. configurable: true
  15188. });
  15189. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15190. /**
  15191. * nit (cd/m^2)
  15192. */
  15193. get: function () {
  15194. return Light._INTENSITYMODE_LUMINANCE;
  15195. },
  15196. enumerable: true,
  15197. configurable: true
  15198. });
  15199. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15200. /**
  15201. * Light type const id of the point light.
  15202. */
  15203. get: function () {
  15204. return Light._LIGHTTYPEID_POINTLIGHT;
  15205. },
  15206. enumerable: true,
  15207. configurable: true
  15208. });
  15209. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15210. /**
  15211. * Light type const id of the directional light.
  15212. */
  15213. get: function () {
  15214. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15215. },
  15216. enumerable: true,
  15217. configurable: true
  15218. });
  15219. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15220. /**
  15221. * Light type const id of the spot light.
  15222. */
  15223. get: function () {
  15224. return Light._LIGHTTYPEID_SPOTLIGHT;
  15225. },
  15226. enumerable: true,
  15227. configurable: true
  15228. });
  15229. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15230. /**
  15231. * Light type const id of the hemispheric light.
  15232. */
  15233. get: function () {
  15234. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15235. },
  15236. enumerable: true,
  15237. configurable: true
  15238. });
  15239. Object.defineProperty(Light.prototype, "intensityMode", {
  15240. /**
  15241. * Gets the photometric scale used to interpret the intensity.
  15242. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15243. */
  15244. get: function () {
  15245. return this._intensityMode;
  15246. },
  15247. /**
  15248. * Sets the photometric scale used to interpret the intensity.
  15249. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15250. */
  15251. set: function (value) {
  15252. this._intensityMode = value;
  15253. this._computePhotometricScale();
  15254. },
  15255. enumerable: true,
  15256. configurable: true
  15257. });
  15258. ;
  15259. ;
  15260. Object.defineProperty(Light.prototype, "radius", {
  15261. /**
  15262. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15263. */
  15264. get: function () {
  15265. return this._radius;
  15266. },
  15267. /**
  15268. * sets the light radius used by PBR Materials to simulate soft area lights.
  15269. */
  15270. set: function (value) {
  15271. this._radius = value;
  15272. this._computePhotometricScale();
  15273. },
  15274. enumerable: true,
  15275. configurable: true
  15276. });
  15277. ;
  15278. ;
  15279. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15280. get: function () {
  15281. return this._includedOnlyMeshes;
  15282. },
  15283. set: function (value) {
  15284. this._includedOnlyMeshes = value;
  15285. this._hookArrayForIncludedOnly(value);
  15286. },
  15287. enumerable: true,
  15288. configurable: true
  15289. });
  15290. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15291. get: function () {
  15292. return this._excludedMeshes;
  15293. },
  15294. set: function (value) {
  15295. this._excludedMeshes = value;
  15296. this._hookArrayForExcluded(value);
  15297. },
  15298. enumerable: true,
  15299. configurable: true
  15300. });
  15301. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15302. get: function () {
  15303. return this._excludeWithLayerMask;
  15304. },
  15305. set: function (value) {
  15306. this._excludeWithLayerMask = value;
  15307. this._resyncMeshes();
  15308. },
  15309. enumerable: true,
  15310. configurable: true
  15311. });
  15312. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15313. get: function () {
  15314. return this._includeOnlyWithLayerMask;
  15315. },
  15316. set: function (value) {
  15317. this._includeOnlyWithLayerMask = value;
  15318. this._resyncMeshes();
  15319. },
  15320. enumerable: true,
  15321. configurable: true
  15322. });
  15323. Object.defineProperty(Light.prototype, "lightmapMode", {
  15324. get: function () {
  15325. return this._lightmapMode;
  15326. },
  15327. set: function (value) {
  15328. if (this._lightmapMode === value) {
  15329. return;
  15330. }
  15331. this._lightmapMode = value;
  15332. this._markMeshesAsLightDirty();
  15333. },
  15334. enumerable: true,
  15335. configurable: true
  15336. });
  15337. Light.prototype._buildUniformLayout = function () {
  15338. // Overridden
  15339. };
  15340. /**
  15341. * Returns the string "Light".
  15342. */
  15343. Light.prototype.getClassName = function () {
  15344. return "Light";
  15345. };
  15346. /**
  15347. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15348. */
  15349. Light.prototype.toString = function (fullDetails) {
  15350. var ret = "Name: " + this.name;
  15351. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15352. if (this.animations) {
  15353. for (var i = 0; i < this.animations.length; i++) {
  15354. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15355. }
  15356. }
  15357. if (fullDetails) {
  15358. }
  15359. return ret;
  15360. };
  15361. /**
  15362. * Set the enabled state of this node.
  15363. * @param {boolean} value - the new enabled state
  15364. * @see isEnabled
  15365. */
  15366. Light.prototype.setEnabled = function (value) {
  15367. _super.prototype.setEnabled.call(this, value);
  15368. this._resyncMeshes();
  15369. };
  15370. /**
  15371. * Returns the Light associated shadow generator.
  15372. */
  15373. Light.prototype.getShadowGenerator = function () {
  15374. return this._shadowGenerator;
  15375. };
  15376. /**
  15377. * Returns a Vector3, the absolute light position in the World.
  15378. */
  15379. Light.prototype.getAbsolutePosition = function () {
  15380. return BABYLON.Vector3.Zero();
  15381. };
  15382. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15383. };
  15384. Light.prototype._getWorldMatrix = function () {
  15385. return BABYLON.Matrix.Identity();
  15386. };
  15387. /**
  15388. * Boolean : True if the light will affect the passed mesh.
  15389. */
  15390. Light.prototype.canAffectMesh = function (mesh) {
  15391. if (!mesh) {
  15392. return true;
  15393. }
  15394. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15395. return false;
  15396. }
  15397. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15398. return false;
  15399. }
  15400. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15401. return false;
  15402. }
  15403. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15404. return false;
  15405. }
  15406. return true;
  15407. };
  15408. /**
  15409. * Returns the light World matrix.
  15410. */
  15411. Light.prototype.getWorldMatrix = function () {
  15412. this._currentRenderId = this.getScene().getRenderId();
  15413. var worldMatrix = this._getWorldMatrix();
  15414. if (this.parent && this.parent.getWorldMatrix) {
  15415. if (!this._parentedWorldMatrix) {
  15416. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15417. }
  15418. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15419. this._markSyncedWithParent();
  15420. return this._parentedWorldMatrix;
  15421. }
  15422. return worldMatrix;
  15423. };
  15424. /**
  15425. * Sort function to order lights for rendering.
  15426. * @param a First Light object to compare to second.
  15427. * @param b Second Light object to compare first.
  15428. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15429. */
  15430. Light.compareLightsPriority = function (a, b) {
  15431. //shadow-casting lights have priority over non-shadow-casting lights
  15432. //the renderPrioirty is a secondary sort criterion
  15433. if (a.shadowEnabled !== b.shadowEnabled) {
  15434. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15435. }
  15436. return b.renderPriority - a.renderPriority;
  15437. };
  15438. /**
  15439. * Disposes the light.
  15440. */
  15441. Light.prototype.dispose = function () {
  15442. if (this._shadowGenerator) {
  15443. this._shadowGenerator.dispose();
  15444. this._shadowGenerator = null;
  15445. }
  15446. // Animations
  15447. this.getScene().stopAnimation(this);
  15448. // Remove from meshes
  15449. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15450. var mesh = _a[_i];
  15451. mesh._removeLightSource(this);
  15452. }
  15453. this._uniformBuffer.dispose();
  15454. // Remove from scene
  15455. this.getScene().removeLight(this);
  15456. _super.prototype.dispose.call(this);
  15457. };
  15458. /**
  15459. * Returns the light type ID (integer).
  15460. */
  15461. Light.prototype.getTypeID = function () {
  15462. return 0;
  15463. };
  15464. /**
  15465. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15466. */
  15467. Light.prototype.getScaledIntensity = function () {
  15468. return this._photometricScale * this.intensity;
  15469. };
  15470. /**
  15471. * Returns a new Light object, named "name", from the current one.
  15472. */
  15473. Light.prototype.clone = function (name) {
  15474. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15475. if (!constructor) {
  15476. return null;
  15477. }
  15478. return BABYLON.SerializationHelper.Clone(constructor, this);
  15479. };
  15480. /**
  15481. * Serializes the current light into a Serialization object.
  15482. * Returns the serialized object.
  15483. */
  15484. Light.prototype.serialize = function () {
  15485. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15486. // Type
  15487. serializationObject.type = this.getTypeID();
  15488. // Parent
  15489. if (this.parent) {
  15490. serializationObject.parentId = this.parent.id;
  15491. }
  15492. // Inclusion / exclusions
  15493. if (this.excludedMeshes.length > 0) {
  15494. serializationObject.excludedMeshesIds = [];
  15495. this.excludedMeshes.forEach(function (mesh) {
  15496. serializationObject.excludedMeshesIds.push(mesh.id);
  15497. });
  15498. }
  15499. if (this.includedOnlyMeshes.length > 0) {
  15500. serializationObject.includedOnlyMeshesIds = [];
  15501. this.includedOnlyMeshes.forEach(function (mesh) {
  15502. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15503. });
  15504. }
  15505. // Animations
  15506. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15507. serializationObject.ranges = this.serializeAnimationRanges();
  15508. return serializationObject;
  15509. };
  15510. /**
  15511. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15512. * This new light is named "name" and added to the passed scene.
  15513. */
  15514. Light.GetConstructorFromName = function (type, name, scene) {
  15515. switch (type) {
  15516. case 0:
  15517. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15518. case 1:
  15519. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15520. case 2:
  15521. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15522. case 3:
  15523. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15524. }
  15525. return null;
  15526. };
  15527. /**
  15528. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15529. */
  15530. Light.Parse = function (parsedLight, scene) {
  15531. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15532. if (!constructor) {
  15533. return null;
  15534. }
  15535. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15536. // Inclusion / exclusions
  15537. if (parsedLight.excludedMeshesIds) {
  15538. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15539. }
  15540. if (parsedLight.includedOnlyMeshesIds) {
  15541. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15542. }
  15543. // Parent
  15544. if (parsedLight.parentId) {
  15545. light._waitingParentId = parsedLight.parentId;
  15546. }
  15547. // Animations
  15548. if (parsedLight.animations) {
  15549. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15550. var parsedAnimation = parsedLight.animations[animationIndex];
  15551. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15552. }
  15553. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15554. }
  15555. if (parsedLight.autoAnimate) {
  15556. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15557. }
  15558. return light;
  15559. };
  15560. Light.prototype._hookArrayForExcluded = function (array) {
  15561. var _this = this;
  15562. var oldPush = array.push;
  15563. array.push = function () {
  15564. var items = [];
  15565. for (var _i = 0; _i < arguments.length; _i++) {
  15566. items[_i] = arguments[_i];
  15567. }
  15568. var result = oldPush.apply(array, items);
  15569. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15570. var item = items_1[_a];
  15571. item._resyncLighSource(_this);
  15572. }
  15573. return result;
  15574. };
  15575. var oldSplice = array.splice;
  15576. array.splice = function (index, deleteCount) {
  15577. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15578. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15579. var item = deleted_1[_i];
  15580. item._resyncLighSource(_this);
  15581. }
  15582. return deleted;
  15583. };
  15584. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15585. var item = array_1[_i];
  15586. item._resyncLighSource(this);
  15587. }
  15588. };
  15589. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15590. var _this = this;
  15591. var oldPush = array.push;
  15592. array.push = function () {
  15593. var items = [];
  15594. for (var _i = 0; _i < arguments.length; _i++) {
  15595. items[_i] = arguments[_i];
  15596. }
  15597. var result = oldPush.apply(array, items);
  15598. _this._resyncMeshes();
  15599. return result;
  15600. };
  15601. var oldSplice = array.splice;
  15602. array.splice = function (index, deleteCount) {
  15603. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15604. _this._resyncMeshes();
  15605. return deleted;
  15606. };
  15607. this._resyncMeshes();
  15608. };
  15609. Light.prototype._resyncMeshes = function () {
  15610. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15611. var mesh = _a[_i];
  15612. mesh._resyncLighSource(this);
  15613. }
  15614. };
  15615. Light.prototype._markMeshesAsLightDirty = function () {
  15616. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15617. var mesh = _a[_i];
  15618. if (mesh._lightSources.indexOf(this) !== -1) {
  15619. mesh._markSubMeshesAsLightDirty();
  15620. }
  15621. }
  15622. };
  15623. /**
  15624. * Recomputes the cached photometric scale if needed.
  15625. */
  15626. Light.prototype._computePhotometricScale = function () {
  15627. this._photometricScale = this._getPhotometricScale();
  15628. this.getScene().resetCachedMaterial();
  15629. };
  15630. /**
  15631. * Returns the Photometric Scale according to the light type and intensity mode.
  15632. */
  15633. Light.prototype._getPhotometricScale = function () {
  15634. var photometricScale = 0.0;
  15635. var lightTypeID = this.getTypeID();
  15636. //get photometric mode
  15637. var photometricMode = this.intensityMode;
  15638. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15639. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15640. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15641. }
  15642. else {
  15643. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15644. }
  15645. }
  15646. //compute photometric scale
  15647. switch (lightTypeID) {
  15648. case Light.LIGHTTYPEID_POINTLIGHT:
  15649. case Light.LIGHTTYPEID_SPOTLIGHT:
  15650. switch (photometricMode) {
  15651. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15652. photometricScale = 1.0 / (4.0 * Math.PI);
  15653. break;
  15654. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15655. photometricScale = 1.0;
  15656. break;
  15657. case Light.INTENSITYMODE_LUMINANCE:
  15658. photometricScale = this.radius * this.radius;
  15659. break;
  15660. }
  15661. break;
  15662. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15663. switch (photometricMode) {
  15664. case Light.INTENSITYMODE_ILLUMINANCE:
  15665. photometricScale = 1.0;
  15666. break;
  15667. case Light.INTENSITYMODE_LUMINANCE:
  15668. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15669. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15670. var apexAngleRadians = this.radius;
  15671. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15672. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15673. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15674. photometricScale = solidAngle;
  15675. break;
  15676. }
  15677. break;
  15678. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15679. // No fall off in hemisperic light.
  15680. photometricScale = 1.0;
  15681. break;
  15682. }
  15683. return photometricScale;
  15684. };
  15685. Light.prototype._reorderLightsInScene = function () {
  15686. var scene = this.getScene();
  15687. if (this._renderPriority != 0) {
  15688. scene.requireLightSorting = true;
  15689. }
  15690. this.getScene().sortLightsByPriority();
  15691. };
  15692. //lightmapMode Consts
  15693. Light._LIGHTMAP_DEFAULT = 0;
  15694. Light._LIGHTMAP_SPECULAR = 1;
  15695. Light._LIGHTMAP_SHADOWSONLY = 2;
  15696. // Intensity Mode Consts
  15697. Light._INTENSITYMODE_AUTOMATIC = 0;
  15698. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15699. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15700. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15701. Light._INTENSITYMODE_LUMINANCE = 4;
  15702. // Light types ids const.
  15703. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15704. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15705. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15706. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15707. __decorate([
  15708. BABYLON.serializeAsColor3()
  15709. ], Light.prototype, "diffuse", void 0);
  15710. __decorate([
  15711. BABYLON.serializeAsColor3()
  15712. ], Light.prototype, "specular", void 0);
  15713. __decorate([
  15714. BABYLON.serialize()
  15715. ], Light.prototype, "intensity", void 0);
  15716. __decorate([
  15717. BABYLON.serialize()
  15718. ], Light.prototype, "range", void 0);
  15719. __decorate([
  15720. BABYLON.serialize()
  15721. ], Light.prototype, "intensityMode", null);
  15722. __decorate([
  15723. BABYLON.serialize()
  15724. ], Light.prototype, "radius", null);
  15725. __decorate([
  15726. BABYLON.serialize()
  15727. ], Light.prototype, "_renderPriority", void 0);
  15728. __decorate([
  15729. BABYLON.expandToProperty("_reorderLightsInScene")
  15730. ], Light.prototype, "renderPriority", void 0);
  15731. __decorate([
  15732. BABYLON.serialize()
  15733. ], Light.prototype, "shadowEnabled", void 0);
  15734. __decorate([
  15735. BABYLON.serialize("excludeWithLayerMask")
  15736. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15737. __decorate([
  15738. BABYLON.serialize("includeOnlyWithLayerMask")
  15739. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15740. __decorate([
  15741. BABYLON.serialize("lightmapMode")
  15742. ], Light.prototype, "_lightmapMode", void 0);
  15743. return Light;
  15744. }(BABYLON.Node));
  15745. BABYLON.Light = Light;
  15746. })(BABYLON || (BABYLON = {}));
  15747. //# sourceMappingURL=babylon.light.js.map
  15748. var BABYLON;
  15749. (function (BABYLON) {
  15750. var Camera = /** @class */ (function (_super) {
  15751. __extends(Camera, _super);
  15752. function Camera(name, position, scene) {
  15753. var _this = _super.call(this, name, scene) || this;
  15754. _this.upVector = BABYLON.Vector3.Up();
  15755. _this.orthoLeft = null;
  15756. _this.orthoRight = null;
  15757. _this.orthoBottom = null;
  15758. _this.orthoTop = null;
  15759. _this.fov = 0.8;
  15760. _this.minZ = 1;
  15761. _this.maxZ = 10000.0;
  15762. _this.inertia = 0.9;
  15763. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15764. _this.isIntermediate = false;
  15765. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15766. _this.layerMask = 0x0FFFFFFF;
  15767. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15768. // Camera rig members
  15769. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15770. _this._rigCameras = new Array();
  15771. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15772. _this._skipRendering = false;
  15773. _this.customRenderTargets = new Array();
  15774. // Observables
  15775. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15776. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15777. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15778. _this.onRestoreStateObservable = new BABYLON.Observable();
  15779. // Cache
  15780. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15781. _this._projectionMatrix = new BABYLON.Matrix();
  15782. _this._doNotComputeProjectionMatrix = false;
  15783. _this._postProcesses = new Array();
  15784. _this._transformMatrix = BABYLON.Matrix.Zero();
  15785. _this._activeMeshes = new BABYLON.SmartArray(256);
  15786. _this._globalPosition = BABYLON.Vector3.Zero();
  15787. _this._refreshFrustumPlanes = true;
  15788. _this.getScene().addCamera(_this);
  15789. if (!_this.getScene().activeCamera) {
  15790. _this.getScene().activeCamera = _this;
  15791. }
  15792. _this.position = position;
  15793. return _this;
  15794. }
  15795. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15796. get: function () {
  15797. return Camera._PERSPECTIVE_CAMERA;
  15798. },
  15799. enumerable: true,
  15800. configurable: true
  15801. });
  15802. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15803. get: function () {
  15804. return Camera._ORTHOGRAPHIC_CAMERA;
  15805. },
  15806. enumerable: true,
  15807. configurable: true
  15808. });
  15809. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15810. get: function () {
  15811. return Camera._FOVMODE_VERTICAL_FIXED;
  15812. },
  15813. enumerable: true,
  15814. configurable: true
  15815. });
  15816. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15817. get: function () {
  15818. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15819. },
  15820. enumerable: true,
  15821. configurable: true
  15822. });
  15823. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15824. get: function () {
  15825. return Camera._RIG_MODE_NONE;
  15826. },
  15827. enumerable: true,
  15828. configurable: true
  15829. });
  15830. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15831. get: function () {
  15832. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15833. },
  15834. enumerable: true,
  15835. configurable: true
  15836. });
  15837. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15838. get: function () {
  15839. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15840. },
  15841. enumerable: true,
  15842. configurable: true
  15843. });
  15844. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15845. get: function () {
  15846. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15847. },
  15848. enumerable: true,
  15849. configurable: true
  15850. });
  15851. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15852. get: function () {
  15853. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15854. },
  15855. enumerable: true,
  15856. configurable: true
  15857. });
  15858. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15859. get: function () {
  15860. return Camera._RIG_MODE_VR;
  15861. },
  15862. enumerable: true,
  15863. configurable: true
  15864. });
  15865. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15866. get: function () {
  15867. return Camera._RIG_MODE_WEBVR;
  15868. },
  15869. enumerable: true,
  15870. configurable: true
  15871. });
  15872. /**
  15873. * Store current camera state (fov, position, etc..)
  15874. */
  15875. Camera.prototype.storeState = function () {
  15876. this._stateStored = true;
  15877. this._storedFov = this.fov;
  15878. return this;
  15879. };
  15880. /**
  15881. * Restores the camera state values if it has been stored. You must call storeState() first
  15882. */
  15883. Camera.prototype._restoreStateValues = function () {
  15884. if (!this._stateStored) {
  15885. return false;
  15886. }
  15887. this.fov = this._storedFov;
  15888. return true;
  15889. };
  15890. /**
  15891. * Restored camera state. You must call storeState() first
  15892. */
  15893. Camera.prototype.restoreState = function () {
  15894. if (this._restoreStateValues()) {
  15895. this.onRestoreStateObservable.notifyObservers(this);
  15896. return true;
  15897. }
  15898. return false;
  15899. };
  15900. Camera.prototype.getClassName = function () {
  15901. return "Camera";
  15902. };
  15903. /**
  15904. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15905. */
  15906. Camera.prototype.toString = function (fullDetails) {
  15907. var ret = "Name: " + this.name;
  15908. ret += ", type: " + this.getClassName();
  15909. if (this.animations) {
  15910. for (var i = 0; i < this.animations.length; i++) {
  15911. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15912. }
  15913. }
  15914. if (fullDetails) {
  15915. }
  15916. return ret;
  15917. };
  15918. Object.defineProperty(Camera.prototype, "globalPosition", {
  15919. get: function () {
  15920. return this._globalPosition;
  15921. },
  15922. enumerable: true,
  15923. configurable: true
  15924. });
  15925. Camera.prototype.getActiveMeshes = function () {
  15926. return this._activeMeshes;
  15927. };
  15928. Camera.prototype.isActiveMesh = function (mesh) {
  15929. return (this._activeMeshes.indexOf(mesh) !== -1);
  15930. };
  15931. //Cache
  15932. Camera.prototype._initCache = function () {
  15933. _super.prototype._initCache.call(this);
  15934. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15935. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15936. this._cache.mode = undefined;
  15937. this._cache.minZ = undefined;
  15938. this._cache.maxZ = undefined;
  15939. this._cache.fov = undefined;
  15940. this._cache.fovMode = undefined;
  15941. this._cache.aspectRatio = undefined;
  15942. this._cache.orthoLeft = undefined;
  15943. this._cache.orthoRight = undefined;
  15944. this._cache.orthoBottom = undefined;
  15945. this._cache.orthoTop = undefined;
  15946. this._cache.renderWidth = undefined;
  15947. this._cache.renderHeight = undefined;
  15948. };
  15949. Camera.prototype._updateCache = function (ignoreParentClass) {
  15950. if (!ignoreParentClass) {
  15951. _super.prototype._updateCache.call(this);
  15952. }
  15953. this._cache.position.copyFrom(this.position);
  15954. this._cache.upVector.copyFrom(this.upVector);
  15955. };
  15956. // Synchronized
  15957. Camera.prototype._isSynchronized = function () {
  15958. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15959. };
  15960. Camera.prototype._isSynchronizedViewMatrix = function () {
  15961. if (!_super.prototype._isSynchronized.call(this))
  15962. return false;
  15963. return this._cache.position.equals(this.position)
  15964. && this._cache.upVector.equals(this.upVector)
  15965. && this.isSynchronizedWithParent();
  15966. };
  15967. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15968. var check = this._cache.mode === this.mode
  15969. && this._cache.minZ === this.minZ
  15970. && this._cache.maxZ === this.maxZ;
  15971. if (!check) {
  15972. return false;
  15973. }
  15974. var engine = this.getEngine();
  15975. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15976. check = this._cache.fov === this.fov
  15977. && this._cache.fovMode === this.fovMode
  15978. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15979. }
  15980. else {
  15981. check = this._cache.orthoLeft === this.orthoLeft
  15982. && this._cache.orthoRight === this.orthoRight
  15983. && this._cache.orthoBottom === this.orthoBottom
  15984. && this._cache.orthoTop === this.orthoTop
  15985. && this._cache.renderWidth === engine.getRenderWidth()
  15986. && this._cache.renderHeight === engine.getRenderHeight();
  15987. }
  15988. return check;
  15989. };
  15990. // Controls
  15991. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15992. };
  15993. Camera.prototype.detachControl = function (element) {
  15994. };
  15995. Camera.prototype.update = function () {
  15996. this._checkInputs();
  15997. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15998. this._updateRigCameras();
  15999. }
  16000. };
  16001. Camera.prototype._checkInputs = function () {
  16002. this.onAfterCheckInputsObservable.notifyObservers(this);
  16003. };
  16004. Object.defineProperty(Camera.prototype, "rigCameras", {
  16005. get: function () {
  16006. return this._rigCameras;
  16007. },
  16008. enumerable: true,
  16009. configurable: true
  16010. });
  16011. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16012. get: function () {
  16013. return this._rigPostProcess;
  16014. },
  16015. enumerable: true,
  16016. configurable: true
  16017. });
  16018. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16019. // invalidate framebuffer
  16020. if (this._postProcesses.length > 0) {
  16021. this._postProcesses[0].markTextureDirty();
  16022. }
  16023. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16024. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16025. var cam = this._rigCameras[i];
  16026. var rigPostProcess = cam._rigPostProcess;
  16027. // for VR rig, there does not have to be a post process
  16028. if (rigPostProcess) {
  16029. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16030. if (isPass) {
  16031. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16032. cam.isIntermediate = this._postProcesses.length === 0;
  16033. }
  16034. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16035. rigPostProcess.markTextureDirty();
  16036. }
  16037. else {
  16038. cam._postProcesses = this._postProcesses.slice(0);
  16039. }
  16040. }
  16041. };
  16042. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16043. if (insertAt === void 0) { insertAt = null; }
  16044. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16045. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16046. return 0;
  16047. }
  16048. if (insertAt == null || insertAt < 0) {
  16049. this._postProcesses.push(postProcess);
  16050. }
  16051. else {
  16052. this._postProcesses.splice(insertAt, 0, postProcess);
  16053. }
  16054. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16055. return this._postProcesses.indexOf(postProcess);
  16056. };
  16057. Camera.prototype.detachPostProcess = function (postProcess) {
  16058. var idx = this._postProcesses.indexOf(postProcess);
  16059. if (idx !== -1) {
  16060. this._postProcesses.splice(idx, 1);
  16061. }
  16062. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16063. };
  16064. Camera.prototype.getWorldMatrix = function () {
  16065. if (!this._worldMatrix) {
  16066. this._worldMatrix = BABYLON.Matrix.Identity();
  16067. }
  16068. var viewMatrix = this.getViewMatrix();
  16069. viewMatrix.invertToRef(this._worldMatrix);
  16070. return this._worldMatrix;
  16071. };
  16072. Camera.prototype._getViewMatrix = function () {
  16073. return BABYLON.Matrix.Identity();
  16074. };
  16075. Camera.prototype.getViewMatrix = function (force) {
  16076. if (!force && this._isSynchronizedViewMatrix()) {
  16077. return this._computedViewMatrix;
  16078. }
  16079. this.updateCache();
  16080. this._computedViewMatrix = this._getViewMatrix();
  16081. this._currentRenderId = this.getScene().getRenderId();
  16082. this._refreshFrustumPlanes = true;
  16083. if (!this.parent || !this.parent.getWorldMatrix) {
  16084. this._globalPosition.copyFrom(this.position);
  16085. }
  16086. else {
  16087. if (!this._worldMatrix) {
  16088. this._worldMatrix = BABYLON.Matrix.Identity();
  16089. }
  16090. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16091. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16092. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16093. this._computedViewMatrix.invert();
  16094. this._markSyncedWithParent();
  16095. }
  16096. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16097. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16098. }
  16099. this.onViewMatrixChangedObservable.notifyObservers(this);
  16100. return this._computedViewMatrix;
  16101. };
  16102. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16103. this._doNotComputeProjectionMatrix = true;
  16104. if (projection !== undefined) {
  16105. this._projectionMatrix = projection;
  16106. }
  16107. };
  16108. ;
  16109. Camera.prototype.unfreezeProjectionMatrix = function () {
  16110. this._doNotComputeProjectionMatrix = false;
  16111. };
  16112. ;
  16113. Camera.prototype.getProjectionMatrix = function (force) {
  16114. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16115. return this._projectionMatrix;
  16116. }
  16117. // Cache
  16118. this._cache.mode = this.mode;
  16119. this._cache.minZ = this.minZ;
  16120. this._cache.maxZ = this.maxZ;
  16121. // Matrix
  16122. this._refreshFrustumPlanes = true;
  16123. var engine = this.getEngine();
  16124. var scene = this.getScene();
  16125. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16126. this._cache.fov = this.fov;
  16127. this._cache.fovMode = this.fovMode;
  16128. this._cache.aspectRatio = engine.getAspectRatio(this);
  16129. if (this.minZ <= 0) {
  16130. this.minZ = 0.1;
  16131. }
  16132. if (scene.useRightHandedSystem) {
  16133. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16134. }
  16135. else {
  16136. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16137. }
  16138. }
  16139. else {
  16140. var halfWidth = engine.getRenderWidth() / 2.0;
  16141. var halfHeight = engine.getRenderHeight() / 2.0;
  16142. if (scene.useRightHandedSystem) {
  16143. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16144. }
  16145. else {
  16146. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16147. }
  16148. this._cache.orthoLeft = this.orthoLeft;
  16149. this._cache.orthoRight = this.orthoRight;
  16150. this._cache.orthoBottom = this.orthoBottom;
  16151. this._cache.orthoTop = this.orthoTop;
  16152. this._cache.renderWidth = engine.getRenderWidth();
  16153. this._cache.renderHeight = engine.getRenderHeight();
  16154. }
  16155. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16156. return this._projectionMatrix;
  16157. };
  16158. Camera.prototype.getTranformationMatrix = function () {
  16159. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16160. return this._transformMatrix;
  16161. };
  16162. Camera.prototype.updateFrustumPlanes = function () {
  16163. if (!this._refreshFrustumPlanes) {
  16164. return;
  16165. }
  16166. this.getTranformationMatrix();
  16167. if (!this._frustumPlanes) {
  16168. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16169. }
  16170. else {
  16171. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16172. }
  16173. this._refreshFrustumPlanes = false;
  16174. };
  16175. Camera.prototype.isInFrustum = function (target) {
  16176. this.updateFrustumPlanes();
  16177. return target.isInFrustum(this._frustumPlanes);
  16178. };
  16179. Camera.prototype.isCompletelyInFrustum = function (target) {
  16180. this.updateFrustumPlanes();
  16181. return target.isCompletelyInFrustum(this._frustumPlanes);
  16182. };
  16183. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16184. if (length === void 0) { length = 100; }
  16185. if (!transform) {
  16186. transform = this.getWorldMatrix();
  16187. }
  16188. if (!origin) {
  16189. origin = this.position;
  16190. }
  16191. var forward = new BABYLON.Vector3(0, 0, 1);
  16192. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16193. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16194. return new BABYLON.Ray(origin, direction, length);
  16195. };
  16196. Camera.prototype.dispose = function () {
  16197. // Observables
  16198. this.onViewMatrixChangedObservable.clear();
  16199. this.onProjectionMatrixChangedObservable.clear();
  16200. this.onAfterCheckInputsObservable.clear();
  16201. this.onRestoreStateObservable.clear();
  16202. // Inputs
  16203. if (this.inputs) {
  16204. this.inputs.clear();
  16205. }
  16206. // Animations
  16207. this.getScene().stopAnimation(this);
  16208. // Remove from scene
  16209. this.getScene().removeCamera(this);
  16210. while (this._rigCameras.length > 0) {
  16211. var camera = this._rigCameras.pop();
  16212. if (camera) {
  16213. camera.dispose();
  16214. }
  16215. }
  16216. // Postprocesses
  16217. if (this._rigPostProcess) {
  16218. this._rigPostProcess.dispose(this);
  16219. this._rigPostProcess = null;
  16220. this._postProcesses = [];
  16221. }
  16222. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16223. this._rigPostProcess = null;
  16224. this._postProcesses = [];
  16225. }
  16226. else {
  16227. var i = this._postProcesses.length;
  16228. while (--i >= 0) {
  16229. this._postProcesses[i].dispose(this);
  16230. }
  16231. }
  16232. // Render targets
  16233. var i = this.customRenderTargets.length;
  16234. while (--i >= 0) {
  16235. this.customRenderTargets[i].dispose();
  16236. }
  16237. this.customRenderTargets = [];
  16238. // Active Meshes
  16239. this._activeMeshes.dispose();
  16240. _super.prototype.dispose.call(this);
  16241. };
  16242. Object.defineProperty(Camera.prototype, "leftCamera", {
  16243. // ---- Camera rigs section ----
  16244. get: function () {
  16245. if (this._rigCameras.length < 1) {
  16246. return null;
  16247. }
  16248. return this._rigCameras[0];
  16249. },
  16250. enumerable: true,
  16251. configurable: true
  16252. });
  16253. Object.defineProperty(Camera.prototype, "rightCamera", {
  16254. get: function () {
  16255. if (this._rigCameras.length < 2) {
  16256. return null;
  16257. }
  16258. return this._rigCameras[1];
  16259. },
  16260. enumerable: true,
  16261. configurable: true
  16262. });
  16263. Camera.prototype.getLeftTarget = function () {
  16264. if (this._rigCameras.length < 1) {
  16265. return null;
  16266. }
  16267. return this._rigCameras[0].getTarget();
  16268. };
  16269. Camera.prototype.getRightTarget = function () {
  16270. if (this._rigCameras.length < 2) {
  16271. return null;
  16272. }
  16273. return this._rigCameras[1].getTarget();
  16274. };
  16275. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16276. if (this.cameraRigMode === mode) {
  16277. return;
  16278. }
  16279. while (this._rigCameras.length > 0) {
  16280. var camera = this._rigCameras.pop();
  16281. if (camera) {
  16282. camera.dispose();
  16283. }
  16284. }
  16285. this.cameraRigMode = mode;
  16286. this._cameraRigParams = {};
  16287. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16288. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16289. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16290. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16291. // create the rig cameras, unless none
  16292. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16293. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16294. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16295. if (leftCamera && rightCamera) {
  16296. this._rigCameras.push(leftCamera);
  16297. this._rigCameras.push(rightCamera);
  16298. }
  16299. }
  16300. switch (this.cameraRigMode) {
  16301. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16302. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16303. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16304. break;
  16305. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16306. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16307. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16308. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16309. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16310. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16311. break;
  16312. case Camera.RIG_MODE_VR:
  16313. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16314. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16315. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16316. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16317. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16318. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16319. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16320. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16321. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16322. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16323. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16324. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16325. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16326. if (metrics.compensateDistortion) {
  16327. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16328. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16329. }
  16330. break;
  16331. case Camera.RIG_MODE_WEBVR:
  16332. if (rigParams.vrDisplay) {
  16333. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16334. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16335. //Left eye
  16336. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16337. this._rigCameras[0].setCameraRigParameter("left", true);
  16338. //leaving this for future reference
  16339. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16340. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16341. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16342. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16343. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16344. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16345. this._rigCameras[0].parent = this;
  16346. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16347. //Right eye
  16348. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16349. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16350. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16351. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16352. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16353. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16354. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16355. this._rigCameras[1].parent = this;
  16356. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16357. if (Camera.UseAlternateWebVRRendering) {
  16358. this._rigCameras[1]._skipRendering = true;
  16359. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16360. }
  16361. }
  16362. break;
  16363. }
  16364. this._cascadePostProcessesToRigCams();
  16365. this.update();
  16366. };
  16367. Camera.prototype._getVRProjectionMatrix = function () {
  16368. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16369. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16370. return this._projectionMatrix;
  16371. };
  16372. Camera.prototype._updateCameraRotationMatrix = function () {
  16373. //Here for WebVR
  16374. };
  16375. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16376. //Here for WebVR
  16377. };
  16378. /**
  16379. * This function MUST be overwritten by the different WebVR cameras available.
  16380. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16381. */
  16382. Camera.prototype._getWebVRProjectionMatrix = function () {
  16383. return BABYLON.Matrix.Identity();
  16384. };
  16385. /**
  16386. * This function MUST be overwritten by the different WebVR cameras available.
  16387. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16388. */
  16389. Camera.prototype._getWebVRViewMatrix = function () {
  16390. return BABYLON.Matrix.Identity();
  16391. };
  16392. Camera.prototype.setCameraRigParameter = function (name, value) {
  16393. if (!this._cameraRigParams) {
  16394. this._cameraRigParams = {};
  16395. }
  16396. this._cameraRigParams[name] = value;
  16397. //provisionnally:
  16398. if (name === "interaxialDistance") {
  16399. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16400. }
  16401. };
  16402. /**
  16403. * needs to be overridden by children so sub has required properties to be copied
  16404. */
  16405. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16406. return null;
  16407. };
  16408. /**
  16409. * May need to be overridden by children
  16410. */
  16411. Camera.prototype._updateRigCameras = function () {
  16412. for (var i = 0; i < this._rigCameras.length; i++) {
  16413. this._rigCameras[i].minZ = this.minZ;
  16414. this._rigCameras[i].maxZ = this.maxZ;
  16415. this._rigCameras[i].fov = this.fov;
  16416. }
  16417. // only update viewport when ANAGLYPH
  16418. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16419. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16420. }
  16421. };
  16422. Camera.prototype._setupInputs = function () {
  16423. };
  16424. Camera.prototype.serialize = function () {
  16425. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16426. // Type
  16427. serializationObject.type = this.getClassName();
  16428. // Parent
  16429. if (this.parent) {
  16430. serializationObject.parentId = this.parent.id;
  16431. }
  16432. if (this.inputs) {
  16433. this.inputs.serialize(serializationObject);
  16434. }
  16435. // Animations
  16436. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16437. serializationObject.ranges = this.serializeAnimationRanges();
  16438. return serializationObject;
  16439. };
  16440. Camera.prototype.clone = function (name) {
  16441. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16442. };
  16443. Camera.prototype.getDirection = function (localAxis) {
  16444. var result = BABYLON.Vector3.Zero();
  16445. this.getDirectionToRef(localAxis, result);
  16446. return result;
  16447. };
  16448. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16449. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16450. };
  16451. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16452. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16453. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16454. switch (type) {
  16455. case "ArcRotateCamera":
  16456. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16457. case "DeviceOrientationCamera":
  16458. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16459. case "FollowCamera":
  16460. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16461. case "ArcFollowCamera":
  16462. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16463. case "GamepadCamera":
  16464. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16465. case "TouchCamera":
  16466. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16467. case "VirtualJoysticksCamera":
  16468. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16469. case "WebVRFreeCamera":
  16470. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16471. case "WebVRGamepadCamera":
  16472. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16473. case "VRDeviceOrientationFreeCamera":
  16474. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16475. case "VRDeviceOrientationGamepadCamera":
  16476. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16477. case "AnaglyphArcRotateCamera":
  16478. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16479. case "AnaglyphFreeCamera":
  16480. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16481. case "AnaglyphGamepadCamera":
  16482. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16483. case "AnaglyphUniversalCamera":
  16484. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16485. case "StereoscopicArcRotateCamera":
  16486. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16487. case "StereoscopicFreeCamera":
  16488. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16489. case "StereoscopicGamepadCamera":
  16490. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16491. case "StereoscopicUniversalCamera":
  16492. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16493. case "FreeCamera":// Forcing Universal here
  16494. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16495. default:// Universal Camera is the default value
  16496. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16497. }
  16498. };
  16499. Camera.Parse = function (parsedCamera, scene) {
  16500. var type = parsedCamera.type;
  16501. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16502. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16503. // Parent
  16504. if (parsedCamera.parentId) {
  16505. camera._waitingParentId = parsedCamera.parentId;
  16506. }
  16507. //If camera has an input manager, let it parse inputs settings
  16508. if (camera.inputs) {
  16509. camera.inputs.parse(parsedCamera);
  16510. camera._setupInputs();
  16511. }
  16512. if (camera.setPosition) {
  16513. camera.position.copyFromFloats(0, 0, 0);
  16514. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16515. }
  16516. // Target
  16517. if (parsedCamera.target) {
  16518. if (camera.setTarget) {
  16519. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16520. }
  16521. }
  16522. // Apply 3d rig, when found
  16523. if (parsedCamera.cameraRigMode) {
  16524. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16525. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16526. }
  16527. // Animations
  16528. if (parsedCamera.animations) {
  16529. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16530. var parsedAnimation = parsedCamera.animations[animationIndex];
  16531. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16532. }
  16533. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16534. }
  16535. if (parsedCamera.autoAnimate) {
  16536. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16537. }
  16538. return camera;
  16539. };
  16540. // Statics
  16541. Camera._PERSPECTIVE_CAMERA = 0;
  16542. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16543. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16544. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16545. Camera._RIG_MODE_NONE = 0;
  16546. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16547. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16548. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16549. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16550. Camera._RIG_MODE_VR = 20;
  16551. Camera._RIG_MODE_WEBVR = 21;
  16552. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16553. Camera.UseAlternateWebVRRendering = false;
  16554. __decorate([
  16555. BABYLON.serializeAsVector3()
  16556. ], Camera.prototype, "position", void 0);
  16557. __decorate([
  16558. BABYLON.serializeAsVector3()
  16559. ], Camera.prototype, "upVector", void 0);
  16560. __decorate([
  16561. BABYLON.serialize()
  16562. ], Camera.prototype, "orthoLeft", void 0);
  16563. __decorate([
  16564. BABYLON.serialize()
  16565. ], Camera.prototype, "orthoRight", void 0);
  16566. __decorate([
  16567. BABYLON.serialize()
  16568. ], Camera.prototype, "orthoBottom", void 0);
  16569. __decorate([
  16570. BABYLON.serialize()
  16571. ], Camera.prototype, "orthoTop", void 0);
  16572. __decorate([
  16573. BABYLON.serialize()
  16574. ], Camera.prototype, "fov", void 0);
  16575. __decorate([
  16576. BABYLON.serialize()
  16577. ], Camera.prototype, "minZ", void 0);
  16578. __decorate([
  16579. BABYLON.serialize()
  16580. ], Camera.prototype, "maxZ", void 0);
  16581. __decorate([
  16582. BABYLON.serialize()
  16583. ], Camera.prototype, "inertia", void 0);
  16584. __decorate([
  16585. BABYLON.serialize()
  16586. ], Camera.prototype, "mode", void 0);
  16587. __decorate([
  16588. BABYLON.serialize()
  16589. ], Camera.prototype, "layerMask", void 0);
  16590. __decorate([
  16591. BABYLON.serialize()
  16592. ], Camera.prototype, "fovMode", void 0);
  16593. __decorate([
  16594. BABYLON.serialize()
  16595. ], Camera.prototype, "cameraRigMode", void 0);
  16596. __decorate([
  16597. BABYLON.serialize()
  16598. ], Camera.prototype, "interaxialDistance", void 0);
  16599. __decorate([
  16600. BABYLON.serialize()
  16601. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16602. return Camera;
  16603. }(BABYLON.Node));
  16604. BABYLON.Camera = Camera;
  16605. })(BABYLON || (BABYLON = {}));
  16606. //# sourceMappingURL=babylon.camera.js.map
  16607. var BABYLON;
  16608. (function (BABYLON) {
  16609. var RenderingManager = /** @class */ (function () {
  16610. function RenderingManager(scene) {
  16611. this._renderingGroups = new Array();
  16612. this._autoClearDepthStencil = {};
  16613. this._customOpaqueSortCompareFn = {};
  16614. this._customAlphaTestSortCompareFn = {};
  16615. this._customTransparentSortCompareFn = {};
  16616. this._renderinGroupInfo = null;
  16617. this._scene = scene;
  16618. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16619. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16620. }
  16621. }
  16622. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16623. if (depth === void 0) { depth = true; }
  16624. if (stencil === void 0) { stencil = true; }
  16625. if (this._depthStencilBufferAlreadyCleaned) {
  16626. return;
  16627. }
  16628. this._scene.getEngine().clear(null, false, depth, stencil);
  16629. this._depthStencilBufferAlreadyCleaned = true;
  16630. };
  16631. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16632. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16633. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16634. var info = null;
  16635. if (observable) {
  16636. if (!this._renderinGroupInfo) {
  16637. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16638. }
  16639. info = this._renderinGroupInfo;
  16640. info.scene = this._scene;
  16641. info.camera = this._scene.activeCamera;
  16642. }
  16643. // Dispatch sprites
  16644. if (renderSprites) {
  16645. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16646. var manager = this._scene.spriteManagers[index];
  16647. this.dispatchSprites(manager);
  16648. }
  16649. }
  16650. // Render
  16651. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16652. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16653. var renderingGroup = this._renderingGroups[index];
  16654. if (!renderingGroup && !observable)
  16655. continue;
  16656. this._currentIndex = index;
  16657. var renderingGroupMask = 0;
  16658. // Fire PRECLEAR stage
  16659. if (observable && info) {
  16660. renderingGroupMask = Math.pow(2, index);
  16661. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16662. info.renderingGroupId = index;
  16663. observable.notifyObservers(info, renderingGroupMask);
  16664. }
  16665. // Clear depth/stencil if needed
  16666. if (RenderingManager.AUTOCLEAR) {
  16667. var autoClear = this._autoClearDepthStencil[index];
  16668. if (autoClear && autoClear.autoClear) {
  16669. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16670. }
  16671. }
  16672. if (observable && info) {
  16673. // Fire PREOPAQUE stage
  16674. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16675. observable.notifyObservers(info, renderingGroupMask);
  16676. // Fire PRETRANSPARENT stage
  16677. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16678. observable.notifyObservers(info, renderingGroupMask);
  16679. }
  16680. if (renderingGroup)
  16681. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16682. // Fire POSTTRANSPARENT stage
  16683. if (observable && info) {
  16684. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16685. observable.notifyObservers(info, renderingGroupMask);
  16686. }
  16687. }
  16688. };
  16689. RenderingManager.prototype.reset = function () {
  16690. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16691. var renderingGroup = this._renderingGroups[index];
  16692. if (renderingGroup) {
  16693. renderingGroup.prepare();
  16694. }
  16695. }
  16696. };
  16697. RenderingManager.prototype.dispose = function () {
  16698. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16699. var renderingGroup = this._renderingGroups[index];
  16700. if (renderingGroup) {
  16701. renderingGroup.dispose();
  16702. }
  16703. }
  16704. this._renderingGroups.length = 0;
  16705. };
  16706. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16707. if (!this._renderingGroups[renderingGroupId]) {
  16708. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16709. }
  16710. };
  16711. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16712. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16713. this._prepareRenderingGroup(renderingGroupId);
  16714. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16715. };
  16716. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16717. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16718. this._prepareRenderingGroup(renderingGroupId);
  16719. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16720. };
  16721. RenderingManager.prototype.dispatch = function (subMesh) {
  16722. var mesh = subMesh.getMesh();
  16723. var renderingGroupId = mesh.renderingGroupId || 0;
  16724. this._prepareRenderingGroup(renderingGroupId);
  16725. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16726. };
  16727. /**
  16728. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16729. * This allowed control for front to back rendering or reversly depending of the special needs.
  16730. *
  16731. * @param renderingGroupId The rendering group id corresponding to its index
  16732. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16733. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16734. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16735. */
  16736. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16737. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16738. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16739. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16740. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16741. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16742. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16743. if (this._renderingGroups[renderingGroupId]) {
  16744. var group = this._renderingGroups[renderingGroupId];
  16745. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16746. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16747. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16748. }
  16749. };
  16750. /**
  16751. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16752. *
  16753. * @param renderingGroupId The rendering group id corresponding to its index
  16754. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16755. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16756. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16757. */
  16758. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16759. if (depth === void 0) { depth = true; }
  16760. if (stencil === void 0) { stencil = true; }
  16761. this._autoClearDepthStencil[renderingGroupId] = {
  16762. autoClear: autoClearDepthStencil,
  16763. depth: depth,
  16764. stencil: stencil
  16765. };
  16766. };
  16767. /**
  16768. * The max id used for rendering groups (not included)
  16769. */
  16770. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16771. /**
  16772. * The min id used for rendering groups (included)
  16773. */
  16774. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16775. /**
  16776. * Used to globally prevent autoclearing scenes.
  16777. */
  16778. RenderingManager.AUTOCLEAR = true;
  16779. return RenderingManager;
  16780. }());
  16781. BABYLON.RenderingManager = RenderingManager;
  16782. })(BABYLON || (BABYLON = {}));
  16783. //# sourceMappingURL=babylon.renderingManager.js.map
  16784. var BABYLON;
  16785. (function (BABYLON) {
  16786. var RenderingGroup = /** @class */ (function () {
  16787. /**
  16788. * Creates a new rendering group.
  16789. * @param index The rendering group index
  16790. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16791. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16792. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16793. */
  16794. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16795. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16796. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16797. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16798. this.index = index;
  16799. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16800. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16801. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16802. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16803. this._particleSystems = new BABYLON.SmartArray(256);
  16804. this._spriteManagers = new BABYLON.SmartArray(256);
  16805. this._edgesRenderers = new BABYLON.SmartArray(16);
  16806. this._scene = scene;
  16807. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16808. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16809. this.transparentSortCompareFn = transparentSortCompareFn;
  16810. }
  16811. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16812. /**
  16813. * Set the opaque sort comparison function.
  16814. * If null the sub meshes will be render in the order they were created
  16815. */
  16816. set: function (value) {
  16817. this._opaqueSortCompareFn = value;
  16818. if (value) {
  16819. this._renderOpaque = this.renderOpaqueSorted;
  16820. }
  16821. else {
  16822. this._renderOpaque = RenderingGroup.renderUnsorted;
  16823. }
  16824. },
  16825. enumerable: true,
  16826. configurable: true
  16827. });
  16828. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16829. /**
  16830. * Set the alpha test sort comparison function.
  16831. * If null the sub meshes will be render in the order they were created
  16832. */
  16833. set: function (value) {
  16834. this._alphaTestSortCompareFn = value;
  16835. if (value) {
  16836. this._renderAlphaTest = this.renderAlphaTestSorted;
  16837. }
  16838. else {
  16839. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16840. }
  16841. },
  16842. enumerable: true,
  16843. configurable: true
  16844. });
  16845. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16846. /**
  16847. * Set the transparent sort comparison function.
  16848. * If null the sub meshes will be render in the order they were created
  16849. */
  16850. set: function (value) {
  16851. if (value) {
  16852. this._transparentSortCompareFn = value;
  16853. }
  16854. else {
  16855. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16856. }
  16857. this._renderTransparent = this.renderTransparentSorted;
  16858. },
  16859. enumerable: true,
  16860. configurable: true
  16861. });
  16862. /**
  16863. * Render all the sub meshes contained in the group.
  16864. * @param customRenderFunction Used to override the default render behaviour of the group.
  16865. * @returns true if rendered some submeshes.
  16866. */
  16867. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16868. if (customRenderFunction) {
  16869. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16870. return;
  16871. }
  16872. var engine = this._scene.getEngine();
  16873. // Depth only
  16874. if (this._depthOnlySubMeshes.length !== 0) {
  16875. engine.setAlphaTesting(true);
  16876. engine.setColorWrite(false);
  16877. this._renderAlphaTest(this._depthOnlySubMeshes);
  16878. engine.setAlphaTesting(false);
  16879. engine.setColorWrite(true);
  16880. }
  16881. // Opaque
  16882. if (this._opaqueSubMeshes.length !== 0) {
  16883. this._renderOpaque(this._opaqueSubMeshes);
  16884. }
  16885. // Alpha test
  16886. if (this._alphaTestSubMeshes.length !== 0) {
  16887. engine.setAlphaTesting(true);
  16888. this._renderAlphaTest(this._alphaTestSubMeshes);
  16889. engine.setAlphaTesting(false);
  16890. }
  16891. var stencilState = engine.getStencilBuffer();
  16892. engine.setStencilBuffer(false);
  16893. // Sprites
  16894. if (renderSprites) {
  16895. this._renderSprites();
  16896. }
  16897. // Particles
  16898. if (renderParticles) {
  16899. this._renderParticles(activeMeshes);
  16900. }
  16901. if (this.onBeforeTransparentRendering) {
  16902. this.onBeforeTransparentRendering();
  16903. }
  16904. // Transparent
  16905. if (this._transparentSubMeshes.length !== 0) {
  16906. this._renderTransparent(this._transparentSubMeshes);
  16907. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16908. }
  16909. // Set back stencil to false in case it changes before the edge renderer.
  16910. engine.setStencilBuffer(false);
  16911. // Edges
  16912. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16913. this._edgesRenderers.data[edgesRendererIndex].render();
  16914. }
  16915. // Restore Stencil state.
  16916. engine.setStencilBuffer(stencilState);
  16917. };
  16918. /**
  16919. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16920. * @param subMeshes The submeshes to render
  16921. */
  16922. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16923. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  16924. };
  16925. /**
  16926. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16927. * @param subMeshes The submeshes to render
  16928. */
  16929. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16930. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  16931. };
  16932. /**
  16933. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16934. * @param subMeshes The submeshes to render
  16935. */
  16936. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16937. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  16938. };
  16939. /**
  16940. * Renders the submeshes in a specified order.
  16941. * @param subMeshes The submeshes to sort before render
  16942. * @param sortCompareFn The comparison function use to sort
  16943. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16944. * @param transparent Specifies to activate blending if true
  16945. */
  16946. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  16947. var subIndex = 0;
  16948. var subMesh;
  16949. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  16950. for (; subIndex < subMeshes.length; subIndex++) {
  16951. subMesh = subMeshes.data[subIndex];
  16952. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16953. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16954. }
  16955. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16956. if (sortCompareFn) {
  16957. sortedArray.sort(sortCompareFn);
  16958. }
  16959. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16960. subMesh = sortedArray[subIndex];
  16961. if (transparent) {
  16962. var material = subMesh.getMaterial();
  16963. if (material && material.needDepthPrePass) {
  16964. var engine = material.getScene().getEngine();
  16965. engine.setColorWrite(false);
  16966. engine.setAlphaTesting(true);
  16967. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16968. subMesh.render(false);
  16969. engine.setAlphaTesting(false);
  16970. engine.setColorWrite(true);
  16971. }
  16972. }
  16973. subMesh.render(transparent);
  16974. }
  16975. };
  16976. /**
  16977. * Renders the submeshes in the order they were dispatched (no sort applied).
  16978. * @param subMeshes The submeshes to render
  16979. */
  16980. RenderingGroup.renderUnsorted = function (subMeshes) {
  16981. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16982. var submesh = subMeshes.data[subIndex];
  16983. submesh.render(false);
  16984. }
  16985. };
  16986. /**
  16987. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16988. * are rendered back to front if in the same alpha index.
  16989. *
  16990. * @param a The first submesh
  16991. * @param b The second submesh
  16992. * @returns The result of the comparison
  16993. */
  16994. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16995. // Alpha index first
  16996. if (a._alphaIndex > b._alphaIndex) {
  16997. return 1;
  16998. }
  16999. if (a._alphaIndex < b._alphaIndex) {
  17000. return -1;
  17001. }
  17002. // Then distance to camera
  17003. return RenderingGroup.backToFrontSortCompare(a, b);
  17004. };
  17005. /**
  17006. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17007. * are rendered back to front.
  17008. *
  17009. * @param a The first submesh
  17010. * @param b The second submesh
  17011. * @returns The result of the comparison
  17012. */
  17013. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17014. // Then distance to camera
  17015. if (a._distanceToCamera < b._distanceToCamera) {
  17016. return 1;
  17017. }
  17018. if (a._distanceToCamera > b._distanceToCamera) {
  17019. return -1;
  17020. }
  17021. return 0;
  17022. };
  17023. /**
  17024. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17025. * are rendered front to back (prevent overdraw).
  17026. *
  17027. * @param a The first submesh
  17028. * @param b The second submesh
  17029. * @returns The result of the comparison
  17030. */
  17031. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17032. // Then distance to camera
  17033. if (a._distanceToCamera < b._distanceToCamera) {
  17034. return -1;
  17035. }
  17036. if (a._distanceToCamera > b._distanceToCamera) {
  17037. return 1;
  17038. }
  17039. return 0;
  17040. };
  17041. /**
  17042. * Resets the different lists of submeshes to prepare a new frame.
  17043. */
  17044. RenderingGroup.prototype.prepare = function () {
  17045. this._opaqueSubMeshes.reset();
  17046. this._transparentSubMeshes.reset();
  17047. this._alphaTestSubMeshes.reset();
  17048. this._depthOnlySubMeshes.reset();
  17049. this._particleSystems.reset();
  17050. this._spriteManagers.reset();
  17051. this._edgesRenderers.reset();
  17052. };
  17053. RenderingGroup.prototype.dispose = function () {
  17054. this._opaqueSubMeshes.dispose();
  17055. this._transparentSubMeshes.dispose();
  17056. this._alphaTestSubMeshes.dispose();
  17057. this._depthOnlySubMeshes.dispose();
  17058. this._particleSystems.dispose();
  17059. this._spriteManagers.dispose();
  17060. this._edgesRenderers.dispose();
  17061. };
  17062. /**
  17063. * Inserts the submesh in its correct queue depending on its material.
  17064. * @param subMesh The submesh to dispatch
  17065. */
  17066. RenderingGroup.prototype.dispatch = function (subMesh) {
  17067. var material = subMesh.getMaterial();
  17068. var mesh = subMesh.getMesh();
  17069. if (!material) {
  17070. return;
  17071. }
  17072. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  17073. this._transparentSubMeshes.push(subMesh);
  17074. }
  17075. else if (material.needAlphaTesting()) {
  17076. if (material.needDepthPrePass) {
  17077. this._depthOnlySubMeshes.push(subMesh);
  17078. }
  17079. this._alphaTestSubMeshes.push(subMesh);
  17080. }
  17081. else {
  17082. if (material.needDepthPrePass) {
  17083. this._depthOnlySubMeshes.push(subMesh);
  17084. }
  17085. this._opaqueSubMeshes.push(subMesh); // Opaque
  17086. }
  17087. if (mesh._edgesRenderer) {
  17088. this._edgesRenderers.push(mesh._edgesRenderer);
  17089. }
  17090. };
  17091. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17092. this._spriteManagers.push(spriteManager);
  17093. };
  17094. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17095. this._particleSystems.push(particleSystem);
  17096. };
  17097. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17098. if (this._particleSystems.length === 0) {
  17099. return;
  17100. }
  17101. // Particles
  17102. var activeCamera = this._scene.activeCamera;
  17103. this._scene._particlesDuration.beginMonitoring();
  17104. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17105. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17106. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17107. continue;
  17108. }
  17109. var emitter = particleSystem.emitter;
  17110. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17111. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17112. }
  17113. }
  17114. this._scene._particlesDuration.endMonitoring(false);
  17115. };
  17116. RenderingGroup.prototype._renderSprites = function () {
  17117. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17118. return;
  17119. }
  17120. // Sprites
  17121. var activeCamera = this._scene.activeCamera;
  17122. this._scene._spritesDuration.beginMonitoring();
  17123. for (var id = 0; id < this._spriteManagers.length; id++) {
  17124. var spriteManager = this._spriteManagers.data[id];
  17125. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17126. spriteManager.render();
  17127. }
  17128. }
  17129. this._scene._spritesDuration.endMonitoring(false);
  17130. };
  17131. return RenderingGroup;
  17132. }());
  17133. BABYLON.RenderingGroup = RenderingGroup;
  17134. })(BABYLON || (BABYLON = {}));
  17135. //# sourceMappingURL=babylon.renderingGroup.js.map
  17136. var BABYLON;
  17137. (function (BABYLON) {
  17138. var ClickInfo = /** @class */ (function () {
  17139. function ClickInfo() {
  17140. this._singleClick = false;
  17141. this._doubleClick = false;
  17142. this._hasSwiped = false;
  17143. this._ignore = false;
  17144. }
  17145. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17146. get: function () {
  17147. return this._singleClick;
  17148. },
  17149. set: function (b) {
  17150. this._singleClick = b;
  17151. },
  17152. enumerable: true,
  17153. configurable: true
  17154. });
  17155. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17156. get: function () {
  17157. return this._doubleClick;
  17158. },
  17159. set: function (b) {
  17160. this._doubleClick = b;
  17161. },
  17162. enumerable: true,
  17163. configurable: true
  17164. });
  17165. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17166. get: function () {
  17167. return this._hasSwiped;
  17168. },
  17169. set: function (b) {
  17170. this._hasSwiped = b;
  17171. },
  17172. enumerable: true,
  17173. configurable: true
  17174. });
  17175. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17176. get: function () {
  17177. return this._ignore;
  17178. },
  17179. set: function (b) {
  17180. this._ignore = b;
  17181. },
  17182. enumerable: true,
  17183. configurable: true
  17184. });
  17185. return ClickInfo;
  17186. }());
  17187. /**
  17188. * This class is used by the onRenderingGroupObservable
  17189. */
  17190. var RenderingGroupInfo = /** @class */ (function () {
  17191. function RenderingGroupInfo() {
  17192. }
  17193. /**
  17194. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17195. * This stage will be fired no matter what
  17196. */
  17197. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17198. /**
  17199. * Called before opaque object are rendered.
  17200. * This stage will be fired only if there's 3D Opaque content to render
  17201. */
  17202. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17203. /**
  17204. * Called after the opaque objects are rendered and before the transparent ones
  17205. * This stage will be fired only if there's 3D transparent content to render
  17206. */
  17207. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17208. /**
  17209. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17210. * This stage will be fired no matter what
  17211. */
  17212. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17213. return RenderingGroupInfo;
  17214. }());
  17215. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17216. /**
  17217. * Represents a scene to be rendered by the engine.
  17218. * @see http://doc.babylonjs.com/page.php?p=21911
  17219. */
  17220. var Scene = /** @class */ (function () {
  17221. /**
  17222. * @constructor
  17223. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17224. */
  17225. function Scene(engine) {
  17226. // Members
  17227. this.autoClear = true;
  17228. this.autoClearDepthAndStencil = true;
  17229. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17230. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17231. this.forceWireframe = false;
  17232. this._forcePointsCloud = false;
  17233. this.forceShowBoundingBoxes = false;
  17234. this.animationsEnabled = true;
  17235. this.constantlyUpdateMeshUnderPointer = false;
  17236. this.hoverCursor = "pointer";
  17237. this.defaultCursor = "";
  17238. /**
  17239. * This is used to call preventDefault() on pointer down
  17240. * in order to block unwanted artifacts like system double clicks
  17241. */
  17242. this.preventDefaultOnPointerDown = true;
  17243. // Metadata
  17244. this.metadata = null;
  17245. /**
  17246. * An event triggered when the scene is disposed.
  17247. * @type {BABYLON.Observable}
  17248. */
  17249. this.onDisposeObservable = new BABYLON.Observable();
  17250. /**
  17251. * An event triggered before rendering the scene
  17252. * @type {BABYLON.Observable}
  17253. */
  17254. this.onBeforeRenderObservable = new BABYLON.Observable();
  17255. /**
  17256. * An event triggered after rendering the scene
  17257. * @type {BABYLON.Observable}
  17258. */
  17259. this.onAfterRenderObservable = new BABYLON.Observable();
  17260. /**
  17261. * An event triggered when the scene is ready
  17262. * @type {BABYLON.Observable}
  17263. */
  17264. this.onReadyObservable = new BABYLON.Observable();
  17265. /**
  17266. * An event triggered before rendering a camera
  17267. * @type {BABYLON.Observable}
  17268. */
  17269. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17270. /**
  17271. * An event triggered after rendering a camera
  17272. * @type {BABYLON.Observable}
  17273. */
  17274. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17275. /**
  17276. * An event triggered when active meshes evaluation is about to start
  17277. * @type {BABYLON.Observable}
  17278. */
  17279. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17280. /**
  17281. * An event triggered when active meshes evaluation is done
  17282. * @type {BABYLON.Observable}
  17283. */
  17284. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17285. /**
  17286. * An event triggered when a camera is created
  17287. * @type {BABYLON.Observable}
  17288. */
  17289. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17290. /**
  17291. * An event triggered when a camera is removed
  17292. * @type {BABYLON.Observable}
  17293. */
  17294. this.onCameraRemovedObservable = new BABYLON.Observable();
  17295. /**
  17296. * An event triggered when a light is created
  17297. * @type {BABYLON.Observable}
  17298. */
  17299. this.onNewLightAddedObservable = new BABYLON.Observable();
  17300. /**
  17301. * An event triggered when a light is removed
  17302. * @type {BABYLON.Observable}
  17303. */
  17304. this.onLightRemovedObservable = new BABYLON.Observable();
  17305. /**
  17306. * An event triggered when a geometry is created
  17307. * @type {BABYLON.Observable}
  17308. */
  17309. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17310. /**
  17311. * An event triggered when a geometry is removed
  17312. * @type {BABYLON.Observable}
  17313. */
  17314. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17315. /**
  17316. * An event triggered when a mesh is created
  17317. * @type {BABYLON.Observable}
  17318. */
  17319. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17320. /**
  17321. * An event triggered when a mesh is removed
  17322. * @type {BABYLON.Observable}
  17323. */
  17324. this.onMeshRemovedObservable = new BABYLON.Observable();
  17325. /**
  17326. * An event triggered when render targets are about to be rendered
  17327. * Can happen multiple times per frame.
  17328. * @type {BABYLON.Observable}
  17329. */
  17330. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17331. /**
  17332. * An event triggered when render targets were rendered.
  17333. * Can happen multiple times per frame.
  17334. * @type {BABYLON.Observable}
  17335. */
  17336. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17337. /**
  17338. * An event triggered before calculating deterministic simulation step
  17339. * @type {BABYLON.Observable}
  17340. */
  17341. this.onBeforeStepObservable = new BABYLON.Observable();
  17342. /**
  17343. * An event triggered after calculating deterministic simulation step
  17344. * @type {BABYLON.Observable}
  17345. */
  17346. this.onAfterStepObservable = new BABYLON.Observable();
  17347. /**
  17348. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17349. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17350. * 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)
  17351. */
  17352. this.onRenderingGroupObservable = new BABYLON.Observable();
  17353. // Animations
  17354. this.animations = [];
  17355. /**
  17356. * 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).
  17357. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17358. */
  17359. this.onPrePointerObservable = new BABYLON.Observable();
  17360. /**
  17361. * Observable event triggered each time an input event is received from the rendering canvas
  17362. */
  17363. this.onPointerObservable = new BABYLON.Observable();
  17364. this._meshPickProceed = false;
  17365. this._previousHasSwiped = false;
  17366. this._currentPickResult = null;
  17367. this._previousPickResult = null;
  17368. this._totalPointersPressed = 0;
  17369. this._doubleClickOccured = false;
  17370. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17371. this.cameraToUseForPointers = null;
  17372. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17373. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17374. this._startingPointerTime = 0;
  17375. this._previousStartingPointerTime = 0;
  17376. // Deterministic lockstep
  17377. this._timeAccumulator = 0;
  17378. this._currentStepId = 0;
  17379. this._currentInternalStep = 0;
  17380. // Keyboard
  17381. /**
  17382. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17383. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17384. */
  17385. this.onPreKeyboardObservable = new BABYLON.Observable();
  17386. /**
  17387. * Observable event triggered each time an keyboard event is received from the hosting window
  17388. */
  17389. this.onKeyboardObservable = new BABYLON.Observable();
  17390. // Coordinate system
  17391. /**
  17392. * use right-handed coordinate system on this scene.
  17393. * @type {boolean}
  17394. */
  17395. this._useRightHandedSystem = false;
  17396. // Fog
  17397. this._fogEnabled = true;
  17398. this._fogMode = Scene.FOGMODE_NONE;
  17399. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17400. this.fogDensity = 0.1;
  17401. this.fogStart = 0;
  17402. this.fogEnd = 1000.0;
  17403. // Lights
  17404. /**
  17405. * is shadow enabled on this scene.
  17406. * @type {boolean}
  17407. */
  17408. this._shadowsEnabled = true;
  17409. /**
  17410. * is light enabled on this scene.
  17411. * @type {boolean}
  17412. */
  17413. this._lightsEnabled = true;
  17414. /**
  17415. * All of the lights added to this scene.
  17416. * @see BABYLON.Light
  17417. * @type {BABYLON.Light[]}
  17418. */
  17419. this.lights = new Array();
  17420. // Cameras
  17421. /** All of the cameras added to this scene. */
  17422. this.cameras = new Array();
  17423. /** All of the active cameras added to this scene. */
  17424. this.activeCameras = new Array();
  17425. // Meshes
  17426. /**
  17427. * All of the (abstract) meshes added to this scene.
  17428. * @see BABYLON.AbstractMesh
  17429. * @type {BABYLON.AbstractMesh[]}
  17430. */
  17431. this.meshes = new Array();
  17432. // Geometries
  17433. this._geometries = new Array();
  17434. this.materials = new Array();
  17435. this.multiMaterials = new Array();
  17436. // Textures
  17437. this._texturesEnabled = true;
  17438. this.textures = new Array();
  17439. // Particles
  17440. this.particlesEnabled = true;
  17441. this.particleSystems = new Array();
  17442. // Sprites
  17443. this.spritesEnabled = true;
  17444. this.spriteManagers = new Array();
  17445. // Layers
  17446. this.layers = new Array();
  17447. this.highlightLayers = new Array();
  17448. // Skeletons
  17449. this._skeletonsEnabled = true;
  17450. this.skeletons = new Array();
  17451. // Morph targets
  17452. this.morphTargetManagers = new Array();
  17453. // Lens flares
  17454. this.lensFlaresEnabled = true;
  17455. this.lensFlareSystems = new Array();
  17456. // Collisions
  17457. this.collisionsEnabled = true;
  17458. /** Defines the gravity applied to this scene */
  17459. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17460. // Postprocesses
  17461. this.postProcesses = new Array();
  17462. this.postProcessesEnabled = true;
  17463. // Customs render targets
  17464. this.renderTargetsEnabled = true;
  17465. this.dumpNextRenderTargets = false;
  17466. this.customRenderTargets = new Array();
  17467. // Imported meshes
  17468. this.importedMeshesFiles = new Array();
  17469. // Probes
  17470. this.probesEnabled = true;
  17471. this.reflectionProbes = new Array();
  17472. this._actionManagers = new Array();
  17473. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17474. // Procedural textures
  17475. this.proceduralTexturesEnabled = true;
  17476. this._proceduralTextures = new Array();
  17477. this.soundTracks = new Array();
  17478. this._audioEnabled = true;
  17479. this._headphone = false;
  17480. // Performance counters
  17481. this._totalVertices = new BABYLON.PerfCounter();
  17482. this._activeIndices = new BABYLON.PerfCounter();
  17483. this._activeParticles = new BABYLON.PerfCounter();
  17484. this._interFrameDuration = new BABYLON.PerfCounter();
  17485. this._particlesDuration = new BABYLON.PerfCounter();
  17486. this._renderDuration = new BABYLON.PerfCounter();
  17487. this._spritesDuration = new BABYLON.PerfCounter();
  17488. this._activeBones = new BABYLON.PerfCounter();
  17489. this._animationTime = 0;
  17490. this.animationTimeScale = 1;
  17491. this._renderId = 0;
  17492. this._executeWhenReadyTimeoutId = -1;
  17493. this._intermediateRendering = false;
  17494. this._viewUpdateFlag = -1;
  17495. this._projectionUpdateFlag = -1;
  17496. this._alternateViewUpdateFlag = -1;
  17497. this._alternateProjectionUpdateFlag = -1;
  17498. this._toBeDisposed = new BABYLON.SmartArray(256);
  17499. this._pendingData = new Array();
  17500. this._isDisposed = false;
  17501. this._activeMeshes = new BABYLON.SmartArray(256);
  17502. this._processedMaterials = new BABYLON.SmartArray(256);
  17503. this._renderTargets = new BABYLON.SmartArray(256);
  17504. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17505. this._activeSkeletons = new BABYLON.SmartArray(32);
  17506. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17507. this._activeAnimatables = new Array();
  17508. this._transformMatrix = BABYLON.Matrix.Zero();
  17509. this._useAlternateCameraConfiguration = false;
  17510. this._alternateRendering = false;
  17511. this.requireLightSorting = false;
  17512. this._activeMeshesFrozen = false;
  17513. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17514. this._engine.scenes.push(this);
  17515. this._uid = null;
  17516. this._renderingManager = new BABYLON.RenderingManager(this);
  17517. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17518. if (BABYLON.OutlineRenderer) {
  17519. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17520. }
  17521. if (BABYLON.Tools.IsWindowObjectExist()) {
  17522. this.attachControl();
  17523. }
  17524. //simplification queue
  17525. if (BABYLON.SimplificationQueue) {
  17526. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17527. }
  17528. //collision coordinator initialization. For now legacy per default.
  17529. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17530. // Uniform Buffer
  17531. this._createUbo();
  17532. // Default Image processing definition.
  17533. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17534. }
  17535. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17536. /** The fog is deactivated */
  17537. get: function () {
  17538. return Scene._FOGMODE_NONE;
  17539. },
  17540. enumerable: true,
  17541. configurable: true
  17542. });
  17543. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17544. /** The fog density is following an exponential function */
  17545. get: function () {
  17546. return Scene._FOGMODE_EXP;
  17547. },
  17548. enumerable: true,
  17549. configurable: true
  17550. });
  17551. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17552. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17553. get: function () {
  17554. return Scene._FOGMODE_EXP2;
  17555. },
  17556. enumerable: true,
  17557. configurable: true
  17558. });
  17559. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17560. /** The fog density is following a linear function. */
  17561. get: function () {
  17562. return Scene._FOGMODE_LINEAR;
  17563. },
  17564. enumerable: true,
  17565. configurable: true
  17566. });
  17567. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17568. /**
  17569. * Texture used in all pbr material as the reflection texture.
  17570. * As in the majority of the scene they are the same (exception for multi room and so on),
  17571. * this is easier to reference from here than from all the materials.
  17572. */
  17573. get: function () {
  17574. return this._environmentTexture;
  17575. },
  17576. /**
  17577. * Texture used in all pbr material as the reflection texture.
  17578. * As in the majority of the scene they are the same (exception for multi room and so on),
  17579. * this is easier to set here than in all the materials.
  17580. */
  17581. set: function (value) {
  17582. if (this._environmentTexture === value) {
  17583. return;
  17584. }
  17585. this._environmentTexture = value;
  17586. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17587. },
  17588. enumerable: true,
  17589. configurable: true
  17590. });
  17591. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17592. /**
  17593. * Default image processing configuration used either in the rendering
  17594. * Forward main pass or through the imageProcessingPostProcess if present.
  17595. * As in the majority of the scene they are the same (exception for multi camera),
  17596. * this is easier to reference from here than from all the materials and post process.
  17597. *
  17598. * No setter as we it is a shared configuration, you can set the values instead.
  17599. */
  17600. get: function () {
  17601. return this._imageProcessingConfiguration;
  17602. },
  17603. enumerable: true,
  17604. configurable: true
  17605. });
  17606. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17607. get: function () {
  17608. return this._forcePointsCloud;
  17609. },
  17610. set: function (value) {
  17611. if (this._forcePointsCloud === value) {
  17612. return;
  17613. }
  17614. this._forcePointsCloud = value;
  17615. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17616. },
  17617. enumerable: true,
  17618. configurable: true
  17619. });
  17620. Object.defineProperty(Scene.prototype, "onDispose", {
  17621. /** A function to be executed when this scene is disposed. */
  17622. set: function (callback) {
  17623. if (this._onDisposeObserver) {
  17624. this.onDisposeObservable.remove(this._onDisposeObserver);
  17625. }
  17626. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17627. },
  17628. enumerable: true,
  17629. configurable: true
  17630. });
  17631. Object.defineProperty(Scene.prototype, "beforeRender", {
  17632. /** A function to be executed before rendering this scene */
  17633. set: function (callback) {
  17634. if (this._onBeforeRenderObserver) {
  17635. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17636. }
  17637. if (callback) {
  17638. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17639. }
  17640. },
  17641. enumerable: true,
  17642. configurable: true
  17643. });
  17644. Object.defineProperty(Scene.prototype, "afterRender", {
  17645. /** A function to be executed after rendering this scene */
  17646. set: function (callback) {
  17647. if (this._onAfterRenderObserver) {
  17648. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17649. }
  17650. if (callback) {
  17651. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17652. }
  17653. },
  17654. enumerable: true,
  17655. configurable: true
  17656. });
  17657. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17658. set: function (callback) {
  17659. if (this._onBeforeCameraRenderObserver) {
  17660. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17661. }
  17662. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17663. },
  17664. enumerable: true,
  17665. configurable: true
  17666. });
  17667. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17668. set: function (callback) {
  17669. if (this._onAfterCameraRenderObserver) {
  17670. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17671. }
  17672. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17673. },
  17674. enumerable: true,
  17675. configurable: true
  17676. });
  17677. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17678. get: function () {
  17679. if (!this._gamepadManager) {
  17680. this._gamepadManager = new BABYLON.GamepadManager();
  17681. }
  17682. return this._gamepadManager;
  17683. },
  17684. enumerable: true,
  17685. configurable: true
  17686. });
  17687. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17688. get: function () {
  17689. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17690. },
  17691. enumerable: true,
  17692. configurable: true
  17693. });
  17694. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17695. get: function () {
  17696. return this._useRightHandedSystem;
  17697. },
  17698. set: function (value) {
  17699. if (this._useRightHandedSystem === value) {
  17700. return;
  17701. }
  17702. this._useRightHandedSystem = value;
  17703. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17704. },
  17705. enumerable: true,
  17706. configurable: true
  17707. });
  17708. Scene.prototype.setStepId = function (newStepId) {
  17709. this._currentStepId = newStepId;
  17710. };
  17711. ;
  17712. Scene.prototype.getStepId = function () {
  17713. return this._currentStepId;
  17714. };
  17715. ;
  17716. Scene.prototype.getInternalStep = function () {
  17717. return this._currentInternalStep;
  17718. };
  17719. ;
  17720. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17721. get: function () {
  17722. return this._fogEnabled;
  17723. },
  17724. /**
  17725. * is fog enabled on this scene.
  17726. */
  17727. set: function (value) {
  17728. if (this._fogEnabled === value) {
  17729. return;
  17730. }
  17731. this._fogEnabled = value;
  17732. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17733. },
  17734. enumerable: true,
  17735. configurable: true
  17736. });
  17737. Object.defineProperty(Scene.prototype, "fogMode", {
  17738. get: function () {
  17739. return this._fogMode;
  17740. },
  17741. set: function (value) {
  17742. if (this._fogMode === value) {
  17743. return;
  17744. }
  17745. this._fogMode = value;
  17746. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17747. },
  17748. enumerable: true,
  17749. configurable: true
  17750. });
  17751. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17752. get: function () {
  17753. return this._shadowsEnabled;
  17754. },
  17755. set: function (value) {
  17756. if (this._shadowsEnabled === value) {
  17757. return;
  17758. }
  17759. this._shadowsEnabled = value;
  17760. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17761. },
  17762. enumerable: true,
  17763. configurable: true
  17764. });
  17765. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17766. get: function () {
  17767. return this._lightsEnabled;
  17768. },
  17769. set: function (value) {
  17770. if (this._lightsEnabled === value) {
  17771. return;
  17772. }
  17773. this._lightsEnabled = value;
  17774. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17775. },
  17776. enumerable: true,
  17777. configurable: true
  17778. });
  17779. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17780. /** The default material used on meshes when no material is affected */
  17781. get: function () {
  17782. if (!this._defaultMaterial) {
  17783. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17784. }
  17785. return this._defaultMaterial;
  17786. },
  17787. /** The default material used on meshes when no material is affected */
  17788. set: function (value) {
  17789. this._defaultMaterial = value;
  17790. },
  17791. enumerable: true,
  17792. configurable: true
  17793. });
  17794. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17795. get: function () {
  17796. return this._texturesEnabled;
  17797. },
  17798. set: function (value) {
  17799. if (this._texturesEnabled === value) {
  17800. return;
  17801. }
  17802. this._texturesEnabled = value;
  17803. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17804. },
  17805. enumerable: true,
  17806. configurable: true
  17807. });
  17808. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17809. get: function () {
  17810. return this._skeletonsEnabled;
  17811. },
  17812. set: function (value) {
  17813. if (this._skeletonsEnabled === value) {
  17814. return;
  17815. }
  17816. this._skeletonsEnabled = value;
  17817. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17818. },
  17819. enumerable: true,
  17820. configurable: true
  17821. });
  17822. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17823. get: function () {
  17824. if (!this._postProcessRenderPipelineManager) {
  17825. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17826. }
  17827. return this._postProcessRenderPipelineManager;
  17828. },
  17829. enumerable: true,
  17830. configurable: true
  17831. });
  17832. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17833. get: function () {
  17834. if (!this._mainSoundTrack) {
  17835. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17836. }
  17837. return this._mainSoundTrack;
  17838. },
  17839. enumerable: true,
  17840. configurable: true
  17841. });
  17842. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17843. get: function () {
  17844. return this._alternateRendering;
  17845. },
  17846. enumerable: true,
  17847. configurable: true
  17848. });
  17849. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17850. get: function () {
  17851. return this._frustumPlanes;
  17852. },
  17853. enumerable: true,
  17854. configurable: true
  17855. });
  17856. Object.defineProperty(Scene.prototype, "debugLayer", {
  17857. // Properties
  17858. get: function () {
  17859. if (!this._debugLayer) {
  17860. this._debugLayer = new BABYLON.DebugLayer(this);
  17861. }
  17862. return this._debugLayer;
  17863. },
  17864. enumerable: true,
  17865. configurable: true
  17866. });
  17867. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17868. get: function () {
  17869. return this._workerCollisions;
  17870. },
  17871. set: function (enabled) {
  17872. if (!BABYLON.CollisionCoordinatorLegacy) {
  17873. return;
  17874. }
  17875. enabled = (enabled && !!Worker);
  17876. this._workerCollisions = enabled;
  17877. if (this.collisionCoordinator) {
  17878. this.collisionCoordinator.destroy();
  17879. }
  17880. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17881. this.collisionCoordinator.init(this);
  17882. },
  17883. enumerable: true,
  17884. configurable: true
  17885. });
  17886. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17887. get: function () {
  17888. return this._selectionOctree;
  17889. },
  17890. enumerable: true,
  17891. configurable: true
  17892. });
  17893. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17894. /**
  17895. * The mesh that is currently under the pointer.
  17896. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17897. */
  17898. get: function () {
  17899. return this._pointerOverMesh;
  17900. },
  17901. enumerable: true,
  17902. configurable: true
  17903. });
  17904. Object.defineProperty(Scene.prototype, "pointerX", {
  17905. /**
  17906. * Current on-screen X position of the pointer
  17907. * @return {number} X position of the pointer
  17908. */
  17909. get: function () {
  17910. return this._pointerX;
  17911. },
  17912. enumerable: true,
  17913. configurable: true
  17914. });
  17915. Object.defineProperty(Scene.prototype, "pointerY", {
  17916. /**
  17917. * Current on-screen Y position of the pointer
  17918. * @return {number} Y position of the pointer
  17919. */
  17920. get: function () {
  17921. return this._pointerY;
  17922. },
  17923. enumerable: true,
  17924. configurable: true
  17925. });
  17926. Scene.prototype.getCachedMaterial = function () {
  17927. return this._cachedMaterial;
  17928. };
  17929. Scene.prototype.getCachedEffect = function () {
  17930. return this._cachedEffect;
  17931. };
  17932. Scene.prototype.getCachedVisibility = function () {
  17933. return this._cachedVisibility;
  17934. };
  17935. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17936. if (visibility === void 0) { visibility = 1; }
  17937. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17938. };
  17939. Scene.prototype.getBoundingBoxRenderer = function () {
  17940. if (!this._boundingBoxRenderer) {
  17941. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17942. }
  17943. return this._boundingBoxRenderer;
  17944. };
  17945. Scene.prototype.getOutlineRenderer = function () {
  17946. return this._outlineRenderer;
  17947. };
  17948. Scene.prototype.getEngine = function () {
  17949. return this._engine;
  17950. };
  17951. Scene.prototype.getTotalVertices = function () {
  17952. return this._totalVertices.current;
  17953. };
  17954. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17955. get: function () {
  17956. return this._totalVertices;
  17957. },
  17958. enumerable: true,
  17959. configurable: true
  17960. });
  17961. Scene.prototype.getActiveIndices = function () {
  17962. return this._activeIndices.current;
  17963. };
  17964. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17965. get: function () {
  17966. return this._activeIndices;
  17967. },
  17968. enumerable: true,
  17969. configurable: true
  17970. });
  17971. Scene.prototype.getActiveParticles = function () {
  17972. return this._activeParticles.current;
  17973. };
  17974. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17975. get: function () {
  17976. return this._activeParticles;
  17977. },
  17978. enumerable: true,
  17979. configurable: true
  17980. });
  17981. Scene.prototype.getActiveBones = function () {
  17982. return this._activeBones.current;
  17983. };
  17984. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17985. get: function () {
  17986. return this._activeBones;
  17987. },
  17988. enumerable: true,
  17989. configurable: true
  17990. });
  17991. // Stats
  17992. Scene.prototype.getInterFramePerfCounter = function () {
  17993. return this._interFrameDuration.current;
  17994. };
  17995. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17996. get: function () {
  17997. return this._interFrameDuration;
  17998. },
  17999. enumerable: true,
  18000. configurable: true
  18001. });
  18002. Scene.prototype.getLastFrameDuration = function () {
  18003. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18004. return 0;
  18005. };
  18006. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18007. get: function () {
  18008. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18009. return null;
  18010. },
  18011. enumerable: true,
  18012. configurable: true
  18013. });
  18014. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18015. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18016. return 0;
  18017. };
  18018. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18019. get: function () {
  18020. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18021. return null;
  18022. },
  18023. enumerable: true,
  18024. configurable: true
  18025. });
  18026. Scene.prototype.getActiveMeshes = function () {
  18027. return this._activeMeshes;
  18028. };
  18029. Scene.prototype.getRenderTargetsDuration = function () {
  18030. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18031. return 0;
  18032. };
  18033. Scene.prototype.getRenderDuration = function () {
  18034. return this._renderDuration.current;
  18035. };
  18036. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18037. get: function () {
  18038. return this._renderDuration;
  18039. },
  18040. enumerable: true,
  18041. configurable: true
  18042. });
  18043. Scene.prototype.getParticlesDuration = function () {
  18044. return this._particlesDuration.current;
  18045. };
  18046. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18047. get: function () {
  18048. return this._particlesDuration;
  18049. },
  18050. enumerable: true,
  18051. configurable: true
  18052. });
  18053. Scene.prototype.getSpritesDuration = function () {
  18054. return this._spritesDuration.current;
  18055. };
  18056. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18057. get: function () {
  18058. return this._spritesDuration;
  18059. },
  18060. enumerable: true,
  18061. configurable: true
  18062. });
  18063. Scene.prototype.getAnimationRatio = function () {
  18064. return this._animationRatio;
  18065. };
  18066. Scene.prototype.getRenderId = function () {
  18067. return this._renderId;
  18068. };
  18069. Scene.prototype.incrementRenderId = function () {
  18070. this._renderId++;
  18071. };
  18072. Scene.prototype._updatePointerPosition = function (evt) {
  18073. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18074. if (!canvasRect) {
  18075. return;
  18076. }
  18077. this._pointerX = evt.clientX - canvasRect.left;
  18078. this._pointerY = evt.clientY - canvasRect.top;
  18079. this._unTranslatedPointerX = this._pointerX;
  18080. this._unTranslatedPointerY = this._pointerY;
  18081. };
  18082. Scene.prototype._createUbo = function () {
  18083. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18084. this._sceneUbo.addUniform("viewProjection", 16);
  18085. this._sceneUbo.addUniform("view", 16);
  18086. };
  18087. Scene.prototype._createAlternateUbo = function () {
  18088. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18089. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18090. this._alternateSceneUbo.addUniform("view", 16);
  18091. };
  18092. // Pointers handling
  18093. /**
  18094. * Use this method to simulate a pointer move on a mesh
  18095. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18096. */
  18097. Scene.prototype.simulatePointerMove = function (pickResult) {
  18098. var evt = new PointerEvent("pointermove");
  18099. return this._processPointerMove(pickResult, evt);
  18100. };
  18101. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18102. var canvas = this._engine.getRenderingCanvas();
  18103. if (!canvas) {
  18104. return this;
  18105. }
  18106. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18107. this.setPointerOverSprite(null);
  18108. this.setPointerOverMesh(pickResult.pickedMesh);
  18109. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18110. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18111. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18112. }
  18113. else {
  18114. canvas.style.cursor = this.hoverCursor;
  18115. }
  18116. }
  18117. else {
  18118. canvas.style.cursor = this.defaultCursor;
  18119. }
  18120. }
  18121. else {
  18122. this.setPointerOverMesh(null);
  18123. // Sprites
  18124. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18125. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18126. this.setPointerOverSprite(pickResult.pickedSprite);
  18127. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18128. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18129. }
  18130. else {
  18131. canvas.style.cursor = this.hoverCursor;
  18132. }
  18133. }
  18134. else {
  18135. this.setPointerOverSprite(null);
  18136. // Restore pointer
  18137. canvas.style.cursor = this.defaultCursor;
  18138. }
  18139. }
  18140. if (pickResult) {
  18141. if (this.onPointerMove) {
  18142. this.onPointerMove(evt, pickResult);
  18143. }
  18144. if (this.onPointerObservable.hasObservers()) {
  18145. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18146. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18147. this.onPointerObservable.notifyObservers(pi, type);
  18148. }
  18149. }
  18150. return this;
  18151. };
  18152. /**
  18153. * Use this method to simulate a pointer down on a mesh
  18154. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18155. */
  18156. Scene.prototype.simulatePointerDown = function (pickResult) {
  18157. var evt = new PointerEvent("pointerdown");
  18158. return this._processPointerDown(pickResult, evt);
  18159. };
  18160. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18161. var _this = this;
  18162. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18163. this._pickedDownMesh = pickResult.pickedMesh;
  18164. var actionManager = pickResult.pickedMesh.actionManager;
  18165. if (actionManager) {
  18166. if (actionManager.hasPickTriggers) {
  18167. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18168. switch (evt.button) {
  18169. case 0:
  18170. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18171. break;
  18172. case 1:
  18173. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18174. break;
  18175. case 2:
  18176. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18177. break;
  18178. }
  18179. }
  18180. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18181. window.setTimeout(function () {
  18182. 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);
  18183. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18184. if (_this._totalPointersPressed !== 0 &&
  18185. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18186. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18187. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18188. _this._startingPointerTime = 0;
  18189. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18190. }
  18191. }
  18192. }, Scene.LongPressDelay);
  18193. }
  18194. }
  18195. }
  18196. if (pickResult) {
  18197. if (this.onPointerDown) {
  18198. this.onPointerDown(evt, pickResult);
  18199. }
  18200. if (this.onPointerObservable.hasObservers()) {
  18201. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18202. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18203. this.onPointerObservable.notifyObservers(pi, type);
  18204. }
  18205. }
  18206. return this;
  18207. };
  18208. /**
  18209. * Use this method to simulate a pointer up on a mesh
  18210. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18211. */
  18212. Scene.prototype.simulatePointerUp = function (pickResult) {
  18213. var evt = new PointerEvent("pointerup");
  18214. var clickInfo = new ClickInfo();
  18215. clickInfo.singleClick = true;
  18216. return this._processPointerUp(pickResult, evt, clickInfo);
  18217. };
  18218. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18219. if (pickResult && pickResult && pickResult.pickedMesh) {
  18220. this._pickedUpMesh = pickResult.pickedMesh;
  18221. if (this._pickedDownMesh === this._pickedUpMesh) {
  18222. if (this.onPointerPick) {
  18223. this.onPointerPick(evt, pickResult);
  18224. }
  18225. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18226. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18227. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18228. this.onPointerObservable.notifyObservers(pi, type);
  18229. }
  18230. }
  18231. if (pickResult.pickedMesh.actionManager) {
  18232. if (clickInfo.ignore) {
  18233. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18234. }
  18235. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18236. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18237. }
  18238. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18239. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18240. }
  18241. }
  18242. }
  18243. if (this._pickedDownMesh &&
  18244. this._pickedDownMesh.actionManager &&
  18245. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18246. this._pickedDownMesh !== this._pickedUpMesh) {
  18247. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18248. }
  18249. if (this.onPointerUp) {
  18250. this.onPointerUp(evt, pickResult);
  18251. }
  18252. if (this.onPointerObservable.hasObservers()) {
  18253. if (!clickInfo.ignore) {
  18254. if (!clickInfo.hasSwiped) {
  18255. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18256. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18257. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18258. this.onPointerObservable.notifyObservers(pi, type);
  18259. }
  18260. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18261. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18262. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18263. this.onPointerObservable.notifyObservers(pi, type);
  18264. }
  18265. }
  18266. }
  18267. else {
  18268. var type = BABYLON.PointerEventTypes.POINTERUP;
  18269. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18270. this.onPointerObservable.notifyObservers(pi, type);
  18271. }
  18272. }
  18273. return this;
  18274. };
  18275. /**
  18276. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18277. * @param attachUp defines if you want to attach events to pointerup
  18278. * @param attachDown defines if you want to attach events to pointerdown
  18279. * @param attachMove defines if you want to attach events to pointermove
  18280. */
  18281. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18282. var _this = this;
  18283. if (attachUp === void 0) { attachUp = true; }
  18284. if (attachDown === void 0) { attachDown = true; }
  18285. if (attachMove === void 0) { attachMove = true; }
  18286. this._initActionManager = function (act, clickInfo) {
  18287. if (!_this._meshPickProceed) {
  18288. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18289. _this._currentPickResult = pickResult;
  18290. if (pickResult) {
  18291. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18292. }
  18293. _this._meshPickProceed = true;
  18294. }
  18295. return act;
  18296. };
  18297. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18298. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18299. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18300. btn !== _this._previousButtonPressed) {
  18301. _this._doubleClickOccured = false;
  18302. clickInfo.singleClick = true;
  18303. clickInfo.ignore = false;
  18304. cb(clickInfo, _this._currentPickResult);
  18305. }
  18306. };
  18307. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18308. var clickInfo = new ClickInfo();
  18309. _this._currentPickResult = null;
  18310. var act = null;
  18311. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18312. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18313. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18314. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18315. act = _this._initActionManager(act, clickInfo);
  18316. if (act)
  18317. checkPicking = act.hasPickTriggers;
  18318. }
  18319. if (checkPicking) {
  18320. var btn = evt.button;
  18321. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18322. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18323. if (!clickInfo.hasSwiped) {
  18324. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18325. if (!checkSingleClickImmediately) {
  18326. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18327. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18328. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18329. act = _this._initActionManager(act, clickInfo);
  18330. if (act)
  18331. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18332. }
  18333. }
  18334. if (checkSingleClickImmediately) {
  18335. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18336. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18337. btn !== _this._previousButtonPressed) {
  18338. clickInfo.singleClick = true;
  18339. cb(clickInfo, _this._currentPickResult);
  18340. }
  18341. }
  18342. else {
  18343. // wait that no double click has been raised during the double click delay
  18344. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18345. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18346. }
  18347. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18348. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18349. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18350. act = _this._initActionManager(act, clickInfo);
  18351. if (act)
  18352. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18353. }
  18354. if (checkDoubleClick) {
  18355. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18356. if (btn === _this._previousButtonPressed &&
  18357. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18358. !_this._doubleClickOccured) {
  18359. // pointer has not moved for 2 clicks, it's a double click
  18360. if (!clickInfo.hasSwiped &&
  18361. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18362. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18363. _this._previousStartingPointerTime = 0;
  18364. _this._doubleClickOccured = true;
  18365. clickInfo.doubleClick = true;
  18366. clickInfo.ignore = false;
  18367. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18368. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18369. }
  18370. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18371. cb(clickInfo, _this._currentPickResult);
  18372. }
  18373. else {
  18374. _this._doubleClickOccured = false;
  18375. _this._previousStartingPointerTime = _this._startingPointerTime;
  18376. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18377. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18378. _this._previousButtonPressed = btn;
  18379. _this._previousHasSwiped = clickInfo.hasSwiped;
  18380. if (Scene.ExclusiveDoubleClickMode) {
  18381. if (_this._previousDelayedSimpleClickTimeout) {
  18382. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18383. }
  18384. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18385. cb(clickInfo, _this._previousPickResult);
  18386. }
  18387. else {
  18388. cb(clickInfo, _this._currentPickResult);
  18389. }
  18390. }
  18391. }
  18392. else {
  18393. _this._doubleClickOccured = false;
  18394. _this._previousStartingPointerTime = _this._startingPointerTime;
  18395. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18396. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18397. _this._previousButtonPressed = btn;
  18398. _this._previousHasSwiped = clickInfo.hasSwiped;
  18399. }
  18400. }
  18401. }
  18402. }
  18403. clickInfo.ignore = true;
  18404. cb(clickInfo, _this._currentPickResult);
  18405. };
  18406. this._spritePredicate = function (sprite) {
  18407. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18408. };
  18409. this._onPointerMove = function (evt) {
  18410. _this._updatePointerPosition(evt);
  18411. // PreObservable support
  18412. if (_this.onPrePointerObservable.hasObservers()) {
  18413. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18414. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18415. _this.onPrePointerObservable.notifyObservers(pi, type);
  18416. if (pi.skipOnPointerObservable) {
  18417. return;
  18418. }
  18419. }
  18420. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18421. return;
  18422. }
  18423. if (!_this.pointerMovePredicate) {
  18424. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18425. }
  18426. // Meshes
  18427. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18428. _this._processPointerMove(pickResult, evt);
  18429. };
  18430. this._onPointerDown = function (evt) {
  18431. _this._totalPointersPressed++;
  18432. _this._pickedDownMesh = null;
  18433. _this._meshPickProceed = false;
  18434. _this._updatePointerPosition(evt);
  18435. if (_this.preventDefaultOnPointerDown && canvas) {
  18436. evt.preventDefault();
  18437. canvas.focus();
  18438. }
  18439. // PreObservable support
  18440. if (_this.onPrePointerObservable.hasObservers()) {
  18441. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18442. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18443. _this.onPrePointerObservable.notifyObservers(pi, type);
  18444. if (pi.skipOnPointerObservable) {
  18445. return;
  18446. }
  18447. }
  18448. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18449. return;
  18450. }
  18451. _this._startingPointerPosition.x = _this._pointerX;
  18452. _this._startingPointerPosition.y = _this._pointerY;
  18453. _this._startingPointerTime = new Date().getTime();
  18454. if (!_this.pointerDownPredicate) {
  18455. _this.pointerDownPredicate = function (mesh) {
  18456. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18457. };
  18458. }
  18459. // Meshes
  18460. _this._pickedDownMesh = null;
  18461. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18462. _this._processPointerDown(pickResult, evt);
  18463. // Sprites
  18464. _this._pickedDownSprite = null;
  18465. if (_this.spriteManagers.length > 0) {
  18466. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18467. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18468. if (pickResult.pickedSprite.actionManager) {
  18469. _this._pickedDownSprite = pickResult.pickedSprite;
  18470. switch (evt.button) {
  18471. case 0:
  18472. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18473. break;
  18474. case 1:
  18475. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18476. break;
  18477. case 2:
  18478. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18479. break;
  18480. }
  18481. if (pickResult.pickedSprite.actionManager) {
  18482. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18483. }
  18484. }
  18485. }
  18486. }
  18487. };
  18488. this._onPointerUp = function (evt) {
  18489. if (_this._totalPointersPressed === 0) {
  18490. return; // So we need to test it the pointer down was pressed before.
  18491. }
  18492. _this._totalPointersPressed--;
  18493. _this._pickedUpMesh = null;
  18494. _this._meshPickProceed = false;
  18495. _this._updatePointerPosition(evt);
  18496. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18497. // PreObservable support
  18498. if (_this.onPrePointerObservable.hasObservers()) {
  18499. if (!clickInfo.ignore) {
  18500. if (!clickInfo.hasSwiped) {
  18501. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18502. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18503. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18504. _this.onPrePointerObservable.notifyObservers(pi, type);
  18505. if (pi.skipOnPointerObservable) {
  18506. return;
  18507. }
  18508. }
  18509. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18510. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18511. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18512. _this.onPrePointerObservable.notifyObservers(pi, type);
  18513. if (pi.skipOnPointerObservable) {
  18514. return;
  18515. }
  18516. }
  18517. }
  18518. }
  18519. else {
  18520. var type = BABYLON.PointerEventTypes.POINTERUP;
  18521. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18522. _this.onPrePointerObservable.notifyObservers(pi, type);
  18523. if (pi.skipOnPointerObservable) {
  18524. return;
  18525. }
  18526. }
  18527. }
  18528. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18529. return;
  18530. }
  18531. if (!_this.pointerUpPredicate) {
  18532. _this.pointerUpPredicate = function (mesh) {
  18533. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18534. };
  18535. }
  18536. // Meshes
  18537. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18538. _this._initActionManager(null, clickInfo);
  18539. }
  18540. if (!pickResult) {
  18541. pickResult = _this._currentPickResult;
  18542. }
  18543. _this._processPointerUp(pickResult, evt, clickInfo);
  18544. // Sprites
  18545. if (_this.spriteManagers.length > 0) {
  18546. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18547. if (spritePickResult) {
  18548. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18549. if (spritePickResult.pickedSprite.actionManager) {
  18550. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18551. if (spritePickResult.pickedSprite.actionManager) {
  18552. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18553. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18554. }
  18555. }
  18556. }
  18557. }
  18558. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18559. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18560. }
  18561. }
  18562. }
  18563. _this._previousPickResult = _this._currentPickResult;
  18564. });
  18565. };
  18566. this._onKeyDown = function (evt) {
  18567. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18568. if (_this.onPreKeyboardObservable.hasObservers()) {
  18569. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18570. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18571. if (pi.skipOnPointerObservable) {
  18572. return;
  18573. }
  18574. }
  18575. if (_this.onKeyboardObservable.hasObservers()) {
  18576. var pi = new BABYLON.KeyboardInfo(type, evt);
  18577. _this.onKeyboardObservable.notifyObservers(pi, type);
  18578. }
  18579. if (_this.actionManager) {
  18580. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18581. }
  18582. };
  18583. this._onKeyUp = function (evt) {
  18584. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18585. if (_this.onPreKeyboardObservable.hasObservers()) {
  18586. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18587. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18588. if (pi.skipOnPointerObservable) {
  18589. return;
  18590. }
  18591. }
  18592. if (_this.onKeyboardObservable.hasObservers()) {
  18593. var pi = new BABYLON.KeyboardInfo(type, evt);
  18594. _this.onKeyboardObservable.notifyObservers(pi, type);
  18595. }
  18596. if (_this.actionManager) {
  18597. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18598. }
  18599. };
  18600. var engine = this.getEngine();
  18601. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18602. if (!canvas) {
  18603. return;
  18604. }
  18605. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18606. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18607. });
  18608. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18609. if (!canvas) {
  18610. return;
  18611. }
  18612. canvas.removeEventListener("keydown", _this._onKeyDown);
  18613. canvas.removeEventListener("keyup", _this._onKeyUp);
  18614. });
  18615. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18616. var canvas = this._engine.getRenderingCanvas();
  18617. if (!canvas) {
  18618. return;
  18619. }
  18620. if (attachMove) {
  18621. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18622. // Wheel
  18623. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18624. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18625. }
  18626. if (attachDown) {
  18627. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18628. }
  18629. if (attachUp) {
  18630. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18631. }
  18632. canvas.tabIndex = 1;
  18633. };
  18634. Scene.prototype.detachControl = function () {
  18635. var engine = this.getEngine();
  18636. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18637. var canvas = engine.getRenderingCanvas();
  18638. if (!canvas) {
  18639. return;
  18640. }
  18641. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18642. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18643. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18644. if (this._onCanvasBlurObserver) {
  18645. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18646. }
  18647. if (this._onCanvasFocusObserver) {
  18648. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18649. }
  18650. // Wheel
  18651. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18652. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18653. // Keyboard
  18654. canvas.removeEventListener("keydown", this._onKeyDown);
  18655. canvas.removeEventListener("keyup", this._onKeyUp);
  18656. // Observables
  18657. this.onKeyboardObservable.clear();
  18658. this.onPreKeyboardObservable.clear();
  18659. this.onPointerObservable.clear();
  18660. this.onPrePointerObservable.clear();
  18661. };
  18662. // Ready
  18663. Scene.prototype.isReady = function () {
  18664. if (this._isDisposed) {
  18665. return false;
  18666. }
  18667. if (this._pendingData.length > 0) {
  18668. return false;
  18669. }
  18670. var index;
  18671. // Geometries
  18672. for (index = 0; index < this._geometries.length; index++) {
  18673. var geometry = this._geometries[index];
  18674. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18675. return false;
  18676. }
  18677. }
  18678. // Meshes
  18679. for (index = 0; index < this.meshes.length; index++) {
  18680. var mesh = this.meshes[index];
  18681. if (!mesh.isEnabled()) {
  18682. continue;
  18683. }
  18684. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18685. continue;
  18686. }
  18687. if (!mesh.isReady()) {
  18688. return false;
  18689. }
  18690. var mat = mesh.material;
  18691. if (mat) {
  18692. if (!mat.isReady(mesh)) {
  18693. return false;
  18694. }
  18695. }
  18696. }
  18697. return true;
  18698. };
  18699. Scene.prototype.resetCachedMaterial = function () {
  18700. this._cachedMaterial = null;
  18701. this._cachedEffect = null;
  18702. this._cachedVisibility = null;
  18703. };
  18704. Scene.prototype.registerBeforeRender = function (func) {
  18705. this.onBeforeRenderObservable.add(func);
  18706. };
  18707. Scene.prototype.unregisterBeforeRender = function (func) {
  18708. this.onBeforeRenderObservable.removeCallback(func);
  18709. };
  18710. Scene.prototype.registerAfterRender = function (func) {
  18711. this.onAfterRenderObservable.add(func);
  18712. };
  18713. Scene.prototype.unregisterAfterRender = function (func) {
  18714. this.onAfterRenderObservable.removeCallback(func);
  18715. };
  18716. Scene.prototype._addPendingData = function (data) {
  18717. this._pendingData.push(data);
  18718. };
  18719. Scene.prototype._removePendingData = function (data) {
  18720. var index = this._pendingData.indexOf(data);
  18721. if (index !== -1) {
  18722. this._pendingData.splice(index, 1);
  18723. }
  18724. };
  18725. Scene.prototype.getWaitingItemsCount = function () {
  18726. return this._pendingData.length;
  18727. };
  18728. /**
  18729. * Registers a function to be executed when the scene is ready.
  18730. * @param {Function} func - the function to be executed.
  18731. */
  18732. Scene.prototype.executeWhenReady = function (func) {
  18733. var _this = this;
  18734. this.onReadyObservable.add(func);
  18735. if (this._executeWhenReadyTimeoutId !== -1) {
  18736. return;
  18737. }
  18738. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18739. _this._checkIsReady();
  18740. }, 150);
  18741. };
  18742. Scene.prototype._checkIsReady = function () {
  18743. var _this = this;
  18744. if (this.isReady()) {
  18745. this.onReadyObservable.notifyObservers(this);
  18746. this.onReadyObservable.clear();
  18747. this._executeWhenReadyTimeoutId = -1;
  18748. return;
  18749. }
  18750. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18751. _this._checkIsReady();
  18752. }, 150);
  18753. };
  18754. // Animations
  18755. /**
  18756. * Will start the animation sequence of a given target
  18757. * @param target - the target
  18758. * @param {number} from - from which frame should animation start
  18759. * @param {number} to - till which frame should animation run.
  18760. * @param {boolean} [loop] - should the animation loop
  18761. * @param {number} [speedRatio] - the speed in which to run the animation
  18762. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18763. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18764. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18765. * See BABYLON.Animatable
  18766. */
  18767. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18768. if (speedRatio === void 0) { speedRatio = 1.0; }
  18769. if (from > to && speedRatio > 0) {
  18770. speedRatio *= -1;
  18771. }
  18772. this.stopAnimation(target);
  18773. if (!animatable) {
  18774. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18775. }
  18776. // Local animations
  18777. if (target.animations) {
  18778. animatable.appendAnimations(target, target.animations);
  18779. }
  18780. // Children animations
  18781. if (target.getAnimatables) {
  18782. var animatables = target.getAnimatables();
  18783. for (var index = 0; index < animatables.length; index++) {
  18784. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18785. }
  18786. }
  18787. animatable.reset();
  18788. return animatable;
  18789. };
  18790. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18791. if (speedRatio === undefined) {
  18792. speedRatio = 1.0;
  18793. }
  18794. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18795. return animatable;
  18796. };
  18797. Scene.prototype.getAnimatableByTarget = function (target) {
  18798. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18799. if (this._activeAnimatables[index].target === target) {
  18800. return this._activeAnimatables[index];
  18801. }
  18802. }
  18803. return null;
  18804. };
  18805. Object.defineProperty(Scene.prototype, "Animatables", {
  18806. get: function () {
  18807. return this._activeAnimatables;
  18808. },
  18809. enumerable: true,
  18810. configurable: true
  18811. });
  18812. /**
  18813. * Will stop the animation of the given target
  18814. * @param target - the target
  18815. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18816. * @see beginAnimation
  18817. */
  18818. Scene.prototype.stopAnimation = function (target, animationName) {
  18819. var animatable = this.getAnimatableByTarget(target);
  18820. if (animatable) {
  18821. animatable.stop(animationName);
  18822. }
  18823. };
  18824. Scene.prototype._animate = function () {
  18825. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18826. return;
  18827. }
  18828. // Getting time
  18829. var now = BABYLON.Tools.Now;
  18830. if (!this._animationTimeLast) {
  18831. if (this._pendingData.length > 0) {
  18832. return;
  18833. }
  18834. this._animationTimeLast = now;
  18835. }
  18836. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18837. this._animationTime += deltaTime;
  18838. this._animationTimeLast = now;
  18839. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18840. this._activeAnimatables[index]._animate(this._animationTime);
  18841. }
  18842. };
  18843. // Matrix
  18844. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18845. this._useAlternateCameraConfiguration = active;
  18846. };
  18847. Scene.prototype.getViewMatrix = function () {
  18848. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18849. };
  18850. Scene.prototype.getProjectionMatrix = function () {
  18851. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18852. };
  18853. Scene.prototype.getTransformMatrix = function () {
  18854. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18855. };
  18856. Scene.prototype.setTransformMatrix = function (view, projection) {
  18857. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18858. return;
  18859. }
  18860. this._viewUpdateFlag = view.updateFlag;
  18861. this._projectionUpdateFlag = projection.updateFlag;
  18862. this._viewMatrix = view;
  18863. this._projectionMatrix = projection;
  18864. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18865. // Update frustum
  18866. if (!this._frustumPlanes) {
  18867. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18868. }
  18869. else {
  18870. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18871. }
  18872. if (this.activeCamera && this.activeCamera._alternateCamera) {
  18873. var otherCamera = this.activeCamera._alternateCamera;
  18874. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  18875. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  18876. }
  18877. if (this._sceneUbo.useUbo) {
  18878. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18879. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18880. this._sceneUbo.update();
  18881. }
  18882. };
  18883. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18884. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18885. return;
  18886. }
  18887. this._alternateViewUpdateFlag = view.updateFlag;
  18888. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18889. this._alternateViewMatrix = view;
  18890. this._alternateProjectionMatrix = projection;
  18891. if (!this._alternateTransformMatrix) {
  18892. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18893. }
  18894. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18895. if (!this._alternateSceneUbo) {
  18896. this._createAlternateUbo();
  18897. }
  18898. if (this._alternateSceneUbo.useUbo) {
  18899. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18900. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18901. this._alternateSceneUbo.update();
  18902. }
  18903. };
  18904. Scene.prototype.getSceneUniformBuffer = function () {
  18905. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18906. };
  18907. // Methods
  18908. Scene.prototype.getUniqueId = function () {
  18909. var result = Scene._uniqueIdCounter;
  18910. Scene._uniqueIdCounter++;
  18911. return result;
  18912. };
  18913. Scene.prototype.addMesh = function (newMesh) {
  18914. this.meshes.push(newMesh);
  18915. //notify the collision coordinator
  18916. if (this.collisionCoordinator) {
  18917. this.collisionCoordinator.onMeshAdded(newMesh);
  18918. }
  18919. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18920. };
  18921. Scene.prototype.removeMesh = function (toRemove) {
  18922. var index = this.meshes.indexOf(toRemove);
  18923. if (index !== -1) {
  18924. // Remove from the scene if mesh found
  18925. this.meshes.splice(index, 1);
  18926. }
  18927. //notify the collision coordinator
  18928. if (this.collisionCoordinator) {
  18929. this.collisionCoordinator.onMeshRemoved(toRemove);
  18930. }
  18931. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18932. return index;
  18933. };
  18934. Scene.prototype.removeSkeleton = function (toRemove) {
  18935. var index = this.skeletons.indexOf(toRemove);
  18936. if (index !== -1) {
  18937. // Remove from the scene if found
  18938. this.skeletons.splice(index, 1);
  18939. }
  18940. return index;
  18941. };
  18942. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18943. var index = this.morphTargetManagers.indexOf(toRemove);
  18944. if (index !== -1) {
  18945. // Remove from the scene if found
  18946. this.morphTargetManagers.splice(index, 1);
  18947. }
  18948. return index;
  18949. };
  18950. Scene.prototype.removeLight = function (toRemove) {
  18951. var index = this.lights.indexOf(toRemove);
  18952. if (index !== -1) {
  18953. // Remove from the scene if mesh found
  18954. this.lights.splice(index, 1);
  18955. this.sortLightsByPriority();
  18956. }
  18957. this.onLightRemovedObservable.notifyObservers(toRemove);
  18958. return index;
  18959. };
  18960. Scene.prototype.removeCamera = function (toRemove) {
  18961. var index = this.cameras.indexOf(toRemove);
  18962. if (index !== -1) {
  18963. // Remove from the scene if mesh found
  18964. this.cameras.splice(index, 1);
  18965. }
  18966. // Remove from activeCameras
  18967. var index2 = this.activeCameras.indexOf(toRemove);
  18968. if (index2 !== -1) {
  18969. // Remove from the scene if mesh found
  18970. this.activeCameras.splice(index2, 1);
  18971. }
  18972. // Reset the activeCamera
  18973. if (this.activeCamera === toRemove) {
  18974. if (this.cameras.length > 0) {
  18975. this.activeCamera = this.cameras[0];
  18976. }
  18977. else {
  18978. this.activeCamera = null;
  18979. }
  18980. }
  18981. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18982. return index;
  18983. };
  18984. Scene.prototype.addLight = function (newLight) {
  18985. this.lights.push(newLight);
  18986. this.sortLightsByPriority();
  18987. this.onNewLightAddedObservable.notifyObservers(newLight);
  18988. };
  18989. Scene.prototype.sortLightsByPriority = function () {
  18990. if (this.requireLightSorting) {
  18991. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18992. }
  18993. };
  18994. Scene.prototype.addCamera = function (newCamera) {
  18995. this.cameras.push(newCamera);
  18996. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18997. };
  18998. /**
  18999. * Switch active camera
  19000. * @param {Camera} newCamera - new active camera
  19001. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19002. */
  19003. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19004. if (attachControl === void 0) { attachControl = true; }
  19005. var canvas = this._engine.getRenderingCanvas();
  19006. if (!canvas) {
  19007. return;
  19008. }
  19009. if (this.activeCamera) {
  19010. this.activeCamera.detachControl(canvas);
  19011. }
  19012. this.activeCamera = newCamera;
  19013. if (attachControl) {
  19014. newCamera.attachControl(canvas);
  19015. }
  19016. };
  19017. /**
  19018. * sets the active camera of the scene using its ID
  19019. * @param {string} id - the camera's ID
  19020. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19021. * @see activeCamera
  19022. */
  19023. Scene.prototype.setActiveCameraByID = function (id) {
  19024. var camera = this.getCameraByID(id);
  19025. if (camera) {
  19026. this.activeCamera = camera;
  19027. return camera;
  19028. }
  19029. return null;
  19030. };
  19031. /**
  19032. * sets the active camera of the scene using its name
  19033. * @param {string} name - the camera's name
  19034. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19035. * @see activeCamera
  19036. */
  19037. Scene.prototype.setActiveCameraByName = function (name) {
  19038. var camera = this.getCameraByName(name);
  19039. if (camera) {
  19040. this.activeCamera = camera;
  19041. return camera;
  19042. }
  19043. return null;
  19044. };
  19045. /**
  19046. * get a material using its id
  19047. * @param {string} the material's ID
  19048. * @return {BABYLON.Material|null} the material or null if none found.
  19049. */
  19050. Scene.prototype.getMaterialByID = function (id) {
  19051. for (var index = 0; index < this.materials.length; index++) {
  19052. if (this.materials[index].id === id) {
  19053. return this.materials[index];
  19054. }
  19055. }
  19056. return null;
  19057. };
  19058. /**
  19059. * get a material using its name
  19060. * @param {string} the material's name
  19061. * @return {BABYLON.Material|null} the material or null if none found.
  19062. */
  19063. Scene.prototype.getMaterialByName = function (name) {
  19064. for (var index = 0; index < this.materials.length; index++) {
  19065. if (this.materials[index].name === name) {
  19066. return this.materials[index];
  19067. }
  19068. }
  19069. return null;
  19070. };
  19071. Scene.prototype.getLensFlareSystemByName = function (name) {
  19072. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19073. if (this.lensFlareSystems[index].name === name) {
  19074. return this.lensFlareSystems[index];
  19075. }
  19076. }
  19077. return null;
  19078. };
  19079. Scene.prototype.getLensFlareSystemByID = function (id) {
  19080. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19081. if (this.lensFlareSystems[index].id === id) {
  19082. return this.lensFlareSystems[index];
  19083. }
  19084. }
  19085. return null;
  19086. };
  19087. Scene.prototype.getCameraByID = function (id) {
  19088. for (var index = 0; index < this.cameras.length; index++) {
  19089. if (this.cameras[index].id === id) {
  19090. return this.cameras[index];
  19091. }
  19092. }
  19093. return null;
  19094. };
  19095. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19096. for (var index = 0; index < this.cameras.length; index++) {
  19097. if (this.cameras[index].uniqueId === uniqueId) {
  19098. return this.cameras[index];
  19099. }
  19100. }
  19101. return null;
  19102. };
  19103. /**
  19104. * get a camera using its name
  19105. * @param {string} the camera's name
  19106. * @return {BABYLON.Camera|null} the camera or null if none found.
  19107. */
  19108. Scene.prototype.getCameraByName = function (name) {
  19109. for (var index = 0; index < this.cameras.length; index++) {
  19110. if (this.cameras[index].name === name) {
  19111. return this.cameras[index];
  19112. }
  19113. }
  19114. return null;
  19115. };
  19116. /**
  19117. * get a bone using its id
  19118. * @param {string} the bone's id
  19119. * @return {BABYLON.Bone|null} the bone or null if not found
  19120. */
  19121. Scene.prototype.getBoneByID = function (id) {
  19122. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19123. var skeleton = this.skeletons[skeletonIndex];
  19124. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19125. if (skeleton.bones[boneIndex].id === id) {
  19126. return skeleton.bones[boneIndex];
  19127. }
  19128. }
  19129. }
  19130. return null;
  19131. };
  19132. /**
  19133. * get a bone using its id
  19134. * @param {string} the bone's name
  19135. * @return {BABYLON.Bone|null} the bone or null if not found
  19136. */
  19137. Scene.prototype.getBoneByName = function (name) {
  19138. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19139. var skeleton = this.skeletons[skeletonIndex];
  19140. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19141. if (skeleton.bones[boneIndex].name === name) {
  19142. return skeleton.bones[boneIndex];
  19143. }
  19144. }
  19145. }
  19146. return null;
  19147. };
  19148. /**
  19149. * get a light node using its name
  19150. * @param {string} the light's name
  19151. * @return {BABYLON.Light|null} the light or null if none found.
  19152. */
  19153. Scene.prototype.getLightByName = function (name) {
  19154. for (var index = 0; index < this.lights.length; index++) {
  19155. if (this.lights[index].name === name) {
  19156. return this.lights[index];
  19157. }
  19158. }
  19159. return null;
  19160. };
  19161. /**
  19162. * get a light node using its ID
  19163. * @param {string} the light's id
  19164. * @return {BABYLON.Light|null} the light or null if none found.
  19165. */
  19166. Scene.prototype.getLightByID = function (id) {
  19167. for (var index = 0; index < this.lights.length; index++) {
  19168. if (this.lights[index].id === id) {
  19169. return this.lights[index];
  19170. }
  19171. }
  19172. return null;
  19173. };
  19174. /**
  19175. * get a light node using its scene-generated unique ID
  19176. * @param {number} the light's unique id
  19177. * @return {BABYLON.Light|null} the light or null if none found.
  19178. */
  19179. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19180. for (var index = 0; index < this.lights.length; index++) {
  19181. if (this.lights[index].uniqueId === uniqueId) {
  19182. return this.lights[index];
  19183. }
  19184. }
  19185. return null;
  19186. };
  19187. /**
  19188. * get a particle system by id
  19189. * @param id {number} the particle system id
  19190. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19191. */
  19192. Scene.prototype.getParticleSystemByID = function (id) {
  19193. for (var index = 0; index < this.particleSystems.length; index++) {
  19194. if (this.particleSystems[index].id === id) {
  19195. return this.particleSystems[index];
  19196. }
  19197. }
  19198. return null;
  19199. };
  19200. /**
  19201. * get a geometry using its ID
  19202. * @param {string} the geometry's id
  19203. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19204. */
  19205. Scene.prototype.getGeometryByID = function (id) {
  19206. for (var index = 0; index < this._geometries.length; index++) {
  19207. if (this._geometries[index].id === id) {
  19208. return this._geometries[index];
  19209. }
  19210. }
  19211. return null;
  19212. };
  19213. /**
  19214. * add a new geometry to this scene.
  19215. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19216. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19217. * @return {boolean} was the geometry added or not
  19218. */
  19219. Scene.prototype.pushGeometry = function (geometry, force) {
  19220. if (!force && this.getGeometryByID(geometry.id)) {
  19221. return false;
  19222. }
  19223. this._geometries.push(geometry);
  19224. //notify the collision coordinator
  19225. if (this.collisionCoordinator) {
  19226. this.collisionCoordinator.onGeometryAdded(geometry);
  19227. }
  19228. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19229. return true;
  19230. };
  19231. /**
  19232. * Removes an existing geometry
  19233. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19234. * @return {boolean} was the geometry removed or not
  19235. */
  19236. Scene.prototype.removeGeometry = function (geometry) {
  19237. var index = this._geometries.indexOf(geometry);
  19238. if (index > -1) {
  19239. this._geometries.splice(index, 1);
  19240. //notify the collision coordinator
  19241. if (this.collisionCoordinator) {
  19242. this.collisionCoordinator.onGeometryDeleted(geometry);
  19243. }
  19244. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19245. return true;
  19246. }
  19247. return false;
  19248. };
  19249. Scene.prototype.getGeometries = function () {
  19250. return this._geometries;
  19251. };
  19252. /**
  19253. * Get the first added mesh found of a given ID
  19254. * @param {string} id - the id to search for
  19255. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19256. */
  19257. Scene.prototype.getMeshByID = function (id) {
  19258. for (var index = 0; index < this.meshes.length; index++) {
  19259. if (this.meshes[index].id === id) {
  19260. return this.meshes[index];
  19261. }
  19262. }
  19263. return null;
  19264. };
  19265. Scene.prototype.getMeshesByID = function (id) {
  19266. return this.meshes.filter(function (m) {
  19267. return m.id === id;
  19268. });
  19269. };
  19270. /**
  19271. * Get a mesh with its auto-generated unique id
  19272. * @param {number} uniqueId - the unique id to search for
  19273. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19274. */
  19275. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19276. for (var index = 0; index < this.meshes.length; index++) {
  19277. if (this.meshes[index].uniqueId === uniqueId) {
  19278. return this.meshes[index];
  19279. }
  19280. }
  19281. return null;
  19282. };
  19283. /**
  19284. * Get a the last added mesh found of a given ID
  19285. * @param {string} id - the id to search for
  19286. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19287. */
  19288. Scene.prototype.getLastMeshByID = function (id) {
  19289. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19290. if (this.meshes[index].id === id) {
  19291. return this.meshes[index];
  19292. }
  19293. }
  19294. return null;
  19295. };
  19296. /**
  19297. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19298. * @param {string} id - the id to search for
  19299. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19300. */
  19301. Scene.prototype.getLastEntryByID = function (id) {
  19302. var index;
  19303. for (index = this.meshes.length - 1; index >= 0; index--) {
  19304. if (this.meshes[index].id === id) {
  19305. return this.meshes[index];
  19306. }
  19307. }
  19308. for (index = this.cameras.length - 1; index >= 0; index--) {
  19309. if (this.cameras[index].id === id) {
  19310. return this.cameras[index];
  19311. }
  19312. }
  19313. for (index = this.lights.length - 1; index >= 0; index--) {
  19314. if (this.lights[index].id === id) {
  19315. return this.lights[index];
  19316. }
  19317. }
  19318. return null;
  19319. };
  19320. Scene.prototype.getNodeByID = function (id) {
  19321. var mesh = this.getMeshByID(id);
  19322. if (mesh) {
  19323. return mesh;
  19324. }
  19325. var light = this.getLightByID(id);
  19326. if (light) {
  19327. return light;
  19328. }
  19329. var camera = this.getCameraByID(id);
  19330. if (camera) {
  19331. return camera;
  19332. }
  19333. var bone = this.getBoneByID(id);
  19334. return bone;
  19335. };
  19336. Scene.prototype.getNodeByName = function (name) {
  19337. var mesh = this.getMeshByName(name);
  19338. if (mesh) {
  19339. return mesh;
  19340. }
  19341. var light = this.getLightByName(name);
  19342. if (light) {
  19343. return light;
  19344. }
  19345. var camera = this.getCameraByName(name);
  19346. if (camera) {
  19347. return camera;
  19348. }
  19349. var bone = this.getBoneByName(name);
  19350. return bone;
  19351. };
  19352. Scene.prototype.getMeshByName = function (name) {
  19353. for (var index = 0; index < this.meshes.length; index++) {
  19354. if (this.meshes[index].name === name) {
  19355. return this.meshes[index];
  19356. }
  19357. }
  19358. return null;
  19359. };
  19360. Scene.prototype.getSoundByName = function (name) {
  19361. var index;
  19362. if (BABYLON.AudioEngine) {
  19363. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19364. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19365. return this.mainSoundTrack.soundCollection[index];
  19366. }
  19367. }
  19368. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19369. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19370. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19371. return this.soundTracks[sdIndex].soundCollection[index];
  19372. }
  19373. }
  19374. }
  19375. }
  19376. return null;
  19377. };
  19378. Scene.prototype.getLastSkeletonByID = function (id) {
  19379. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19380. if (this.skeletons[index].id === id) {
  19381. return this.skeletons[index];
  19382. }
  19383. }
  19384. return null;
  19385. };
  19386. Scene.prototype.getSkeletonById = function (id) {
  19387. for (var index = 0; index < this.skeletons.length; index++) {
  19388. if (this.skeletons[index].id === id) {
  19389. return this.skeletons[index];
  19390. }
  19391. }
  19392. return null;
  19393. };
  19394. Scene.prototype.getSkeletonByName = function (name) {
  19395. for (var index = 0; index < this.skeletons.length; index++) {
  19396. if (this.skeletons[index].name === name) {
  19397. return this.skeletons[index];
  19398. }
  19399. }
  19400. return null;
  19401. };
  19402. Scene.prototype.getMorphTargetManagerById = function (id) {
  19403. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19404. if (this.morphTargetManagers[index].uniqueId === id) {
  19405. return this.morphTargetManagers[index];
  19406. }
  19407. }
  19408. return null;
  19409. };
  19410. Scene.prototype.isActiveMesh = function (mesh) {
  19411. return (this._activeMeshes.indexOf(mesh) !== -1);
  19412. };
  19413. /**
  19414. * Return a the first highlight layer of the scene with a given name.
  19415. * @param name The name of the highlight layer to look for.
  19416. * @return The highlight layer if found otherwise null.
  19417. */
  19418. Scene.prototype.getHighlightLayerByName = function (name) {
  19419. for (var index = 0; index < this.highlightLayers.length; index++) {
  19420. if (this.highlightLayers[index].name === name) {
  19421. return this.highlightLayers[index];
  19422. }
  19423. }
  19424. return null;
  19425. };
  19426. Object.defineProperty(Scene.prototype, "uid", {
  19427. /**
  19428. * Return a unique id as a string which can serve as an identifier for the scene
  19429. */
  19430. get: function () {
  19431. if (!this._uid) {
  19432. this._uid = BABYLON.Tools.RandomId();
  19433. }
  19434. return this._uid;
  19435. },
  19436. enumerable: true,
  19437. configurable: true
  19438. });
  19439. /**
  19440. * Add an externaly attached data from its key.
  19441. * This method call will fail and return false, if such key already exists.
  19442. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19443. * @param key the unique key that identifies the data
  19444. * @param data the data object to associate to the key for this Engine instance
  19445. * @return true if no such key were already present and the data was added successfully, false otherwise
  19446. */
  19447. Scene.prototype.addExternalData = function (key, data) {
  19448. if (!this._externalData) {
  19449. this._externalData = new BABYLON.StringDictionary();
  19450. }
  19451. return this._externalData.add(key, data);
  19452. };
  19453. /**
  19454. * Get an externaly attached data from its key
  19455. * @param key the unique key that identifies the data
  19456. * @return the associated data, if present (can be null), or undefined if not present
  19457. */
  19458. Scene.prototype.getExternalData = function (key) {
  19459. if (!this._externalData) {
  19460. return null;
  19461. }
  19462. return this._externalData.get(key);
  19463. };
  19464. /**
  19465. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19466. * @param key the unique key that identifies the data
  19467. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19468. * @return the associated data, can be null if the factory returned null.
  19469. */
  19470. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19471. if (!this._externalData) {
  19472. this._externalData = new BABYLON.StringDictionary();
  19473. }
  19474. return this._externalData.getOrAddWithFactory(key, factory);
  19475. };
  19476. /**
  19477. * Remove an externaly attached data from the Engine instance
  19478. * @param key the unique key that identifies the data
  19479. * @return true if the data was successfully removed, false if it doesn't exist
  19480. */
  19481. Scene.prototype.removeExternalData = function (key) {
  19482. return this._externalData.remove(key);
  19483. };
  19484. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19485. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19486. var material = subMesh.getMaterial();
  19487. if (mesh.showSubMeshesBoundingBox) {
  19488. var boundingInfo = subMesh.getBoundingInfo();
  19489. if (boundingInfo) {
  19490. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19491. }
  19492. }
  19493. if (material) {
  19494. // Render targets
  19495. if (material.getRenderTargetTextures) {
  19496. if (this._processedMaterials.indexOf(material) === -1) {
  19497. this._processedMaterials.push(material);
  19498. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19499. }
  19500. }
  19501. // Dispatch
  19502. this._activeIndices.addCount(subMesh.indexCount, false);
  19503. this._renderingManager.dispatch(subMesh);
  19504. }
  19505. }
  19506. };
  19507. Scene.prototype._isInIntermediateRendering = function () {
  19508. return this._intermediateRendering;
  19509. };
  19510. /**
  19511. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19512. */
  19513. Scene.prototype.freezeActiveMeshes = function () {
  19514. this._evaluateActiveMeshes();
  19515. this._activeMeshesFrozen = true;
  19516. return this;
  19517. };
  19518. /**
  19519. * Use this function to restart evaluating active meshes on every frame
  19520. */
  19521. Scene.prototype.unfreezeActiveMeshes = function () {
  19522. this._activeMeshesFrozen = false;
  19523. return this;
  19524. };
  19525. Scene.prototype._evaluateActiveMeshes = function () {
  19526. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19527. return;
  19528. }
  19529. if (!this.activeCamera) {
  19530. return;
  19531. }
  19532. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  19533. this.activeCamera._activeMeshes.reset();
  19534. this._activeMeshes.reset();
  19535. this._renderingManager.reset();
  19536. this._processedMaterials.reset();
  19537. this._activeParticleSystems.reset();
  19538. this._activeSkeletons.reset();
  19539. this._softwareSkinnedMeshes.reset();
  19540. if (this._boundingBoxRenderer) {
  19541. this._boundingBoxRenderer.reset();
  19542. }
  19543. // Meshes
  19544. var meshes;
  19545. var len;
  19546. if (this._selectionOctree) {
  19547. var selection = this._selectionOctree.select(this._frustumPlanes);
  19548. meshes = selection.data;
  19549. len = selection.length;
  19550. }
  19551. else {
  19552. len = this.meshes.length;
  19553. meshes = this.meshes;
  19554. }
  19555. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19556. var mesh = meshes[meshIndex];
  19557. if (mesh.isBlocked) {
  19558. continue;
  19559. }
  19560. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19561. if (!mesh.isReady() || !mesh.isEnabled()) {
  19562. continue;
  19563. }
  19564. mesh.computeWorldMatrix();
  19565. // Intersections
  19566. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19567. this._meshesForIntersections.pushNoDuplicate(mesh);
  19568. }
  19569. // Switch to current LOD
  19570. var meshLOD = mesh.getLOD(this.activeCamera);
  19571. if (!meshLOD) {
  19572. continue;
  19573. }
  19574. mesh._preActivate();
  19575. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19576. this._activeMeshes.push(mesh);
  19577. this.activeCamera._activeMeshes.push(mesh);
  19578. mesh._activate(this._renderId);
  19579. if (meshLOD !== mesh) {
  19580. meshLOD._activate(this._renderId);
  19581. }
  19582. this._activeMesh(mesh, meshLOD);
  19583. }
  19584. }
  19585. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  19586. // Particle systems
  19587. this._particlesDuration.beginMonitoring();
  19588. if (this.particlesEnabled) {
  19589. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  19590. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19591. var particleSystem = this.particleSystems[particleIndex];
  19592. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19593. continue;
  19594. }
  19595. var emitter = particleSystem.emitter;
  19596. if (!emitter.position || emitter.isEnabled()) {
  19597. this._activeParticleSystems.push(particleSystem);
  19598. particleSystem.animate();
  19599. this._renderingManager.dispatchParticles(particleSystem);
  19600. }
  19601. }
  19602. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  19603. }
  19604. this._particlesDuration.endMonitoring(false);
  19605. };
  19606. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19607. if (mesh.skeleton && this.skeletonsEnabled) {
  19608. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19609. mesh.skeleton.prepare();
  19610. }
  19611. if (!mesh.computeBonesUsingShaders) {
  19612. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19613. }
  19614. }
  19615. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19616. var boundingInfo = sourceMesh.getBoundingInfo();
  19617. if (boundingInfo) {
  19618. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19619. }
  19620. }
  19621. if (mesh && mesh.subMeshes) {
  19622. // Submeshes Octrees
  19623. var len;
  19624. var subMeshes;
  19625. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19626. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19627. len = intersections.length;
  19628. subMeshes = intersections.data;
  19629. }
  19630. else {
  19631. subMeshes = mesh.subMeshes;
  19632. len = subMeshes.length;
  19633. }
  19634. for (var subIndex = 0; subIndex < len; subIndex++) {
  19635. var subMesh = subMeshes[subIndex];
  19636. this._evaluateSubMesh(subMesh, mesh);
  19637. }
  19638. }
  19639. };
  19640. Scene.prototype.updateTransformMatrix = function (force) {
  19641. if (!this.activeCamera) {
  19642. return;
  19643. }
  19644. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19645. };
  19646. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19647. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19648. };
  19649. Scene.prototype._renderForCamera = function (camera) {
  19650. if (camera && camera._skipRendering) {
  19651. return;
  19652. }
  19653. var engine = this._engine;
  19654. this.activeCamera = camera;
  19655. if (!this.activeCamera)
  19656. throw new Error("Active camera not set");
  19657. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19658. // Viewport
  19659. engine.setViewport(this.activeCamera.viewport);
  19660. // Camera
  19661. this.resetCachedMaterial();
  19662. this._renderId++;
  19663. this.activeCamera.update();
  19664. this.updateTransformMatrix();
  19665. if (camera._alternateCamera) {
  19666. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19667. this._alternateRendering = true;
  19668. }
  19669. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19670. // Meshes
  19671. this._evaluateActiveMeshes();
  19672. // Software skinning
  19673. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19674. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19675. mesh.applySkeleton(mesh.skeleton);
  19676. }
  19677. // Render targets
  19678. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19679. var needsRestoreFrameBuffer = false;
  19680. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19681. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19682. }
  19683. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19684. this._intermediateRendering = true;
  19685. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19686. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19687. var renderTarget = this._renderTargets.data[renderIndex];
  19688. if (renderTarget._shouldRender()) {
  19689. this._renderId++;
  19690. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19691. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19692. }
  19693. }
  19694. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19695. this._intermediateRendering = false;
  19696. this._renderId++;
  19697. needsRestoreFrameBuffer = true; // Restore back buffer
  19698. }
  19699. // Render HighlightLayer Texture
  19700. var stencilState = this._engine.getStencilBuffer();
  19701. var renderhighlights = false;
  19702. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19703. this._intermediateRendering = true;
  19704. for (var i = 0; i < this.highlightLayers.length; i++) {
  19705. var highlightLayer = this.highlightLayers[i];
  19706. if (highlightLayer.shouldRender() &&
  19707. (!highlightLayer.camera ||
  19708. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19709. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19710. renderhighlights = true;
  19711. var renderTarget = highlightLayer._mainTexture;
  19712. if (renderTarget._shouldRender()) {
  19713. this._renderId++;
  19714. renderTarget.render(false, false);
  19715. needsRestoreFrameBuffer = true;
  19716. }
  19717. }
  19718. }
  19719. this._intermediateRendering = false;
  19720. this._renderId++;
  19721. }
  19722. if (needsRestoreFrameBuffer) {
  19723. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19724. }
  19725. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19726. // Prepare Frame
  19727. this.postProcessManager._prepareFrame();
  19728. this._renderDuration.beginMonitoring();
  19729. // Backgrounds
  19730. var layerIndex;
  19731. var layer;
  19732. if (this.layers.length) {
  19733. engine.setDepthBuffer(false);
  19734. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19735. layer = this.layers[layerIndex];
  19736. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19737. layer.render();
  19738. }
  19739. }
  19740. engine.setDepthBuffer(true);
  19741. }
  19742. // Render
  19743. BABYLON.Tools.StartPerformanceCounter("Main render");
  19744. // Activate HighlightLayer stencil
  19745. if (renderhighlights) {
  19746. this._engine.setStencilBuffer(true);
  19747. }
  19748. this._renderingManager.render(null, null, true, true);
  19749. // Restore HighlightLayer stencil
  19750. if (renderhighlights) {
  19751. this._engine.setStencilBuffer(stencilState);
  19752. }
  19753. BABYLON.Tools.EndPerformanceCounter("Main render");
  19754. // Bounding boxes
  19755. if (this._boundingBoxRenderer) {
  19756. this._boundingBoxRenderer.render();
  19757. }
  19758. // Lens flares
  19759. if (this.lensFlaresEnabled) {
  19760. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19761. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19762. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19763. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19764. lensFlareSystem.render();
  19765. }
  19766. }
  19767. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19768. }
  19769. // Foregrounds
  19770. if (this.layers.length) {
  19771. engine.setDepthBuffer(false);
  19772. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19773. layer = this.layers[layerIndex];
  19774. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19775. layer.render();
  19776. }
  19777. }
  19778. engine.setDepthBuffer(true);
  19779. }
  19780. // Highlight Layer
  19781. if (renderhighlights) {
  19782. engine.setDepthBuffer(false);
  19783. for (var i = 0; i < this.highlightLayers.length; i++) {
  19784. if (this.highlightLayers[i].shouldRender()) {
  19785. this.highlightLayers[i].render();
  19786. }
  19787. }
  19788. engine.setDepthBuffer(true);
  19789. }
  19790. this._renderDuration.endMonitoring(false);
  19791. // Finalize frame
  19792. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19793. // Reset some special arrays
  19794. this._renderTargets.reset();
  19795. this._alternateRendering = false;
  19796. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19797. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19798. };
  19799. Scene.prototype._processSubCameras = function (camera) {
  19800. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19801. this._renderForCamera(camera);
  19802. return;
  19803. }
  19804. // Update camera
  19805. if (this.activeCamera) {
  19806. this.activeCamera.update();
  19807. }
  19808. // rig cameras
  19809. for (var index = 0; index < camera._rigCameras.length; index++) {
  19810. this._renderForCamera(camera._rigCameras[index]);
  19811. }
  19812. this.activeCamera = camera;
  19813. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19814. };
  19815. Scene.prototype._checkIntersections = function () {
  19816. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19817. var sourceMesh = this._meshesForIntersections.data[index];
  19818. if (!sourceMesh.actionManager) {
  19819. continue;
  19820. }
  19821. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19822. var action = sourceMesh.actionManager.actions[actionIndex];
  19823. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19824. var parameters = action.getTriggerParameter();
  19825. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19826. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19827. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19828. if (areIntersecting && currentIntersectionInProgress === -1) {
  19829. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19830. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19831. sourceMesh._intersectionsInProgress.push(otherMesh);
  19832. }
  19833. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19834. sourceMesh._intersectionsInProgress.push(otherMesh);
  19835. }
  19836. }
  19837. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19838. //They intersected, and now they don't.
  19839. //is this trigger an exit trigger? execute an event.
  19840. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19841. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19842. }
  19843. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19844. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19845. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19846. }
  19847. }
  19848. }
  19849. }
  19850. }
  19851. };
  19852. Scene.prototype.render = function () {
  19853. if (this.isDisposed) {
  19854. return;
  19855. }
  19856. this._interFrameDuration.endMonitoring();
  19857. this._particlesDuration.fetchNewFrame();
  19858. this._spritesDuration.fetchNewFrame();
  19859. this._activeParticles.fetchNewFrame();
  19860. this._renderDuration.fetchNewFrame();
  19861. this._totalVertices.fetchNewFrame();
  19862. this._activeIndices.fetchNewFrame();
  19863. this._activeBones.fetchNewFrame();
  19864. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19865. this._meshesForIntersections.reset();
  19866. this.resetCachedMaterial();
  19867. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19868. // Actions
  19869. if (this.actionManager) {
  19870. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  19871. }
  19872. //Simplification Queue
  19873. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19874. this.simplificationQueue.executeNext();
  19875. }
  19876. if (this._engine.isDeterministicLockStep()) {
  19877. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19878. var defaultTimeStep = (60.0 / 1000.0);
  19879. if (this._physicsEngine) {
  19880. defaultTimeStep = this._physicsEngine.getTimeStep();
  19881. }
  19882. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19883. this._timeAccumulator += deltaTime;
  19884. // compute the amount of fixed steps we should have taken since the last step
  19885. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19886. internalSteps = Math.min(internalSteps, maxSubSteps);
  19887. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19888. this.onBeforeStepObservable.notifyObservers(this);
  19889. // Animations
  19890. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19891. this._animate();
  19892. // Physics
  19893. if (this._physicsEngine) {
  19894. BABYLON.Tools.StartPerformanceCounter("Physics");
  19895. this._physicsEngine._step(defaultTimeStep);
  19896. BABYLON.Tools.EndPerformanceCounter("Physics");
  19897. }
  19898. this._timeAccumulator -= defaultTimeStep;
  19899. this.onAfterStepObservable.notifyObservers(this);
  19900. this._currentStepId++;
  19901. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19902. this._evaluateActiveMeshes();
  19903. }
  19904. }
  19905. }
  19906. else {
  19907. // Animations
  19908. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19909. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19910. this._animate();
  19911. // Physics
  19912. if (this._physicsEngine) {
  19913. BABYLON.Tools.StartPerformanceCounter("Physics");
  19914. this._physicsEngine._step(deltaTime / 1000.0);
  19915. BABYLON.Tools.EndPerformanceCounter("Physics");
  19916. }
  19917. }
  19918. // Before render
  19919. this.onBeforeRenderObservable.notifyObservers(this);
  19920. // Customs render targets
  19921. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19922. var engine = this.getEngine();
  19923. var currentActiveCamera = this.activeCamera;
  19924. if (this.renderTargetsEnabled) {
  19925. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19926. this._intermediateRendering = true;
  19927. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19928. var renderTarget = this.customRenderTargets[customIndex];
  19929. if (renderTarget._shouldRender()) {
  19930. this._renderId++;
  19931. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19932. if (!this.activeCamera)
  19933. throw new Error("Active camera not set");
  19934. // Viewport
  19935. engine.setViewport(this.activeCamera.viewport);
  19936. // Camera
  19937. this.updateTransformMatrix();
  19938. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19939. }
  19940. }
  19941. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19942. this._intermediateRendering = false;
  19943. this._renderId++;
  19944. }
  19945. // Restore back buffer
  19946. if (this.customRenderTargets.length > 0) {
  19947. engine.restoreDefaultFramebuffer();
  19948. }
  19949. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19950. this.activeCamera = currentActiveCamera;
  19951. // Procedural textures
  19952. if (this.proceduralTexturesEnabled) {
  19953. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19954. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19955. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19956. if (proceduralTexture._shouldRender()) {
  19957. proceduralTexture.render();
  19958. }
  19959. }
  19960. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19961. }
  19962. // Clear
  19963. if (this.autoClearDepthAndStencil || this.autoClear) {
  19964. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19965. }
  19966. // Shadows
  19967. if (this.shadowsEnabled) {
  19968. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19969. var light = this.lights[lightIndex];
  19970. var shadowGenerator = light.getShadowGenerator();
  19971. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19972. var shadowMap = (shadowGenerator.getShadowMap());
  19973. if (this.textures.indexOf(shadowMap) !== -1) {
  19974. this._renderTargets.push(shadowMap);
  19975. }
  19976. }
  19977. }
  19978. }
  19979. // Depth renderer
  19980. if (this._depthRenderer) {
  19981. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19982. }
  19983. // Geometry renderer
  19984. if (this._geometryBufferRenderer) {
  19985. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19986. }
  19987. // RenderPipeline
  19988. if (this._postProcessRenderPipelineManager) {
  19989. this._postProcessRenderPipelineManager.update();
  19990. }
  19991. // Multi-cameras?
  19992. if (this.activeCameras.length > 0) {
  19993. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19994. if (cameraIndex > 0) {
  19995. this._engine.clear(null, false, true, true);
  19996. }
  19997. this._processSubCameras(this.activeCameras[cameraIndex]);
  19998. }
  19999. }
  20000. else {
  20001. if (!this.activeCamera) {
  20002. throw new Error("No camera defined");
  20003. }
  20004. this._processSubCameras(this.activeCamera);
  20005. }
  20006. // Intersection checks
  20007. this._checkIntersections();
  20008. // Update the audio listener attached to the camera
  20009. if (BABYLON.AudioEngine) {
  20010. this._updateAudioParameters();
  20011. }
  20012. // After render
  20013. if (this.afterRender) {
  20014. this.afterRender();
  20015. }
  20016. this.onAfterRenderObservable.notifyObservers(this);
  20017. // Cleaning
  20018. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20019. var data = this._toBeDisposed.data[index];
  20020. if (data) {
  20021. data.dispose();
  20022. }
  20023. this._toBeDisposed[index] = null;
  20024. }
  20025. this._toBeDisposed.reset();
  20026. if (this.dumpNextRenderTargets) {
  20027. this.dumpNextRenderTargets = false;
  20028. }
  20029. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  20030. this._interFrameDuration.beginMonitoring();
  20031. this._activeBones.addCount(0, true);
  20032. this._activeIndices.addCount(0, true);
  20033. this._activeParticles.addCount(0, true);
  20034. };
  20035. Scene.prototype._updateAudioParameters = function () {
  20036. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20037. return;
  20038. }
  20039. var listeningCamera;
  20040. var audioEngine = BABYLON.Engine.audioEngine;
  20041. if (this.activeCameras.length > 0) {
  20042. listeningCamera = this.activeCameras[0];
  20043. }
  20044. else {
  20045. listeningCamera = this.activeCamera;
  20046. }
  20047. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20048. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20049. // for VR cameras
  20050. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20051. listeningCamera = listeningCamera.rigCameras[0];
  20052. }
  20053. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20054. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20055. cameraDirection.normalize();
  20056. // To avoid some errors on GearVR
  20057. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20058. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20059. }
  20060. var i;
  20061. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20062. var sound = this.mainSoundTrack.soundCollection[i];
  20063. if (sound.useCustomAttenuation) {
  20064. sound.updateDistanceFromListener();
  20065. }
  20066. }
  20067. for (i = 0; i < this.soundTracks.length; i++) {
  20068. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20069. sound = this.soundTracks[i].soundCollection[j];
  20070. if (sound.useCustomAttenuation) {
  20071. sound.updateDistanceFromListener();
  20072. }
  20073. }
  20074. }
  20075. }
  20076. };
  20077. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20078. // Audio
  20079. get: function () {
  20080. return this._audioEnabled;
  20081. },
  20082. set: function (value) {
  20083. this._audioEnabled = value;
  20084. if (BABYLON.AudioEngine) {
  20085. if (this._audioEnabled) {
  20086. this._enableAudio();
  20087. }
  20088. else {
  20089. this._disableAudio();
  20090. }
  20091. }
  20092. },
  20093. enumerable: true,
  20094. configurable: true
  20095. });
  20096. Scene.prototype._disableAudio = function () {
  20097. var i;
  20098. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20099. this.mainSoundTrack.soundCollection[i].pause();
  20100. }
  20101. for (i = 0; i < this.soundTracks.length; i++) {
  20102. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20103. this.soundTracks[i].soundCollection[j].pause();
  20104. }
  20105. }
  20106. };
  20107. Scene.prototype._enableAudio = function () {
  20108. var i;
  20109. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20110. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20111. this.mainSoundTrack.soundCollection[i].play();
  20112. }
  20113. }
  20114. for (i = 0; i < this.soundTracks.length; i++) {
  20115. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20116. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20117. this.soundTracks[i].soundCollection[j].play();
  20118. }
  20119. }
  20120. }
  20121. };
  20122. Object.defineProperty(Scene.prototype, "headphone", {
  20123. get: function () {
  20124. return this._headphone;
  20125. },
  20126. set: function (value) {
  20127. this._headphone = value;
  20128. if (BABYLON.AudioEngine) {
  20129. if (this._headphone) {
  20130. this._switchAudioModeForHeadphones();
  20131. }
  20132. else {
  20133. this._switchAudioModeForNormalSpeakers();
  20134. }
  20135. }
  20136. },
  20137. enumerable: true,
  20138. configurable: true
  20139. });
  20140. Scene.prototype._switchAudioModeForHeadphones = function () {
  20141. this.mainSoundTrack.switchPanningModelToHRTF();
  20142. for (var i = 0; i < this.soundTracks.length; i++) {
  20143. this.soundTracks[i].switchPanningModelToHRTF();
  20144. }
  20145. };
  20146. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20147. this.mainSoundTrack.switchPanningModelToEqualPower();
  20148. for (var i = 0; i < this.soundTracks.length; i++) {
  20149. this.soundTracks[i].switchPanningModelToEqualPower();
  20150. }
  20151. };
  20152. Scene.prototype.enableDepthRenderer = function () {
  20153. if (this._depthRenderer) {
  20154. return this._depthRenderer;
  20155. }
  20156. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20157. return this._depthRenderer;
  20158. };
  20159. Scene.prototype.disableDepthRenderer = function () {
  20160. if (!this._depthRenderer) {
  20161. return;
  20162. }
  20163. this._depthRenderer.dispose();
  20164. this._depthRenderer = null;
  20165. };
  20166. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20167. if (ratio === void 0) { ratio = 1; }
  20168. if (this._geometryBufferRenderer) {
  20169. return this._geometryBufferRenderer;
  20170. }
  20171. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20172. if (!this._geometryBufferRenderer.isSupported) {
  20173. this._geometryBufferRenderer = null;
  20174. }
  20175. return this._geometryBufferRenderer;
  20176. };
  20177. Scene.prototype.disableGeometryBufferRenderer = function () {
  20178. if (!this._geometryBufferRenderer) {
  20179. return;
  20180. }
  20181. this._geometryBufferRenderer.dispose();
  20182. this._geometryBufferRenderer = null;
  20183. };
  20184. Scene.prototype.freezeMaterials = function () {
  20185. for (var i = 0; i < this.materials.length; i++) {
  20186. this.materials[i].freeze();
  20187. }
  20188. };
  20189. Scene.prototype.unfreezeMaterials = function () {
  20190. for (var i = 0; i < this.materials.length; i++) {
  20191. this.materials[i].unfreeze();
  20192. }
  20193. };
  20194. Scene.prototype.dispose = function () {
  20195. this.beforeRender = null;
  20196. this.afterRender = null;
  20197. this.skeletons = [];
  20198. this.morphTargetManagers = [];
  20199. this.importedMeshesFiles = new Array();
  20200. this.resetCachedMaterial();
  20201. if (this._depthRenderer) {
  20202. this._depthRenderer.dispose();
  20203. }
  20204. if (this._gamepadManager) {
  20205. this._gamepadManager.dispose();
  20206. this._gamepadManager = null;
  20207. }
  20208. // Smart arrays
  20209. if (this.activeCamera) {
  20210. this.activeCamera._activeMeshes.dispose();
  20211. this.activeCamera = null;
  20212. }
  20213. this._activeMeshes.dispose();
  20214. this._renderingManager.dispose();
  20215. this._processedMaterials.dispose();
  20216. this._activeParticleSystems.dispose();
  20217. this._activeSkeletons.dispose();
  20218. this._softwareSkinnedMeshes.dispose();
  20219. this._renderTargets.dispose();
  20220. if (this._boundingBoxRenderer) {
  20221. this._boundingBoxRenderer.dispose();
  20222. }
  20223. this._meshesForIntersections.dispose();
  20224. this._toBeDisposed.dispose();
  20225. // Debug layer
  20226. if (this._debugLayer) {
  20227. this._debugLayer.hide();
  20228. }
  20229. // Events
  20230. this.onDisposeObservable.notifyObservers(this);
  20231. this.onDisposeObservable.clear();
  20232. this.onBeforeRenderObservable.clear();
  20233. this.onAfterRenderObservable.clear();
  20234. this.OnBeforeRenderTargetsRenderObservable.clear();
  20235. this.OnAfterRenderTargetsRenderObservable.clear();
  20236. this.onAfterStepObservable.clear();
  20237. this.onBeforeStepObservable.clear();
  20238. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20239. this.onAfterActiveMeshesEvaluationObservable.clear();
  20240. this.detachControl();
  20241. // Release sounds & sounds tracks
  20242. if (BABYLON.AudioEngine) {
  20243. this.disposeSounds();
  20244. }
  20245. // VR Helper
  20246. if (this.VRHelper) {
  20247. this.VRHelper.dispose();
  20248. }
  20249. // Detach cameras
  20250. var canvas = this._engine.getRenderingCanvas();
  20251. if (canvas) {
  20252. var index;
  20253. for (index = 0; index < this.cameras.length; index++) {
  20254. this.cameras[index].detachControl(canvas);
  20255. }
  20256. }
  20257. // Release lights
  20258. while (this.lights.length) {
  20259. this.lights[0].dispose();
  20260. }
  20261. // Release meshes
  20262. while (this.meshes.length) {
  20263. this.meshes[0].dispose(true);
  20264. }
  20265. // Release cameras
  20266. while (this.cameras.length) {
  20267. this.cameras[0].dispose();
  20268. }
  20269. // Release materials
  20270. if (this.defaultMaterial) {
  20271. this.defaultMaterial.dispose();
  20272. }
  20273. while (this.multiMaterials.length) {
  20274. this.multiMaterials[0].dispose();
  20275. }
  20276. while (this.materials.length) {
  20277. this.materials[0].dispose();
  20278. }
  20279. // Release particles
  20280. while (this.particleSystems.length) {
  20281. this.particleSystems[0].dispose();
  20282. }
  20283. // Release sprites
  20284. while (this.spriteManagers.length) {
  20285. this.spriteManagers[0].dispose();
  20286. }
  20287. // Release postProcesses
  20288. while (this.postProcesses.length) {
  20289. this.postProcesses[0].dispose();
  20290. }
  20291. // Release layers
  20292. while (this.layers.length) {
  20293. this.layers[0].dispose();
  20294. }
  20295. while (this.highlightLayers.length) {
  20296. this.highlightLayers[0].dispose();
  20297. }
  20298. // Release textures
  20299. while (this.textures.length) {
  20300. this.textures[0].dispose();
  20301. }
  20302. // Release UBO
  20303. this._sceneUbo.dispose();
  20304. if (this._alternateSceneUbo) {
  20305. this._alternateSceneUbo.dispose();
  20306. }
  20307. // Post-processes
  20308. this.postProcessManager.dispose();
  20309. if (this._postProcessRenderPipelineManager) {
  20310. this._postProcessRenderPipelineManager.dispose();
  20311. }
  20312. // Physics
  20313. if (this._physicsEngine) {
  20314. this.disablePhysicsEngine();
  20315. }
  20316. // Remove from engine
  20317. index = this._engine.scenes.indexOf(this);
  20318. if (index > -1) {
  20319. this._engine.scenes.splice(index, 1);
  20320. }
  20321. this._engine.wipeCaches();
  20322. this._isDisposed = true;
  20323. };
  20324. Object.defineProperty(Scene.prototype, "isDisposed", {
  20325. get: function () {
  20326. return this._isDisposed;
  20327. },
  20328. enumerable: true,
  20329. configurable: true
  20330. });
  20331. // Release sounds & sounds tracks
  20332. Scene.prototype.disposeSounds = function () {
  20333. if (!this._mainSoundTrack) {
  20334. return;
  20335. }
  20336. this.mainSoundTrack.dispose();
  20337. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20338. this.soundTracks[scIndex].dispose();
  20339. }
  20340. };
  20341. // Octrees
  20342. Scene.prototype.getWorldExtends = function () {
  20343. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20344. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20345. for (var index = 0; index < this.meshes.length; index++) {
  20346. var mesh = this.meshes[index];
  20347. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20348. continue;
  20349. }
  20350. mesh.computeWorldMatrix(true);
  20351. var boundingInfo = mesh.getBoundingInfo();
  20352. if (boundingInfo) {
  20353. var minBox = boundingInfo.boundingBox.minimumWorld;
  20354. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20355. BABYLON.Tools.CheckExtends(minBox, min, max);
  20356. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20357. }
  20358. }
  20359. return {
  20360. min: min,
  20361. max: max
  20362. };
  20363. };
  20364. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20365. if (maxCapacity === void 0) { maxCapacity = 64; }
  20366. if (maxDepth === void 0) { maxDepth = 2; }
  20367. if (!this._selectionOctree) {
  20368. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20369. }
  20370. var worldExtends = this.getWorldExtends();
  20371. // Update octree
  20372. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20373. return this._selectionOctree;
  20374. };
  20375. // Picking
  20376. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20377. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20378. var engine = this._engine;
  20379. if (!camera) {
  20380. if (!this.activeCamera)
  20381. throw new Error("Active camera not set");
  20382. camera = this.activeCamera;
  20383. }
  20384. var cameraViewport = camera.viewport;
  20385. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20386. // Moving coordinates to local viewport world
  20387. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20388. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20389. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20390. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20391. };
  20392. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20393. if (!BABYLON.PickingInfo) {
  20394. return null;
  20395. }
  20396. var engine = this._engine;
  20397. if (!camera) {
  20398. if (!this.activeCamera)
  20399. throw new Error("Active camera not set");
  20400. camera = this.activeCamera;
  20401. }
  20402. var cameraViewport = camera.viewport;
  20403. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20404. var identity = BABYLON.Matrix.Identity();
  20405. // Moving coordinates to local viewport world
  20406. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20407. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20408. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20409. };
  20410. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20411. if (!BABYLON.PickingInfo) {
  20412. return null;
  20413. }
  20414. var pickingInfo = null;
  20415. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20416. var mesh = this.meshes[meshIndex];
  20417. if (predicate) {
  20418. if (!predicate(mesh)) {
  20419. continue;
  20420. }
  20421. }
  20422. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20423. continue;
  20424. }
  20425. var world = mesh.getWorldMatrix();
  20426. var ray = rayFunction(world);
  20427. var result = mesh.intersects(ray, fastCheck);
  20428. if (!result || !result.hit)
  20429. continue;
  20430. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20431. continue;
  20432. pickingInfo = result;
  20433. if (fastCheck) {
  20434. break;
  20435. }
  20436. }
  20437. return pickingInfo || new BABYLON.PickingInfo();
  20438. };
  20439. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20440. if (!BABYLON.PickingInfo) {
  20441. return null;
  20442. }
  20443. var pickingInfos = new Array();
  20444. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20445. var mesh = this.meshes[meshIndex];
  20446. if (predicate) {
  20447. if (!predicate(mesh)) {
  20448. continue;
  20449. }
  20450. }
  20451. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20452. continue;
  20453. }
  20454. var world = mesh.getWorldMatrix();
  20455. var ray = rayFunction(world);
  20456. var result = mesh.intersects(ray, false);
  20457. if (!result || !result.hit)
  20458. continue;
  20459. pickingInfos.push(result);
  20460. }
  20461. return pickingInfos;
  20462. };
  20463. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20464. if (!BABYLON.PickingInfo) {
  20465. return null;
  20466. }
  20467. var pickingInfo = null;
  20468. if (!camera) {
  20469. if (!this.activeCamera) {
  20470. return null;
  20471. }
  20472. camera = this.activeCamera;
  20473. }
  20474. if (this.spriteManagers.length > 0) {
  20475. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20476. var spriteManager = this.spriteManagers[spriteIndex];
  20477. if (!spriteManager.isPickable) {
  20478. continue;
  20479. }
  20480. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20481. if (!result || !result.hit)
  20482. continue;
  20483. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20484. continue;
  20485. pickingInfo = result;
  20486. if (fastCheck) {
  20487. break;
  20488. }
  20489. }
  20490. }
  20491. return pickingInfo || new BABYLON.PickingInfo();
  20492. };
  20493. /** Launch a ray to try to pick a mesh in the scene
  20494. * @param x position on screen
  20495. * @param y position on screen
  20496. * @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
  20497. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20498. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20499. */
  20500. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20501. var _this = this;
  20502. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20503. };
  20504. /** Launch a ray to try to pick a sprite in the scene
  20505. * @param x position on screen
  20506. * @param y position on screen
  20507. * @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
  20508. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20509. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20510. */
  20511. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20512. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20513. if (!ray) {
  20514. return null;
  20515. }
  20516. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20517. };
  20518. /** Use the given ray to pick a mesh in the scene
  20519. * @param ray The ray to use to pick meshes
  20520. * @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
  20521. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20522. */
  20523. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20524. var _this = this;
  20525. return this._internalPick(function (world) {
  20526. if (!_this._pickWithRayInverseMatrix) {
  20527. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20528. }
  20529. world.invertToRef(_this._pickWithRayInverseMatrix);
  20530. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20531. }, predicate, fastCheck);
  20532. };
  20533. /**
  20534. * Launch a ray to try to pick a mesh in the scene
  20535. * @param x X position on screen
  20536. * @param y Y position on screen
  20537. * @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
  20538. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20539. */
  20540. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20541. var _this = this;
  20542. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20543. };
  20544. /**
  20545. * Launch a ray to try to pick a mesh in the scene
  20546. * @param ray Ray to use
  20547. * @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
  20548. */
  20549. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20550. var _this = this;
  20551. return this._internalMultiPick(function (world) {
  20552. if (!_this._pickWithRayInverseMatrix) {
  20553. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20554. }
  20555. world.invertToRef(_this._pickWithRayInverseMatrix);
  20556. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20557. }, predicate);
  20558. };
  20559. Scene.prototype.setPointerOverMesh = function (mesh) {
  20560. if (this._pointerOverMesh === mesh) {
  20561. return;
  20562. }
  20563. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20564. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20565. }
  20566. this._pointerOverMesh = mesh;
  20567. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20568. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20569. }
  20570. };
  20571. Scene.prototype.getPointerOverMesh = function () {
  20572. return this._pointerOverMesh;
  20573. };
  20574. Scene.prototype.setPointerOverSprite = function (sprite) {
  20575. if (this._pointerOverSprite === sprite) {
  20576. return;
  20577. }
  20578. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20579. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20580. }
  20581. this._pointerOverSprite = sprite;
  20582. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20583. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20584. }
  20585. };
  20586. Scene.prototype.getPointerOverSprite = function () {
  20587. return this._pointerOverSprite;
  20588. };
  20589. // Physics
  20590. Scene.prototype.getPhysicsEngine = function () {
  20591. return this._physicsEngine;
  20592. };
  20593. /**
  20594. * Enables physics to the current scene
  20595. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20596. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20597. * @return {boolean} was the physics engine initialized
  20598. */
  20599. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20600. if (gravity === void 0) { gravity = null; }
  20601. if (this._physicsEngine) {
  20602. return true;
  20603. }
  20604. try {
  20605. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20606. return true;
  20607. }
  20608. catch (e) {
  20609. BABYLON.Tools.Error(e.message);
  20610. return false;
  20611. }
  20612. };
  20613. Scene.prototype.disablePhysicsEngine = function () {
  20614. if (!this._physicsEngine) {
  20615. return;
  20616. }
  20617. this._physicsEngine.dispose();
  20618. this._physicsEngine = null;
  20619. };
  20620. Scene.prototype.isPhysicsEnabled = function () {
  20621. return this._physicsEngine !== undefined;
  20622. };
  20623. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20624. var mesh = compound.parts[0].mesh;
  20625. if (mesh.physicsImpostor) {
  20626. mesh.physicsImpostor.dispose();
  20627. mesh.physicsImpostor = null;
  20628. }
  20629. };
  20630. // Misc.
  20631. Scene.prototype._rebuildGeometries = function () {
  20632. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20633. var geometry = _a[_i];
  20634. geometry._rebuild();
  20635. }
  20636. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20637. var mesh = _c[_b];
  20638. mesh._rebuild();
  20639. }
  20640. if (this.postProcessManager) {
  20641. this.postProcessManager._rebuild();
  20642. }
  20643. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20644. var layer = _e[_d];
  20645. layer._rebuild();
  20646. }
  20647. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20648. var highlightLayer = _g[_f];
  20649. highlightLayer._rebuild();
  20650. }
  20651. if (this._boundingBoxRenderer) {
  20652. this._boundingBoxRenderer._rebuild();
  20653. }
  20654. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20655. var system = _j[_h];
  20656. system.rebuild();
  20657. }
  20658. if (this._postProcessRenderPipelineManager) {
  20659. this._postProcessRenderPipelineManager._rebuild();
  20660. }
  20661. };
  20662. Scene.prototype._rebuildTextures = function () {
  20663. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20664. var texture = _a[_i];
  20665. texture._rebuild();
  20666. }
  20667. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20668. };
  20669. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20670. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20671. if (replace === void 0) { replace = false; }
  20672. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20673. // Dispose existing camera or light in replace mode.
  20674. if (replace) {
  20675. if (this.activeCamera) {
  20676. this.activeCamera.dispose();
  20677. this.activeCamera = null;
  20678. }
  20679. if (this.lights) {
  20680. for (var i = 0; i < this.lights.length; i++) {
  20681. this.lights[i].dispose();
  20682. }
  20683. }
  20684. }
  20685. // Light
  20686. if (this.lights.length === 0) {
  20687. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20688. }
  20689. // Camera
  20690. if (!this.activeCamera) {
  20691. var worldExtends = this.getWorldExtends();
  20692. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20693. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20694. var camera;
  20695. var radius = worldSize.length() * 1.5;
  20696. if (createArcRotateCamera) {
  20697. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20698. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20699. arcRotateCamera.wheelPrecision = 100 / radius;
  20700. camera = arcRotateCamera;
  20701. }
  20702. else {
  20703. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20704. freeCamera.setTarget(worldCenter);
  20705. camera = freeCamera;
  20706. }
  20707. camera.minZ = radius * 0.01;
  20708. camera.maxZ = radius * 100;
  20709. camera.speed = radius * 0.2;
  20710. this.activeCamera = camera;
  20711. var canvas = this.getEngine().getRenderingCanvas();
  20712. if (attachCameraControls && canvas) {
  20713. camera.attachControl(canvas);
  20714. }
  20715. }
  20716. };
  20717. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20718. if (pbr === void 0) { pbr = false; }
  20719. if (scale === void 0) { scale = 1000; }
  20720. if (blur === void 0) { blur = 0; }
  20721. if (environmentTexture) {
  20722. this.environmentTexture = environmentTexture;
  20723. }
  20724. if (!this.environmentTexture) {
  20725. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20726. return null;
  20727. }
  20728. // Skybox
  20729. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20730. if (pbr) {
  20731. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20732. hdrSkyboxMaterial.backFaceCulling = false;
  20733. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20734. if (hdrSkyboxMaterial.reflectionTexture) {
  20735. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20736. }
  20737. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20738. hdrSkyboxMaterial.disableLighting = true;
  20739. hdrSkyboxMaterial.twoSidedLighting = true;
  20740. hdrSkybox.infiniteDistance = true;
  20741. hdrSkybox.material = hdrSkyboxMaterial;
  20742. }
  20743. else {
  20744. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20745. skyboxMaterial.backFaceCulling = false;
  20746. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20747. if (skyboxMaterial.reflectionTexture) {
  20748. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20749. }
  20750. skyboxMaterial.disableLighting = true;
  20751. hdrSkybox.infiniteDistance = true;
  20752. hdrSkybox.material = skyboxMaterial;
  20753. }
  20754. return hdrSkybox;
  20755. };
  20756. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20757. if (webVROptions === void 0) { webVROptions = {}; }
  20758. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20759. };
  20760. // Tags
  20761. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20762. if (tagsQuery === undefined) {
  20763. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20764. return list;
  20765. }
  20766. var listByTags = [];
  20767. forEach = forEach || (function (item) { return; });
  20768. for (var i in list) {
  20769. var item = list[i];
  20770. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20771. listByTags.push(item);
  20772. forEach(item);
  20773. }
  20774. }
  20775. return listByTags;
  20776. };
  20777. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20778. return this._getByTags(this.meshes, tagsQuery, forEach);
  20779. };
  20780. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20781. return this._getByTags(this.cameras, tagsQuery, forEach);
  20782. };
  20783. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20784. return this._getByTags(this.lights, tagsQuery, forEach);
  20785. };
  20786. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20787. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20788. };
  20789. /**
  20790. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20791. * This allowed control for front to back rendering or reversly depending of the special needs.
  20792. *
  20793. * @param renderingGroupId The rendering group id corresponding to its index
  20794. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20795. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20796. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20797. */
  20798. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20799. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20800. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20801. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20802. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20803. };
  20804. /**
  20805. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20806. *
  20807. * @param renderingGroupId The rendering group id corresponding to its index
  20808. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20809. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20810. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20811. */
  20812. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20813. if (depth === void 0) { depth = true; }
  20814. if (stencil === void 0) { stencil = true; }
  20815. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20816. };
  20817. /**
  20818. * Will flag all materials as dirty to trigger new shader compilation
  20819. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20820. */
  20821. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20822. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20823. var material = _a[_i];
  20824. if (predicate && !predicate(material)) {
  20825. continue;
  20826. }
  20827. material.markAsDirty(flag);
  20828. }
  20829. };
  20830. // Statics
  20831. Scene._FOGMODE_NONE = 0;
  20832. Scene._FOGMODE_EXP = 1;
  20833. Scene._FOGMODE_EXP2 = 2;
  20834. Scene._FOGMODE_LINEAR = 3;
  20835. Scene._uniqueIdCounter = 0;
  20836. Scene.MinDeltaTime = 1.0;
  20837. Scene.MaxDeltaTime = 1000.0;
  20838. /** The distance in pixel that you have to move to prevent some events */
  20839. Scene.DragMovementThreshold = 10; // in pixels
  20840. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20841. Scene.LongPressDelay = 500; // in milliseconds
  20842. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20843. Scene.DoubleClickDelay = 300; // in milliseconds
  20844. /** If you need to check double click without raising a single click at first click, enable this flag */
  20845. Scene.ExclusiveDoubleClickMode = false;
  20846. return Scene;
  20847. }());
  20848. BABYLON.Scene = Scene;
  20849. })(BABYLON || (BABYLON = {}));
  20850. //# sourceMappingURL=babylon.scene.js.map
  20851. var BABYLON;
  20852. (function (BABYLON) {
  20853. var Buffer = /** @class */ (function () {
  20854. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20855. if (instanced === void 0) { instanced = false; }
  20856. if (engine instanceof BABYLON.Mesh) {
  20857. this._engine = engine.getScene().getEngine();
  20858. }
  20859. else {
  20860. this._engine = engine;
  20861. }
  20862. this._updatable = updatable;
  20863. this._data = data;
  20864. this._strideSize = stride;
  20865. if (!postponeInternalCreation) {
  20866. this.create();
  20867. }
  20868. this._instanced = instanced;
  20869. this._instanceDivisor = instanced ? 1 : 0;
  20870. }
  20871. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20872. // a lot of these parameters are ignored as they are overriden by the buffer
  20873. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20874. };
  20875. // Properties
  20876. Buffer.prototype.isUpdatable = function () {
  20877. return this._updatable;
  20878. };
  20879. Buffer.prototype.getData = function () {
  20880. return this._data;
  20881. };
  20882. Buffer.prototype.getBuffer = function () {
  20883. return this._buffer;
  20884. };
  20885. Buffer.prototype.getStrideSize = function () {
  20886. return this._strideSize;
  20887. };
  20888. Buffer.prototype.getIsInstanced = function () {
  20889. return this._instanced;
  20890. };
  20891. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  20892. get: function () {
  20893. return this._instanceDivisor;
  20894. },
  20895. set: function (value) {
  20896. this._instanceDivisor = value;
  20897. if (value == 0) {
  20898. this._instanced = false;
  20899. }
  20900. else {
  20901. this._instanced = true;
  20902. }
  20903. },
  20904. enumerable: true,
  20905. configurable: true
  20906. });
  20907. // Methods
  20908. Buffer.prototype.create = function (data) {
  20909. if (data === void 0) { data = null; }
  20910. if (!data && this._buffer) {
  20911. return; // nothing to do
  20912. }
  20913. data = data || this._data;
  20914. if (!data) {
  20915. return;
  20916. }
  20917. if (!this._buffer) {
  20918. if (this._updatable) {
  20919. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20920. this._data = data;
  20921. }
  20922. else {
  20923. this._buffer = this._engine.createVertexBuffer(data);
  20924. }
  20925. }
  20926. else if (this._updatable) {
  20927. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20928. this._data = data;
  20929. }
  20930. };
  20931. Buffer.prototype._rebuild = function () {
  20932. this._buffer = null;
  20933. this.create(this._data);
  20934. };
  20935. Buffer.prototype.update = function (data) {
  20936. this.create(data);
  20937. };
  20938. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20939. if (!this._buffer) {
  20940. return;
  20941. }
  20942. if (this._updatable) {
  20943. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20944. this._data = null;
  20945. }
  20946. };
  20947. Buffer.prototype.dispose = function () {
  20948. if (!this._buffer) {
  20949. return;
  20950. }
  20951. if (this._engine._releaseBuffer(this._buffer)) {
  20952. this._buffer = null;
  20953. }
  20954. };
  20955. return Buffer;
  20956. }());
  20957. BABYLON.Buffer = Buffer;
  20958. })(BABYLON || (BABYLON = {}));
  20959. //# sourceMappingURL=babylon.buffer.js.map
  20960. var BABYLON;
  20961. (function (BABYLON) {
  20962. var VertexBuffer = /** @class */ (function () {
  20963. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20964. if (!stride) {
  20965. // Deduce stride from kind
  20966. switch (kind) {
  20967. case VertexBuffer.PositionKind:
  20968. stride = 3;
  20969. break;
  20970. case VertexBuffer.NormalKind:
  20971. stride = 3;
  20972. break;
  20973. case VertexBuffer.UVKind:
  20974. case VertexBuffer.UV2Kind:
  20975. case VertexBuffer.UV3Kind:
  20976. case VertexBuffer.UV4Kind:
  20977. case VertexBuffer.UV5Kind:
  20978. case VertexBuffer.UV6Kind:
  20979. stride = 2;
  20980. break;
  20981. case VertexBuffer.TangentKind:
  20982. case VertexBuffer.ColorKind:
  20983. stride = 4;
  20984. break;
  20985. case VertexBuffer.MatricesIndicesKind:
  20986. case VertexBuffer.MatricesIndicesExtraKind:
  20987. stride = 4;
  20988. break;
  20989. case VertexBuffer.MatricesWeightsKind:
  20990. case VertexBuffer.MatricesWeightsExtraKind:
  20991. default:
  20992. stride = 4;
  20993. break;
  20994. }
  20995. }
  20996. if (data instanceof BABYLON.Buffer) {
  20997. if (!stride) {
  20998. stride = data.getStrideSize();
  20999. }
  21000. this._buffer = data;
  21001. this._ownsBuffer = false;
  21002. }
  21003. else {
  21004. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21005. this._ownsBuffer = true;
  21006. }
  21007. this._stride = stride;
  21008. this._offset = offset ? offset : 0;
  21009. this._size = size ? size : stride;
  21010. this._kind = kind;
  21011. }
  21012. VertexBuffer.prototype._rebuild = function () {
  21013. if (!this._buffer) {
  21014. return;
  21015. }
  21016. this._buffer._rebuild();
  21017. };
  21018. /**
  21019. * Returns the kind of the VertexBuffer (string).
  21020. */
  21021. VertexBuffer.prototype.getKind = function () {
  21022. return this._kind;
  21023. };
  21024. // Properties
  21025. /**
  21026. * Boolean : is the VertexBuffer updatable ?
  21027. */
  21028. VertexBuffer.prototype.isUpdatable = function () {
  21029. return this._buffer.isUpdatable();
  21030. };
  21031. /**
  21032. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21033. */
  21034. VertexBuffer.prototype.getData = function () {
  21035. return this._buffer.getData();
  21036. };
  21037. /**
  21038. * Returns the WebGLBuffer associated to the VertexBuffer.
  21039. */
  21040. VertexBuffer.prototype.getBuffer = function () {
  21041. return this._buffer.getBuffer();
  21042. };
  21043. /**
  21044. * Returns the stride of the VertexBuffer (integer).
  21045. */
  21046. VertexBuffer.prototype.getStrideSize = function () {
  21047. return this._stride;
  21048. };
  21049. /**
  21050. * Returns the offset (integer).
  21051. */
  21052. VertexBuffer.prototype.getOffset = function () {
  21053. return this._offset;
  21054. };
  21055. /**
  21056. * Returns the VertexBuffer total size (integer).
  21057. */
  21058. VertexBuffer.prototype.getSize = function () {
  21059. return this._size;
  21060. };
  21061. /**
  21062. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21063. */
  21064. VertexBuffer.prototype.getIsInstanced = function () {
  21065. return this._buffer.getIsInstanced();
  21066. };
  21067. /**
  21068. * Returns the instancing divisor, zero for non-instanced (integer).
  21069. */
  21070. VertexBuffer.prototype.getInstanceDivisor = function () {
  21071. return this._buffer.instanceDivisor;
  21072. };
  21073. // Methods
  21074. /**
  21075. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21076. * Returns the created WebGLBuffer.
  21077. */
  21078. VertexBuffer.prototype.create = function (data) {
  21079. return this._buffer.create(data);
  21080. };
  21081. /**
  21082. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21083. * Returns the updated WebGLBuffer.
  21084. */
  21085. VertexBuffer.prototype.update = function (data) {
  21086. return this._buffer.update(data);
  21087. };
  21088. /**
  21089. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21090. * Returns the directly updated WebGLBuffer.
  21091. */
  21092. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21093. return this._buffer.updateDirectly(data, offset);
  21094. };
  21095. /**
  21096. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21097. */
  21098. VertexBuffer.prototype.dispose = function () {
  21099. if (this._ownsBuffer) {
  21100. this._buffer.dispose();
  21101. }
  21102. };
  21103. Object.defineProperty(VertexBuffer, "PositionKind", {
  21104. get: function () {
  21105. return VertexBuffer._PositionKind;
  21106. },
  21107. enumerable: true,
  21108. configurable: true
  21109. });
  21110. Object.defineProperty(VertexBuffer, "NormalKind", {
  21111. get: function () {
  21112. return VertexBuffer._NormalKind;
  21113. },
  21114. enumerable: true,
  21115. configurable: true
  21116. });
  21117. Object.defineProperty(VertexBuffer, "TangentKind", {
  21118. get: function () {
  21119. return VertexBuffer._TangentKind;
  21120. },
  21121. enumerable: true,
  21122. configurable: true
  21123. });
  21124. Object.defineProperty(VertexBuffer, "UVKind", {
  21125. get: function () {
  21126. return VertexBuffer._UVKind;
  21127. },
  21128. enumerable: true,
  21129. configurable: true
  21130. });
  21131. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21132. get: function () {
  21133. return VertexBuffer._UV2Kind;
  21134. },
  21135. enumerable: true,
  21136. configurable: true
  21137. });
  21138. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21139. get: function () {
  21140. return VertexBuffer._UV3Kind;
  21141. },
  21142. enumerable: true,
  21143. configurable: true
  21144. });
  21145. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21146. get: function () {
  21147. return VertexBuffer._UV4Kind;
  21148. },
  21149. enumerable: true,
  21150. configurable: true
  21151. });
  21152. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21153. get: function () {
  21154. return VertexBuffer._UV5Kind;
  21155. },
  21156. enumerable: true,
  21157. configurable: true
  21158. });
  21159. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21160. get: function () {
  21161. return VertexBuffer._UV6Kind;
  21162. },
  21163. enumerable: true,
  21164. configurable: true
  21165. });
  21166. Object.defineProperty(VertexBuffer, "ColorKind", {
  21167. get: function () {
  21168. return VertexBuffer._ColorKind;
  21169. },
  21170. enumerable: true,
  21171. configurable: true
  21172. });
  21173. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21174. get: function () {
  21175. return VertexBuffer._MatricesIndicesKind;
  21176. },
  21177. enumerable: true,
  21178. configurable: true
  21179. });
  21180. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21181. get: function () {
  21182. return VertexBuffer._MatricesWeightsKind;
  21183. },
  21184. enumerable: true,
  21185. configurable: true
  21186. });
  21187. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21188. get: function () {
  21189. return VertexBuffer._MatricesIndicesExtraKind;
  21190. },
  21191. enumerable: true,
  21192. configurable: true
  21193. });
  21194. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21195. get: function () {
  21196. return VertexBuffer._MatricesWeightsExtraKind;
  21197. },
  21198. enumerable: true,
  21199. configurable: true
  21200. });
  21201. // Enums
  21202. VertexBuffer._PositionKind = "position";
  21203. VertexBuffer._NormalKind = "normal";
  21204. VertexBuffer._TangentKind = "tangent";
  21205. VertexBuffer._UVKind = "uv";
  21206. VertexBuffer._UV2Kind = "uv2";
  21207. VertexBuffer._UV3Kind = "uv3";
  21208. VertexBuffer._UV4Kind = "uv4";
  21209. VertexBuffer._UV5Kind = "uv5";
  21210. VertexBuffer._UV6Kind = "uv6";
  21211. VertexBuffer._ColorKind = "color";
  21212. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21213. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21214. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21215. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21216. return VertexBuffer;
  21217. }());
  21218. BABYLON.VertexBuffer = VertexBuffer;
  21219. })(BABYLON || (BABYLON = {}));
  21220. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21221. var BABYLON;
  21222. (function (BABYLON) {
  21223. var InternalTexture = /** @class */ (function () {
  21224. function InternalTexture(engine, dataSource) {
  21225. this.onLoadedObservable = new BABYLON.Observable();
  21226. // Private
  21227. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21228. this._references = 1;
  21229. this._engine = engine;
  21230. this._dataSource = dataSource;
  21231. this._webGLTexture = engine._createTexture();
  21232. }
  21233. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21234. get: function () {
  21235. return this._dataSource;
  21236. },
  21237. enumerable: true,
  21238. configurable: true
  21239. });
  21240. InternalTexture.prototype.incrementReferences = function () {
  21241. this._references++;
  21242. };
  21243. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21244. if (depth === void 0) { depth = 1; }
  21245. this.width = width;
  21246. this.height = height;
  21247. this.depth = depth;
  21248. this.baseWidth = width;
  21249. this.baseHeight = height;
  21250. this.baseDepth = depth;
  21251. this._size = width * height * depth;
  21252. };
  21253. InternalTexture.prototype._rebuild = function () {
  21254. var _this = this;
  21255. var proxy;
  21256. this.isReady = false;
  21257. this._cachedCoordinatesMode = null;
  21258. this._cachedWrapU = null;
  21259. this._cachedWrapV = null;
  21260. this._cachedAnisotropicFilteringLevel = null;
  21261. switch (this._dataSource) {
  21262. case InternalTexture.DATASOURCE_TEMP:
  21263. return;
  21264. case InternalTexture.DATASOURCE_URL:
  21265. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21266. _this.isReady = true;
  21267. }, null, this._buffer, undefined, this.format);
  21268. proxy._swapAndDie(this);
  21269. return;
  21270. case InternalTexture.DATASOURCE_RAW:
  21271. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21272. proxy._swapAndDie(this);
  21273. this.isReady = true;
  21274. return;
  21275. case InternalTexture.DATASOURCE_RAW3D:
  21276. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21277. proxy._swapAndDie(this);
  21278. this.isReady = true;
  21279. return;
  21280. case InternalTexture.DATASOURCE_DYNAMIC:
  21281. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21282. proxy._swapAndDie(this);
  21283. // The engine will make sure to update content so no need to flag it as isReady = true
  21284. return;
  21285. case InternalTexture.DATASOURCE_RENDERTARGET:
  21286. var options = new BABYLON.RenderTargetCreationOptions();
  21287. options.generateDepthBuffer = this._generateDepthBuffer;
  21288. options.generateMipMaps = this.generateMipMaps;
  21289. options.generateStencilBuffer = this._generateStencilBuffer;
  21290. options.samplingMode = this.samplingMode;
  21291. options.type = this.type;
  21292. if (this.isCube) {
  21293. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21294. }
  21295. else {
  21296. var size = {
  21297. width: this.width,
  21298. height: this.height
  21299. };
  21300. proxy = this._engine.createRenderTargetTexture(size, options);
  21301. }
  21302. proxy._swapAndDie(this);
  21303. this.isReady = true;
  21304. return;
  21305. case InternalTexture.DATASOURCE_CUBE:
  21306. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21307. _this.isReady = true;
  21308. }, null, this.format, this._extension);
  21309. proxy._swapAndDie(this);
  21310. return;
  21311. case InternalTexture.DATASOURCE_CUBERAW:
  21312. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21313. proxy._swapAndDie(this);
  21314. this.isReady = true;
  21315. return;
  21316. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21317. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21318. if (proxy) {
  21319. proxy._swapAndDie(_this);
  21320. }
  21321. _this.isReady = true;
  21322. }, null, this.format, this._extension);
  21323. return;
  21324. }
  21325. };
  21326. InternalTexture.prototype._swapAndDie = function (target) {
  21327. target._webGLTexture = this._webGLTexture;
  21328. if (this._framebuffer) {
  21329. target._framebuffer = this._framebuffer;
  21330. }
  21331. if (this._depthStencilBuffer) {
  21332. target._depthStencilBuffer = this._depthStencilBuffer;
  21333. }
  21334. if (this._lodTextureHigh) {
  21335. if (target._lodTextureHigh) {
  21336. target._lodTextureHigh.dispose();
  21337. }
  21338. target._lodTextureHigh = this._lodTextureHigh;
  21339. }
  21340. if (this._lodTextureMid) {
  21341. if (target._lodTextureMid) {
  21342. target._lodTextureMid.dispose();
  21343. }
  21344. target._lodTextureMid = this._lodTextureMid;
  21345. }
  21346. if (this._lodTextureLow) {
  21347. if (target._lodTextureLow) {
  21348. target._lodTextureLow.dispose();
  21349. }
  21350. target._lodTextureLow = this._lodTextureLow;
  21351. }
  21352. var cache = this._engine.getLoadedTexturesCache();
  21353. var index = cache.indexOf(this);
  21354. if (index !== -1) {
  21355. cache.splice(index, 1);
  21356. }
  21357. };
  21358. InternalTexture.prototype.dispose = function () {
  21359. if (!this._webGLTexture) {
  21360. return;
  21361. }
  21362. this._references--;
  21363. if (this._references === 0) {
  21364. this._engine._releaseTexture(this);
  21365. this._webGLTexture = null;
  21366. }
  21367. };
  21368. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21369. InternalTexture.DATASOURCE_URL = 1;
  21370. InternalTexture.DATASOURCE_TEMP = 2;
  21371. InternalTexture.DATASOURCE_RAW = 3;
  21372. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21373. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21374. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21375. InternalTexture.DATASOURCE_CUBE = 7;
  21376. InternalTexture.DATASOURCE_CUBERAW = 8;
  21377. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21378. InternalTexture.DATASOURCE_RAW3D = 10;
  21379. return InternalTexture;
  21380. }());
  21381. BABYLON.InternalTexture = InternalTexture;
  21382. })(BABYLON || (BABYLON = {}));
  21383. //# sourceMappingURL=babylon.internalTexture.js.map
  21384. var BABYLON;
  21385. (function (BABYLON) {
  21386. var BaseTexture = /** @class */ (function () {
  21387. function BaseTexture(scene) {
  21388. this._hasAlpha = false;
  21389. this.getAlphaFromRGB = false;
  21390. this.level = 1;
  21391. this.coordinatesIndex = 0;
  21392. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21393. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21394. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21395. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  21396. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21397. this.isCube = false;
  21398. this.is3D = false;
  21399. this.gammaSpace = true;
  21400. this.invertZ = false;
  21401. this.lodLevelInAlpha = false;
  21402. this.lodGenerationOffset = 0.0;
  21403. this.lodGenerationScale = 0.8;
  21404. this.isRenderTarget = false;
  21405. this.animations = new Array();
  21406. /**
  21407. * An event triggered when the texture is disposed.
  21408. * @type {BABYLON.Observable}
  21409. */
  21410. this.onDisposeObservable = new BABYLON.Observable();
  21411. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21412. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21413. if (this._scene) {
  21414. this._scene.textures.push(this);
  21415. }
  21416. this._uid = null;
  21417. }
  21418. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21419. get: function () {
  21420. return this._hasAlpha;
  21421. },
  21422. set: function (value) {
  21423. if (this._hasAlpha === value) {
  21424. return;
  21425. }
  21426. this._hasAlpha = value;
  21427. if (this._scene) {
  21428. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21429. }
  21430. },
  21431. enumerable: true,
  21432. configurable: true
  21433. });
  21434. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  21435. get: function () {
  21436. return this._coordinatesMode;
  21437. },
  21438. set: function (value) {
  21439. if (this._coordinatesMode === value) {
  21440. return;
  21441. }
  21442. this._coordinatesMode = value;
  21443. if (this._scene) {
  21444. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21445. }
  21446. },
  21447. enumerable: true,
  21448. configurable: true
  21449. });
  21450. Object.defineProperty(BaseTexture.prototype, "uid", {
  21451. get: function () {
  21452. if (!this._uid) {
  21453. this._uid = BABYLON.Tools.RandomId();
  21454. }
  21455. return this._uid;
  21456. },
  21457. enumerable: true,
  21458. configurable: true
  21459. });
  21460. BaseTexture.prototype.toString = function () {
  21461. return this.name;
  21462. };
  21463. BaseTexture.prototype.getClassName = function () {
  21464. return "BaseTexture";
  21465. };
  21466. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21467. set: function (callback) {
  21468. if (this._onDisposeObserver) {
  21469. this.onDisposeObservable.remove(this._onDisposeObserver);
  21470. }
  21471. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21472. },
  21473. enumerable: true,
  21474. configurable: true
  21475. });
  21476. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21477. get: function () {
  21478. return true;
  21479. },
  21480. enumerable: true,
  21481. configurable: true
  21482. });
  21483. BaseTexture.prototype.getScene = function () {
  21484. return this._scene;
  21485. };
  21486. BaseTexture.prototype.getTextureMatrix = function () {
  21487. return BABYLON.Matrix.IdentityReadOnly;
  21488. };
  21489. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21490. return BABYLON.Matrix.IdentityReadOnly;
  21491. };
  21492. BaseTexture.prototype.getInternalTexture = function () {
  21493. return this._texture;
  21494. };
  21495. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21496. return !this.isBlocking || this.isReady();
  21497. };
  21498. BaseTexture.prototype.isReady = function () {
  21499. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21500. this.delayLoad();
  21501. return false;
  21502. }
  21503. if (this._texture) {
  21504. return this._texture.isReady;
  21505. }
  21506. return false;
  21507. };
  21508. BaseTexture.prototype.getSize = function () {
  21509. if (this._texture && this._texture.width) {
  21510. return new BABYLON.Size(this._texture.width, this._texture.height);
  21511. }
  21512. if (this._texture && this._texture._size) {
  21513. return new BABYLON.Size(this._texture._size, this._texture._size);
  21514. }
  21515. return BABYLON.Size.Zero();
  21516. };
  21517. BaseTexture.prototype.getBaseSize = function () {
  21518. if (!this.isReady() || !this._texture)
  21519. return BABYLON.Size.Zero();
  21520. if (this._texture._size) {
  21521. return new BABYLON.Size(this._texture._size, this._texture._size);
  21522. }
  21523. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21524. };
  21525. BaseTexture.prototype.scale = function (ratio) {
  21526. };
  21527. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21528. get: function () {
  21529. return false;
  21530. },
  21531. enumerable: true,
  21532. configurable: true
  21533. });
  21534. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21535. if (!this._scene) {
  21536. return null;
  21537. }
  21538. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21539. for (var index = 0; index < texturesCache.length; index++) {
  21540. var texturesCacheEntry = texturesCache[index];
  21541. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21542. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21543. texturesCacheEntry.incrementReferences();
  21544. return texturesCacheEntry;
  21545. }
  21546. }
  21547. }
  21548. return null;
  21549. };
  21550. BaseTexture.prototype._rebuild = function () {
  21551. };
  21552. BaseTexture.prototype.delayLoad = function () {
  21553. };
  21554. BaseTexture.prototype.clone = function () {
  21555. return null;
  21556. };
  21557. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21558. get: function () {
  21559. if (!this._texture) {
  21560. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21561. }
  21562. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21563. },
  21564. enumerable: true,
  21565. configurable: true
  21566. });
  21567. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21568. get: function () {
  21569. if (!this._texture) {
  21570. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21571. }
  21572. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21573. },
  21574. enumerable: true,
  21575. configurable: true
  21576. });
  21577. BaseTexture.prototype.readPixels = function (faceIndex) {
  21578. if (faceIndex === void 0) { faceIndex = 0; }
  21579. if (!this._texture) {
  21580. return null;
  21581. }
  21582. var size = this.getSize();
  21583. var scene = this.getScene();
  21584. if (!scene) {
  21585. return null;
  21586. }
  21587. var engine = scene.getEngine();
  21588. if (this._texture.isCube) {
  21589. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21590. }
  21591. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21592. };
  21593. BaseTexture.prototype.releaseInternalTexture = function () {
  21594. if (this._texture) {
  21595. this._texture.dispose();
  21596. this._texture = null;
  21597. }
  21598. };
  21599. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21600. get: function () {
  21601. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21602. return null;
  21603. }
  21604. if (!this._texture._sphericalPolynomial) {
  21605. this._texture._sphericalPolynomial =
  21606. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21607. }
  21608. return this._texture._sphericalPolynomial;
  21609. },
  21610. set: function (value) {
  21611. if (this._texture) {
  21612. this._texture._sphericalPolynomial = value;
  21613. }
  21614. },
  21615. enumerable: true,
  21616. configurable: true
  21617. });
  21618. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21619. get: function () {
  21620. if (this._texture) {
  21621. return this._texture._lodTextureHigh;
  21622. }
  21623. return null;
  21624. },
  21625. enumerable: true,
  21626. configurable: true
  21627. });
  21628. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21629. get: function () {
  21630. if (this._texture) {
  21631. return this._texture._lodTextureMid;
  21632. }
  21633. return null;
  21634. },
  21635. enumerable: true,
  21636. configurable: true
  21637. });
  21638. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21639. get: function () {
  21640. if (this._texture) {
  21641. return this._texture._lodTextureLow;
  21642. }
  21643. return null;
  21644. },
  21645. enumerable: true,
  21646. configurable: true
  21647. });
  21648. BaseTexture.prototype.dispose = function () {
  21649. if (!this._scene) {
  21650. return;
  21651. }
  21652. // Animations
  21653. this._scene.stopAnimation(this);
  21654. // Remove from scene
  21655. this._scene._removePendingData(this);
  21656. var index = this._scene.textures.indexOf(this);
  21657. if (index >= 0) {
  21658. this._scene.textures.splice(index, 1);
  21659. }
  21660. if (this._texture === undefined) {
  21661. return;
  21662. }
  21663. // Release
  21664. this.releaseInternalTexture();
  21665. // Callback
  21666. this.onDisposeObservable.notifyObservers(this);
  21667. this.onDisposeObservable.clear();
  21668. };
  21669. BaseTexture.prototype.serialize = function () {
  21670. if (!this.name) {
  21671. return null;
  21672. }
  21673. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21674. // Animations
  21675. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21676. return serializationObject;
  21677. };
  21678. BaseTexture.WhenAllReady = function (textures, callback) {
  21679. var numRemaining = textures.length;
  21680. if (numRemaining === 0) {
  21681. callback();
  21682. return;
  21683. }
  21684. var _loop_1 = function () {
  21685. texture = textures[i];
  21686. if (texture.isReady()) {
  21687. if (--numRemaining === 0) {
  21688. callback();
  21689. }
  21690. }
  21691. else {
  21692. onLoadObservable = texture.onLoadObservable;
  21693. var onLoadCallback_1 = function () {
  21694. onLoadObservable.removeCallback(onLoadCallback_1);
  21695. if (--numRemaining === 0) {
  21696. callback();
  21697. }
  21698. };
  21699. onLoadObservable.add(onLoadCallback_1);
  21700. }
  21701. };
  21702. var texture, onLoadObservable;
  21703. for (var i = 0; i < textures.length; i++) {
  21704. _loop_1();
  21705. }
  21706. };
  21707. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21708. __decorate([
  21709. BABYLON.serialize()
  21710. ], BaseTexture.prototype, "name", void 0);
  21711. __decorate([
  21712. BABYLON.serialize("hasAlpha")
  21713. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21714. __decorate([
  21715. BABYLON.serialize()
  21716. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21717. __decorate([
  21718. BABYLON.serialize()
  21719. ], BaseTexture.prototype, "level", void 0);
  21720. __decorate([
  21721. BABYLON.serialize()
  21722. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21723. __decorate([
  21724. BABYLON.serialize("coordinatesMode")
  21725. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21726. __decorate([
  21727. BABYLON.serialize()
  21728. ], BaseTexture.prototype, "wrapU", void 0);
  21729. __decorate([
  21730. BABYLON.serialize()
  21731. ], BaseTexture.prototype, "wrapV", void 0);
  21732. __decorate([
  21733. BABYLON.serialize()
  21734. ], BaseTexture.prototype, "wrapR", void 0);
  21735. __decorate([
  21736. BABYLON.serialize()
  21737. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21738. __decorate([
  21739. BABYLON.serialize()
  21740. ], BaseTexture.prototype, "isCube", void 0);
  21741. __decorate([
  21742. BABYLON.serialize()
  21743. ], BaseTexture.prototype, "is3D", void 0);
  21744. __decorate([
  21745. BABYLON.serialize()
  21746. ], BaseTexture.prototype, "gammaSpace", void 0);
  21747. __decorate([
  21748. BABYLON.serialize()
  21749. ], BaseTexture.prototype, "invertZ", void 0);
  21750. __decorate([
  21751. BABYLON.serialize()
  21752. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21753. __decorate([
  21754. BABYLON.serialize()
  21755. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21756. __decorate([
  21757. BABYLON.serialize()
  21758. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21759. __decorate([
  21760. BABYLON.serialize()
  21761. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21762. return BaseTexture;
  21763. }());
  21764. BABYLON.BaseTexture = BaseTexture;
  21765. })(BABYLON || (BABYLON = {}));
  21766. //# sourceMappingURL=babylon.baseTexture.js.map
  21767. var BABYLON;
  21768. (function (BABYLON) {
  21769. var Texture = /** @class */ (function (_super) {
  21770. __extends(Texture, _super);
  21771. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21772. if (noMipmap === void 0) { noMipmap = false; }
  21773. if (invertY === void 0) { invertY = true; }
  21774. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21775. if (onLoad === void 0) { onLoad = null; }
  21776. if (onError === void 0) { onError = null; }
  21777. if (buffer === void 0) { buffer = null; }
  21778. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21779. var _this = _super.call(this, scene) || this;
  21780. _this.uOffset = 0;
  21781. _this.vOffset = 0;
  21782. _this.uScale = 1.0;
  21783. _this.vScale = 1.0;
  21784. _this.uAng = 0;
  21785. _this.vAng = 0;
  21786. _this.wAng = 0;
  21787. _this._isBlocking = true;
  21788. _this.name = url || "";
  21789. _this.url = url;
  21790. _this._noMipmap = noMipmap;
  21791. _this._invertY = invertY;
  21792. _this._samplingMode = samplingMode;
  21793. _this._buffer = buffer;
  21794. _this._deleteBuffer = deleteBuffer;
  21795. if (format) {
  21796. _this._format = format;
  21797. }
  21798. scene = _this.getScene();
  21799. if (!scene) {
  21800. return _this;
  21801. }
  21802. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21803. var load = function () {
  21804. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21805. _this.onLoadObservable.notifyObservers(_this);
  21806. }
  21807. if (onLoad) {
  21808. onLoad();
  21809. }
  21810. if (!_this.isBlocking && scene) {
  21811. scene.resetCachedMaterial();
  21812. }
  21813. };
  21814. if (!_this.url) {
  21815. _this._delayedOnLoad = load;
  21816. _this._delayedOnError = onError;
  21817. return _this;
  21818. }
  21819. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21820. if (!_this._texture) {
  21821. if (!scene.useDelayedTextureLoading) {
  21822. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  21823. if (deleteBuffer) {
  21824. delete _this._buffer;
  21825. }
  21826. }
  21827. else {
  21828. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21829. _this._delayedOnLoad = load;
  21830. _this._delayedOnError = onError;
  21831. }
  21832. }
  21833. else {
  21834. if (_this._texture.isReady) {
  21835. BABYLON.Tools.SetImmediate(function () { return load(); });
  21836. }
  21837. else {
  21838. _this._texture.onLoadedObservable.add(load);
  21839. }
  21840. }
  21841. return _this;
  21842. }
  21843. Object.defineProperty(Texture.prototype, "noMipmap", {
  21844. get: function () {
  21845. return this._noMipmap;
  21846. },
  21847. enumerable: true,
  21848. configurable: true
  21849. });
  21850. Object.defineProperty(Texture.prototype, "isBlocking", {
  21851. get: function () {
  21852. return this._isBlocking;
  21853. },
  21854. set: function (value) {
  21855. this._isBlocking = value;
  21856. },
  21857. enumerable: true,
  21858. configurable: true
  21859. });
  21860. Object.defineProperty(Texture.prototype, "samplingMode", {
  21861. get: function () {
  21862. return this._samplingMode;
  21863. },
  21864. enumerable: true,
  21865. configurable: true
  21866. });
  21867. Texture.prototype.updateURL = function (url) {
  21868. this.url = url;
  21869. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21870. this.delayLoad();
  21871. };
  21872. Texture.prototype.delayLoad = function () {
  21873. var _this = this;
  21874. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21875. return;
  21876. }
  21877. var scene = this.getScene();
  21878. if (!scene) {
  21879. return;
  21880. }
  21881. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21882. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21883. if (!this._texture) {
  21884. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  21885. if (this._deleteBuffer) {
  21886. delete this._buffer;
  21887. }
  21888. }
  21889. else {
  21890. if (this._texture.isReady) {
  21891. BABYLON.Tools.SetImmediate(function () {
  21892. if (!_this._delayedOnLoad) {
  21893. return;
  21894. }
  21895. _this._delayedOnLoad();
  21896. });
  21897. }
  21898. else {
  21899. if (this._delayedOnLoad) {
  21900. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  21901. }
  21902. }
  21903. }
  21904. };
  21905. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21906. if (!this._texture) {
  21907. return;
  21908. }
  21909. var scene = this.getScene();
  21910. if (!scene) {
  21911. return;
  21912. }
  21913. this._samplingMode = samplingMode;
  21914. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21915. };
  21916. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21917. x *= this.uScale;
  21918. y *= this.vScale;
  21919. x -= 0.5 * this.uScale;
  21920. y -= 0.5 * this.vScale;
  21921. z -= 0.5;
  21922. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21923. t.x += 0.5 * this.uScale + this.uOffset;
  21924. t.y += 0.5 * this.vScale + this.vOffset;
  21925. t.z += 0.5;
  21926. };
  21927. Texture.prototype.getTextureMatrix = function () {
  21928. var _this = this;
  21929. if (this.uOffset === this._cachedUOffset &&
  21930. this.vOffset === this._cachedVOffset &&
  21931. this.uScale === this._cachedUScale &&
  21932. this.vScale === this._cachedVScale &&
  21933. this.uAng === this._cachedUAng &&
  21934. this.vAng === this._cachedVAng &&
  21935. this.wAng === this._cachedWAng) {
  21936. return this._cachedTextureMatrix;
  21937. }
  21938. this._cachedUOffset = this.uOffset;
  21939. this._cachedVOffset = this.vOffset;
  21940. this._cachedUScale = this.uScale;
  21941. this._cachedVScale = this.vScale;
  21942. this._cachedUAng = this.uAng;
  21943. this._cachedVAng = this.vAng;
  21944. this._cachedWAng = this.wAng;
  21945. if (!this._cachedTextureMatrix) {
  21946. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21947. this._rowGenerationMatrix = new BABYLON.Matrix();
  21948. this._t0 = BABYLON.Vector3.Zero();
  21949. this._t1 = BABYLON.Vector3.Zero();
  21950. this._t2 = BABYLON.Vector3.Zero();
  21951. }
  21952. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21953. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21954. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21955. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21956. this._t1.subtractInPlace(this._t0);
  21957. this._t2.subtractInPlace(this._t0);
  21958. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21959. this._cachedTextureMatrix.m[0] = this._t1.x;
  21960. this._cachedTextureMatrix.m[1] = this._t1.y;
  21961. this._cachedTextureMatrix.m[2] = this._t1.z;
  21962. this._cachedTextureMatrix.m[4] = this._t2.x;
  21963. this._cachedTextureMatrix.m[5] = this._t2.y;
  21964. this._cachedTextureMatrix.m[6] = this._t2.z;
  21965. this._cachedTextureMatrix.m[8] = this._t0.x;
  21966. this._cachedTextureMatrix.m[9] = this._t0.y;
  21967. this._cachedTextureMatrix.m[10] = this._t0.z;
  21968. var scene = this.getScene();
  21969. if (!scene) {
  21970. return this._cachedTextureMatrix;
  21971. }
  21972. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21973. return mat.hasTexture(_this);
  21974. });
  21975. return this._cachedTextureMatrix;
  21976. };
  21977. Texture.prototype.getReflectionTextureMatrix = function () {
  21978. var _this = this;
  21979. var scene = this.getScene();
  21980. if (!scene) {
  21981. return this._cachedTextureMatrix;
  21982. }
  21983. if (this.uOffset === this._cachedUOffset &&
  21984. this.vOffset === this._cachedVOffset &&
  21985. this.uScale === this._cachedUScale &&
  21986. this.vScale === this._cachedVScale &&
  21987. this.coordinatesMode === this._cachedCoordinatesMode) {
  21988. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21989. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21990. return this._cachedTextureMatrix;
  21991. }
  21992. }
  21993. else {
  21994. return this._cachedTextureMatrix;
  21995. }
  21996. }
  21997. if (!this._cachedTextureMatrix) {
  21998. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21999. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22000. }
  22001. this._cachedUOffset = this.uOffset;
  22002. this._cachedVOffset = this.vOffset;
  22003. this._cachedUScale = this.uScale;
  22004. this._cachedVScale = this.vScale;
  22005. this._cachedCoordinatesMode = this.coordinatesMode;
  22006. switch (this.coordinatesMode) {
  22007. case Texture.PLANAR_MODE:
  22008. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22009. this._cachedTextureMatrix[0] = this.uScale;
  22010. this._cachedTextureMatrix[5] = this.vScale;
  22011. this._cachedTextureMatrix[12] = this.uOffset;
  22012. this._cachedTextureMatrix[13] = this.vOffset;
  22013. break;
  22014. case Texture.PROJECTION_MODE:
  22015. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22016. this._projectionModeMatrix.m[0] = 0.5;
  22017. this._projectionModeMatrix.m[5] = -0.5;
  22018. this._projectionModeMatrix.m[10] = 0.0;
  22019. this._projectionModeMatrix.m[12] = 0.5;
  22020. this._projectionModeMatrix.m[13] = 0.5;
  22021. this._projectionModeMatrix.m[14] = 1.0;
  22022. this._projectionModeMatrix.m[15] = 1.0;
  22023. var projectionMatrix = scene.getProjectionMatrix();
  22024. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22025. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22026. break;
  22027. default:
  22028. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22029. break;
  22030. }
  22031. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22032. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22033. });
  22034. return this._cachedTextureMatrix;
  22035. };
  22036. Texture.prototype.clone = function () {
  22037. var _this = this;
  22038. return BABYLON.SerializationHelper.Clone(function () {
  22039. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22040. }, this);
  22041. };
  22042. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22043. get: function () {
  22044. if (!this._onLoadObservable) {
  22045. this._onLoadObservable = new BABYLON.Observable();
  22046. }
  22047. return this._onLoadObservable;
  22048. },
  22049. enumerable: true,
  22050. configurable: true
  22051. });
  22052. Texture.prototype.serialize = function () {
  22053. var serializationObject = _super.prototype.serialize.call(this);
  22054. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22055. serializationObject.base64String = this._buffer;
  22056. serializationObject.name = serializationObject.name.replace("data:", "");
  22057. }
  22058. return serializationObject;
  22059. };
  22060. Texture.prototype.getClassName = function () {
  22061. return "Texture";
  22062. };
  22063. Texture.prototype.dispose = function () {
  22064. _super.prototype.dispose.call(this);
  22065. if (this.onLoadObservable) {
  22066. this.onLoadObservable.clear();
  22067. this._onLoadObservable = null;
  22068. }
  22069. this._delayedOnLoad = null;
  22070. this._delayedOnError = null;
  22071. };
  22072. // Statics
  22073. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22074. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22075. if (onLoad === void 0) { onLoad = null; }
  22076. if (onError === void 0) { onError = null; }
  22077. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22078. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22079. };
  22080. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22081. if (parsedTexture.customType) {
  22082. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22083. // Update Sampling Mode
  22084. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22085. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22086. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22087. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22088. }
  22089. }
  22090. return parsedCustomTexture;
  22091. }
  22092. if (parsedTexture.isCube) {
  22093. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22094. }
  22095. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22096. return null;
  22097. }
  22098. var texture = BABYLON.SerializationHelper.Parse(function () {
  22099. if (parsedTexture.mirrorPlane) {
  22100. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22101. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22102. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22103. return mirrorTexture;
  22104. }
  22105. else if (parsedTexture.isRenderTarget) {
  22106. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22107. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22108. return renderTargetTexture;
  22109. }
  22110. else {
  22111. var texture;
  22112. if (parsedTexture.base64String) {
  22113. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22114. }
  22115. else {
  22116. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22117. }
  22118. return texture;
  22119. }
  22120. }, parsedTexture, scene);
  22121. // Update Sampling Mode
  22122. if (parsedTexture.samplingMode) {
  22123. var sampling = parsedTexture.samplingMode;
  22124. if (texture._samplingMode !== sampling) {
  22125. texture.updateSamplingMode(sampling);
  22126. }
  22127. }
  22128. // Animations
  22129. if (parsedTexture.animations) {
  22130. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22131. var parsedAnimation = parsedTexture.animations[animationIndex];
  22132. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22133. }
  22134. }
  22135. return texture;
  22136. };
  22137. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22138. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22139. if (noMipmap === void 0) { noMipmap = false; }
  22140. if (invertY === void 0) { invertY = true; }
  22141. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22142. if (onLoad === void 0) { onLoad = null; }
  22143. if (onError === void 0) { onError = null; }
  22144. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22145. if (name.substr(0, 5) !== "data:") {
  22146. name = "data:" + name;
  22147. }
  22148. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22149. };
  22150. // Constants
  22151. Texture.NEAREST_SAMPLINGMODE = 1;
  22152. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22153. Texture.BILINEAR_SAMPLINGMODE = 2;
  22154. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22155. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22156. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22157. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22158. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22159. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22160. Texture.NEAREST_LINEAR = 7;
  22161. Texture.NEAREST_NEAREST = 8;
  22162. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22163. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22164. Texture.LINEAR_LINEAR = 11;
  22165. Texture.LINEAR_NEAREST = 12;
  22166. Texture.EXPLICIT_MODE = 0;
  22167. Texture.SPHERICAL_MODE = 1;
  22168. Texture.PLANAR_MODE = 2;
  22169. Texture.CUBIC_MODE = 3;
  22170. Texture.PROJECTION_MODE = 4;
  22171. Texture.SKYBOX_MODE = 5;
  22172. Texture.INVCUBIC_MODE = 6;
  22173. Texture.EQUIRECTANGULAR_MODE = 7;
  22174. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22175. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22176. Texture.CLAMP_ADDRESSMODE = 0;
  22177. Texture.WRAP_ADDRESSMODE = 1;
  22178. Texture.MIRROR_ADDRESSMODE = 2;
  22179. __decorate([
  22180. BABYLON.serialize()
  22181. ], Texture.prototype, "url", void 0);
  22182. __decorate([
  22183. BABYLON.serialize()
  22184. ], Texture.prototype, "uOffset", void 0);
  22185. __decorate([
  22186. BABYLON.serialize()
  22187. ], Texture.prototype, "vOffset", void 0);
  22188. __decorate([
  22189. BABYLON.serialize()
  22190. ], Texture.prototype, "uScale", void 0);
  22191. __decorate([
  22192. BABYLON.serialize()
  22193. ], Texture.prototype, "vScale", void 0);
  22194. __decorate([
  22195. BABYLON.serialize()
  22196. ], Texture.prototype, "uAng", void 0);
  22197. __decorate([
  22198. BABYLON.serialize()
  22199. ], Texture.prototype, "vAng", void 0);
  22200. __decorate([
  22201. BABYLON.serialize()
  22202. ], Texture.prototype, "wAng", void 0);
  22203. __decorate([
  22204. BABYLON.serialize()
  22205. ], Texture.prototype, "isBlocking", null);
  22206. return Texture;
  22207. }(BABYLON.BaseTexture));
  22208. BABYLON.Texture = Texture;
  22209. })(BABYLON || (BABYLON = {}));
  22210. //# sourceMappingURL=babylon.texture.js.map
  22211. var BABYLON;
  22212. (function (BABYLON) {
  22213. var _InstancesBatch = /** @class */ (function () {
  22214. function _InstancesBatch() {
  22215. this.mustReturn = false;
  22216. this.visibleInstances = new Array();
  22217. this.renderSelf = new Array();
  22218. }
  22219. return _InstancesBatch;
  22220. }());
  22221. BABYLON._InstancesBatch = _InstancesBatch;
  22222. var Mesh = /** @class */ (function (_super) {
  22223. __extends(Mesh, _super);
  22224. /**
  22225. * @constructor
  22226. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22227. * @param {Scene} scene The scene to add this mesh to.
  22228. * @param {Node} parent The parent of this mesh, if it has one
  22229. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22230. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22231. * When false, achieved by calling a clone(), also passing False.
  22232. * This will make creation of children, recursive.
  22233. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22234. */
  22235. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22236. if (scene === void 0) { scene = null; }
  22237. if (parent === void 0) { parent = null; }
  22238. if (source === void 0) { source = null; }
  22239. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22240. var _this = _super.call(this, name, scene) || this;
  22241. // Events
  22242. /**
  22243. * An event triggered before rendering the mesh
  22244. * @type {BABYLON.Observable}
  22245. */
  22246. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22247. /**
  22248. * An event triggered after rendering the mesh
  22249. * @type {BABYLON.Observable}
  22250. */
  22251. _this.onAfterRenderObservable = new BABYLON.Observable();
  22252. /**
  22253. * An event triggered before drawing the mesh
  22254. * @type {BABYLON.Observable}
  22255. */
  22256. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22257. // Members
  22258. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22259. _this.instances = new Array();
  22260. _this._LODLevels = new Array();
  22261. _this._visibleInstances = {};
  22262. _this._renderIdForInstances = new Array();
  22263. _this._batchCache = new _InstancesBatch();
  22264. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22265. // Use by builder only to know what orientation were the mesh build in.
  22266. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22267. _this.overrideMaterialSideOrientation = null;
  22268. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22269. // Will be used to save a source mesh reference, If any
  22270. _this._source = null;
  22271. scene = _this.getScene();
  22272. if (source) {
  22273. // Source mesh
  22274. _this._source = source;
  22275. // Geometry
  22276. if (source._geometry) {
  22277. source._geometry.applyToMesh(_this);
  22278. }
  22279. // Deep copy
  22280. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  22281. // Tags
  22282. if (BABYLON.Tags.HasTags(source)) {
  22283. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22284. }
  22285. _this.metadata = source.metadata;
  22286. // Parent
  22287. _this.parent = source.parent;
  22288. // Pivot
  22289. _this.setPivotMatrix(source.getPivotMatrix());
  22290. _this.id = name + "." + source.id;
  22291. // Material
  22292. _this.material = source.material;
  22293. var index;
  22294. if (!doNotCloneChildren) {
  22295. // Children
  22296. for (index = 0; index < scene.meshes.length; index++) {
  22297. var mesh = scene.meshes[index];
  22298. if (mesh.parent === source) {
  22299. // doNotCloneChildren is always going to be False
  22300. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22301. }
  22302. }
  22303. }
  22304. // Physics clone
  22305. var physicsEngine = _this.getScene().getPhysicsEngine();
  22306. if (clonePhysicsImpostor && physicsEngine) {
  22307. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22308. if (impostor) {
  22309. _this.physicsImpostor = impostor.clone(_this);
  22310. }
  22311. }
  22312. // Particles
  22313. for (index = 0; index < scene.particleSystems.length; index++) {
  22314. var system = scene.particleSystems[index];
  22315. if (system.emitter === source) {
  22316. system.clone(system.name, _this);
  22317. }
  22318. }
  22319. _this.computeWorldMatrix(true);
  22320. }
  22321. // Parent
  22322. if (parent !== null) {
  22323. _this.parent = parent;
  22324. }
  22325. return _this;
  22326. }
  22327. Object.defineProperty(Mesh, "FRONTSIDE", {
  22328. /**
  22329. * Mesh side orientation : usually the external or front surface
  22330. */
  22331. get: function () {
  22332. return Mesh._FRONTSIDE;
  22333. },
  22334. enumerable: true,
  22335. configurable: true
  22336. });
  22337. Object.defineProperty(Mesh, "BACKSIDE", {
  22338. /**
  22339. * Mesh side orientation : usually the internal or back surface
  22340. */
  22341. get: function () {
  22342. return Mesh._BACKSIDE;
  22343. },
  22344. enumerable: true,
  22345. configurable: true
  22346. });
  22347. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22348. /**
  22349. * Mesh side orientation : both internal and external or front and back surfaces
  22350. */
  22351. get: function () {
  22352. return Mesh._DOUBLESIDE;
  22353. },
  22354. enumerable: true,
  22355. configurable: true
  22356. });
  22357. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22358. /**
  22359. * Mesh side orientation : by default, `FRONTSIDE`
  22360. */
  22361. get: function () {
  22362. return Mesh._DEFAULTSIDE;
  22363. },
  22364. enumerable: true,
  22365. configurable: true
  22366. });
  22367. Object.defineProperty(Mesh, "NO_CAP", {
  22368. /**
  22369. * Mesh cap setting : no cap
  22370. */
  22371. get: function () {
  22372. return Mesh._NO_CAP;
  22373. },
  22374. enumerable: true,
  22375. configurable: true
  22376. });
  22377. Object.defineProperty(Mesh, "CAP_START", {
  22378. /**
  22379. * Mesh cap setting : one cap at the beginning of the mesh
  22380. */
  22381. get: function () {
  22382. return Mesh._CAP_START;
  22383. },
  22384. enumerable: true,
  22385. configurable: true
  22386. });
  22387. Object.defineProperty(Mesh, "CAP_END", {
  22388. /**
  22389. * Mesh cap setting : one cap at the end of the mesh
  22390. */
  22391. get: function () {
  22392. return Mesh._CAP_END;
  22393. },
  22394. enumerable: true,
  22395. configurable: true
  22396. });
  22397. Object.defineProperty(Mesh, "CAP_ALL", {
  22398. /**
  22399. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22400. */
  22401. get: function () {
  22402. return Mesh._CAP_ALL;
  22403. },
  22404. enumerable: true,
  22405. configurable: true
  22406. });
  22407. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22408. set: function (callback) {
  22409. if (this._onBeforeDrawObserver) {
  22410. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22411. }
  22412. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22413. },
  22414. enumerable: true,
  22415. configurable: true
  22416. });
  22417. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22418. get: function () {
  22419. return this._morphTargetManager;
  22420. },
  22421. set: function (value) {
  22422. if (this._morphTargetManager === value) {
  22423. return;
  22424. }
  22425. this._morphTargetManager = value;
  22426. this._syncGeometryWithMorphTargetManager();
  22427. },
  22428. enumerable: true,
  22429. configurable: true
  22430. });
  22431. Object.defineProperty(Mesh.prototype, "source", {
  22432. get: function () {
  22433. return this._source;
  22434. },
  22435. enumerable: true,
  22436. configurable: true
  22437. });
  22438. // Methods
  22439. /**
  22440. * Returns the string "Mesh".
  22441. */
  22442. Mesh.prototype.getClassName = function () {
  22443. return "Mesh";
  22444. };
  22445. /**
  22446. * Returns a string.
  22447. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22448. */
  22449. Mesh.prototype.toString = function (fullDetails) {
  22450. var ret = _super.prototype.toString.call(this, fullDetails);
  22451. ret += ", n vertices: " + this.getTotalVertices();
  22452. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22453. if (this.animations) {
  22454. for (var i = 0; i < this.animations.length; i++) {
  22455. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22456. }
  22457. }
  22458. if (fullDetails) {
  22459. if (this._geometry) {
  22460. var ib = this.getIndices();
  22461. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22462. if (vb && ib) {
  22463. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  22464. }
  22465. }
  22466. else {
  22467. ret += ", flat shading: UNKNOWN";
  22468. }
  22469. }
  22470. return ret;
  22471. };
  22472. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22473. /**
  22474. * True if the mesh has some Levels Of Details (LOD).
  22475. * Returns a boolean.
  22476. */
  22477. get: function () {
  22478. return this._LODLevels.length > 0;
  22479. },
  22480. enumerable: true,
  22481. configurable: true
  22482. });
  22483. Mesh.prototype._sortLODLevels = function () {
  22484. this._LODLevels.sort(function (a, b) {
  22485. if (a.distance < b.distance) {
  22486. return 1;
  22487. }
  22488. if (a.distance > b.distance) {
  22489. return -1;
  22490. }
  22491. return 0;
  22492. });
  22493. };
  22494. /**
  22495. * Add a mesh as LOD level triggered at the given distance.
  22496. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22497. * @param {number} distance The distance from the center of the object to show this level
  22498. * @param {Mesh} mesh The mesh to be added as LOD level
  22499. * @return {Mesh} This mesh (for chaining)
  22500. */
  22501. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22502. if (mesh && mesh._masterMesh) {
  22503. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22504. return this;
  22505. }
  22506. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22507. this._LODLevels.push(level);
  22508. if (mesh) {
  22509. mesh._masterMesh = this;
  22510. }
  22511. this._sortLODLevels();
  22512. return this;
  22513. };
  22514. /**
  22515. * Returns the LOD level mesh at the passed distance or null if not found.
  22516. * It is related to the method `addLODLevel(distance, mesh)`.
  22517. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22518. * Returns an object Mesh or `null`.
  22519. */
  22520. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22521. for (var index = 0; index < this._LODLevels.length; index++) {
  22522. var level = this._LODLevels[index];
  22523. if (level.distance === distance) {
  22524. return level.mesh;
  22525. }
  22526. }
  22527. return null;
  22528. };
  22529. /**
  22530. * Remove a mesh from the LOD array
  22531. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22532. * @param {Mesh} mesh The mesh to be removed.
  22533. * @return {Mesh} This mesh (for chaining)
  22534. */
  22535. Mesh.prototype.removeLODLevel = function (mesh) {
  22536. for (var index = 0; index < this._LODLevels.length; index++) {
  22537. if (this._LODLevels[index].mesh === mesh) {
  22538. this._LODLevels.splice(index, 1);
  22539. if (mesh) {
  22540. mesh._masterMesh = null;
  22541. }
  22542. }
  22543. }
  22544. this._sortLODLevels();
  22545. return this;
  22546. };
  22547. /**
  22548. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22549. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22550. */
  22551. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22552. if (!this._LODLevels || this._LODLevels.length === 0) {
  22553. return this;
  22554. }
  22555. var bSphere;
  22556. if (boundingSphere) {
  22557. bSphere = boundingSphere;
  22558. }
  22559. else {
  22560. var boundingInfo = this.getBoundingInfo();
  22561. if (!boundingInfo) {
  22562. return this;
  22563. }
  22564. bSphere = boundingInfo.boundingSphere;
  22565. }
  22566. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  22567. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22568. if (this.onLODLevelSelection) {
  22569. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22570. }
  22571. return this;
  22572. }
  22573. for (var index = 0; index < this._LODLevels.length; index++) {
  22574. var level = this._LODLevels[index];
  22575. if (level.distance < distanceToCamera) {
  22576. if (level.mesh) {
  22577. level.mesh._preActivate();
  22578. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22579. }
  22580. if (this.onLODLevelSelection) {
  22581. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22582. }
  22583. return level.mesh;
  22584. }
  22585. }
  22586. if (this.onLODLevelSelection) {
  22587. this.onLODLevelSelection(distanceToCamera, this, this);
  22588. }
  22589. return this;
  22590. };
  22591. Object.defineProperty(Mesh.prototype, "geometry", {
  22592. /**
  22593. * Returns the mesh internal Geometry object.
  22594. */
  22595. get: function () {
  22596. return this._geometry;
  22597. },
  22598. enumerable: true,
  22599. configurable: true
  22600. });
  22601. /**
  22602. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22603. */
  22604. Mesh.prototype.getTotalVertices = function () {
  22605. if (!this._geometry) {
  22606. return 0;
  22607. }
  22608. return this._geometry.getTotalVertices();
  22609. };
  22610. /**
  22611. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22612. * 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.
  22613. * You can force the copy with forceCopy === true
  22614. * Returns null if the mesh has no geometry or no vertex buffer.
  22615. * Possible `kind` values :
  22616. * - BABYLON.VertexBuffer.PositionKind
  22617. * - BABYLON.VertexBuffer.UVKind
  22618. * - BABYLON.VertexBuffer.UV2Kind
  22619. * - BABYLON.VertexBuffer.UV3Kind
  22620. * - BABYLON.VertexBuffer.UV4Kind
  22621. * - BABYLON.VertexBuffer.UV5Kind
  22622. * - BABYLON.VertexBuffer.UV6Kind
  22623. * - BABYLON.VertexBuffer.ColorKind
  22624. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22625. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22626. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22627. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22628. */
  22629. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22630. if (!this._geometry) {
  22631. return null;
  22632. }
  22633. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22634. };
  22635. /**
  22636. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22637. * Returns `null` if the mesh has no geometry.
  22638. * Possible `kind` values :
  22639. * - BABYLON.VertexBuffer.PositionKind
  22640. * - BABYLON.VertexBuffer.UVKind
  22641. * - BABYLON.VertexBuffer.UV2Kind
  22642. * - BABYLON.VertexBuffer.UV3Kind
  22643. * - BABYLON.VertexBuffer.UV4Kind
  22644. * - BABYLON.VertexBuffer.UV5Kind
  22645. * - BABYLON.VertexBuffer.UV6Kind
  22646. * - BABYLON.VertexBuffer.ColorKind
  22647. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22648. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22649. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22650. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22651. */
  22652. Mesh.prototype.getVertexBuffer = function (kind) {
  22653. if (!this._geometry) {
  22654. return null;
  22655. }
  22656. return this._geometry.getVertexBuffer(kind);
  22657. };
  22658. /**
  22659. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22660. * Possible `kind` values :
  22661. * - BABYLON.VertexBuffer.PositionKind
  22662. * - BABYLON.VertexBuffer.UVKind
  22663. * - BABYLON.VertexBuffer.UV2Kind
  22664. * - BABYLON.VertexBuffer.UV3Kind
  22665. * - BABYLON.VertexBuffer.UV4Kind
  22666. * - BABYLON.VertexBuffer.UV5Kind
  22667. * - BABYLON.VertexBuffer.UV6Kind
  22668. * - BABYLON.VertexBuffer.ColorKind
  22669. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22670. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22671. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22672. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22673. */
  22674. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22675. if (!this._geometry) {
  22676. if (this._delayInfo) {
  22677. return this._delayInfo.indexOf(kind) !== -1;
  22678. }
  22679. return false;
  22680. }
  22681. return this._geometry.isVerticesDataPresent(kind);
  22682. };
  22683. /**
  22684. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  22685. * Possible `kind` values :
  22686. * - BABYLON.VertexBuffer.PositionKind
  22687. * - BABYLON.VertexBuffer.UVKind
  22688. * - BABYLON.VertexBuffer.UV2Kind
  22689. * - BABYLON.VertexBuffer.UV3Kind
  22690. * - BABYLON.VertexBuffer.UV4Kind
  22691. * - BABYLON.VertexBuffer.UV5Kind
  22692. * - BABYLON.VertexBuffer.UV6Kind
  22693. * - BABYLON.VertexBuffer.ColorKind
  22694. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22695. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22696. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22697. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22698. */
  22699. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  22700. if (!this._geometry) {
  22701. if (this._delayInfo) {
  22702. return this._delayInfo.indexOf(kind) !== -1;
  22703. }
  22704. return false;
  22705. }
  22706. return this._geometry.isVertexBufferUpdatable(kind);
  22707. };
  22708. /**
  22709. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22710. * Possible `kind` values :
  22711. * - BABYLON.VertexBuffer.PositionKind
  22712. * - BABYLON.VertexBuffer.UVKind
  22713. * - BABYLON.VertexBuffer.UV2Kind
  22714. * - BABYLON.VertexBuffer.UV3Kind
  22715. * - BABYLON.VertexBuffer.UV4Kind
  22716. * - BABYLON.VertexBuffer.UV5Kind
  22717. * - BABYLON.VertexBuffer.UV6Kind
  22718. * - BABYLON.VertexBuffer.ColorKind
  22719. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22720. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22721. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22722. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22723. */
  22724. Mesh.prototype.getVerticesDataKinds = function () {
  22725. if (!this._geometry) {
  22726. var result = new Array();
  22727. if (this._delayInfo) {
  22728. this._delayInfo.forEach(function (kind, index, array) {
  22729. result.push(kind);
  22730. });
  22731. }
  22732. return result;
  22733. }
  22734. return this._geometry.getVerticesDataKinds();
  22735. };
  22736. /**
  22737. * Returns a positive integer : the total number of indices in this mesh geometry.
  22738. * Returns zero if the mesh has no geometry.
  22739. */
  22740. Mesh.prototype.getTotalIndices = function () {
  22741. if (!this._geometry) {
  22742. return 0;
  22743. }
  22744. return this._geometry.getTotalIndices();
  22745. };
  22746. /**
  22747. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22748. * 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.
  22749. * Returns an empty array if the mesh has no geometry.
  22750. */
  22751. Mesh.prototype.getIndices = function (copyWhenShared) {
  22752. if (!this._geometry) {
  22753. return [];
  22754. }
  22755. return this._geometry.getIndices(copyWhenShared);
  22756. };
  22757. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22758. get: function () {
  22759. return this._masterMesh !== null && this._masterMesh !== undefined;
  22760. },
  22761. enumerable: true,
  22762. configurable: true
  22763. });
  22764. /**
  22765. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22766. */
  22767. Mesh.prototype.isReady = function () {
  22768. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22769. return false;
  22770. }
  22771. return _super.prototype.isReady.call(this);
  22772. };
  22773. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22774. /**
  22775. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22776. * This property is pertinent only for updatable parametric shapes.
  22777. */
  22778. get: function () {
  22779. return this._areNormalsFrozen;
  22780. },
  22781. enumerable: true,
  22782. configurable: true
  22783. });
  22784. /**
  22785. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22786. * It has no effect at all on other shapes.
  22787. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22788. * Returns the Mesh.
  22789. */
  22790. Mesh.prototype.freezeNormals = function () {
  22791. this._areNormalsFrozen = true;
  22792. return this;
  22793. };
  22794. /**
  22795. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22796. * It has no effect at all on other shapes.
  22797. * It reactivates the mesh normals computation if it was previously frozen.
  22798. * Returns the Mesh.
  22799. */
  22800. Mesh.prototype.unfreezeNormals = function () {
  22801. this._areNormalsFrozen = false;
  22802. return this;
  22803. };
  22804. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22805. /**
  22806. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22807. */
  22808. set: function (count) {
  22809. this._overridenInstanceCount = count;
  22810. },
  22811. enumerable: true,
  22812. configurable: true
  22813. });
  22814. // Methods
  22815. Mesh.prototype._preActivate = function () {
  22816. var sceneRenderId = this.getScene().getRenderId();
  22817. if (this._preActivateId === sceneRenderId) {
  22818. return this;
  22819. }
  22820. this._preActivateId = sceneRenderId;
  22821. this._visibleInstances = null;
  22822. return this;
  22823. };
  22824. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22825. if (this._visibleInstances) {
  22826. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22827. }
  22828. return this;
  22829. };
  22830. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22831. if (!this._visibleInstances) {
  22832. this._visibleInstances = {};
  22833. this._visibleInstances.defaultRenderId = renderId;
  22834. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22835. }
  22836. if (!this._visibleInstances[renderId]) {
  22837. this._visibleInstances[renderId] = new Array();
  22838. }
  22839. this._visibleInstances[renderId].push(instance);
  22840. return this;
  22841. };
  22842. /**
  22843. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22844. * This means the mesh underlying bounding box and sphere are recomputed.
  22845. * Returns the Mesh.
  22846. */
  22847. Mesh.prototype.refreshBoundingInfo = function () {
  22848. if (this._boundingInfo && this._boundingInfo.isLocked) {
  22849. return this;
  22850. }
  22851. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22852. if (data) {
  22853. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22854. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22855. }
  22856. if (this.subMeshes) {
  22857. for (var index = 0; index < this.subMeshes.length; index++) {
  22858. this.subMeshes[index].refreshBoundingInfo();
  22859. }
  22860. }
  22861. this._updateBoundingInfo();
  22862. return this;
  22863. };
  22864. Mesh.prototype._createGlobalSubMesh = function (force) {
  22865. var totalVertices = this.getTotalVertices();
  22866. if (!totalVertices || !this.getIndices()) {
  22867. return null;
  22868. }
  22869. // Check if we need to recreate the submeshes
  22870. if (this.subMeshes && this.subMeshes.length > 0) {
  22871. var ib = this.getIndices();
  22872. if (!ib) {
  22873. return null;
  22874. }
  22875. var totalIndices = ib.length;
  22876. var needToRecreate = false;
  22877. if (force) {
  22878. needToRecreate = true;
  22879. }
  22880. else {
  22881. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  22882. var submesh = _a[_i];
  22883. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  22884. needToRecreate = true;
  22885. break;
  22886. }
  22887. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  22888. needToRecreate = true;
  22889. break;
  22890. }
  22891. }
  22892. }
  22893. if (!needToRecreate) {
  22894. return this.subMeshes[0];
  22895. }
  22896. }
  22897. this.releaseSubMeshes();
  22898. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22899. };
  22900. Mesh.prototype.subdivide = function (count) {
  22901. if (count < 1) {
  22902. return;
  22903. }
  22904. var totalIndices = this.getTotalIndices();
  22905. var subdivisionSize = (totalIndices / count) | 0;
  22906. var offset = 0;
  22907. // Ensure that subdivisionSize is a multiple of 3
  22908. while (subdivisionSize % 3 !== 0) {
  22909. subdivisionSize++;
  22910. }
  22911. this.releaseSubMeshes();
  22912. for (var index = 0; index < count; index++) {
  22913. if (offset >= totalIndices) {
  22914. break;
  22915. }
  22916. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22917. offset += subdivisionSize;
  22918. }
  22919. this.synchronizeInstances();
  22920. };
  22921. /**
  22922. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22923. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22924. * The `data` are either a numeric array either a Float32Array.
  22925. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22926. * 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).
  22927. * Note that a new underlying VertexBuffer object is created each call.
  22928. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22929. *
  22930. * Possible `kind` values :
  22931. * - BABYLON.VertexBuffer.PositionKind
  22932. * - BABYLON.VertexBuffer.UVKind
  22933. * - BABYLON.VertexBuffer.UV2Kind
  22934. * - BABYLON.VertexBuffer.UV3Kind
  22935. * - BABYLON.VertexBuffer.UV4Kind
  22936. * - BABYLON.VertexBuffer.UV5Kind
  22937. * - BABYLON.VertexBuffer.UV6Kind
  22938. * - BABYLON.VertexBuffer.ColorKind
  22939. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22940. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22941. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22942. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22943. *
  22944. * Returns the Mesh.
  22945. */
  22946. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22947. if (updatable === void 0) { updatable = false; }
  22948. if (!this._geometry) {
  22949. var vertexData = new BABYLON.VertexData();
  22950. vertexData.set(data, kind);
  22951. var scene = this.getScene();
  22952. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22953. }
  22954. else {
  22955. this._geometry.setVerticesData(kind, data, updatable, stride);
  22956. }
  22957. return this;
  22958. };
  22959. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  22960. if (updatable === void 0) { updatable = true; }
  22961. var vb = this.getVertexBuffer(kind);
  22962. if (!vb || vb.isUpdatable() === updatable) {
  22963. return;
  22964. }
  22965. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  22966. };
  22967. /**
  22968. * Sets the mesh VertexBuffer.
  22969. * Returns the Mesh.
  22970. */
  22971. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22972. if (!this._geometry) {
  22973. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  22974. }
  22975. this._geometry.setVerticesBuffer(buffer);
  22976. return this;
  22977. };
  22978. /**
  22979. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22980. * If the mesh has no geometry, it is simply returned as it is.
  22981. * The `data` are either a numeric array either a Float32Array.
  22982. * No new underlying VertexBuffer object is created.
  22983. * 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.
  22984. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22985. *
  22986. * Possible `kind` values :
  22987. * - BABYLON.VertexBuffer.PositionKind
  22988. * - BABYLON.VertexBuffer.UVKind
  22989. * - BABYLON.VertexBuffer.UV2Kind
  22990. * - BABYLON.VertexBuffer.UV3Kind
  22991. * - BABYLON.VertexBuffer.UV4Kind
  22992. * - BABYLON.VertexBuffer.UV5Kind
  22993. * - BABYLON.VertexBuffer.UV6Kind
  22994. * - BABYLON.VertexBuffer.ColorKind
  22995. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22996. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22997. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22998. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22999. *
  23000. * Returns the Mesh.
  23001. */
  23002. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23003. if (!this._geometry) {
  23004. return this;
  23005. }
  23006. if (!makeItUnique) {
  23007. this._geometry.updateVerticesData(kind, data, updateExtends);
  23008. }
  23009. else {
  23010. this.makeGeometryUnique();
  23011. this.updateVerticesData(kind, data, updateExtends, false);
  23012. }
  23013. return this;
  23014. };
  23015. /**
  23016. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23017. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23018. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23019. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23020. * Returns the Mesh.
  23021. */
  23022. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23023. if (computeNormals === void 0) { computeNormals = true; }
  23024. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23025. if (!positions) {
  23026. return this;
  23027. }
  23028. positionFunction(positions);
  23029. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23030. if (computeNormals) {
  23031. var indices = this.getIndices();
  23032. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23033. if (!normals) {
  23034. return this;
  23035. }
  23036. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23037. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23038. }
  23039. return this;
  23040. };
  23041. /**
  23042. * Creates a un-shared specific occurence of the geometry for the mesh.
  23043. * Returns the Mesh.
  23044. */
  23045. Mesh.prototype.makeGeometryUnique = function () {
  23046. if (!this._geometry) {
  23047. return this;
  23048. }
  23049. var oldGeometry = this._geometry;
  23050. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23051. oldGeometry.releaseForMesh(this, true);
  23052. geometry.applyToMesh(this);
  23053. return this;
  23054. };
  23055. /**
  23056. * Sets the mesh indices.
  23057. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23058. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23059. * This method creates a new index buffer each call.
  23060. * Returns the Mesh.
  23061. */
  23062. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23063. if (totalVertices === void 0) { totalVertices = null; }
  23064. if (updatable === void 0) { updatable = false; }
  23065. if (!this._geometry) {
  23066. var vertexData = new BABYLON.VertexData();
  23067. vertexData.indices = indices;
  23068. var scene = this.getScene();
  23069. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23070. }
  23071. else {
  23072. this._geometry.setIndices(indices, totalVertices, updatable);
  23073. }
  23074. return this;
  23075. };
  23076. /**
  23077. * Update the current index buffer
  23078. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23079. * Returns the Mesh.
  23080. */
  23081. Mesh.prototype.updateIndices = function (indices, offset) {
  23082. if (!this._geometry) {
  23083. return this;
  23084. }
  23085. this._geometry.updateIndices(indices, offset);
  23086. return this;
  23087. };
  23088. /**
  23089. * Invert the geometry to move from a right handed system to a left handed one.
  23090. * Returns the Mesh.
  23091. */
  23092. Mesh.prototype.toLeftHanded = function () {
  23093. if (!this._geometry) {
  23094. return this;
  23095. }
  23096. this._geometry.toLeftHanded();
  23097. return this;
  23098. };
  23099. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23100. if (!this._geometry) {
  23101. return this;
  23102. }
  23103. var engine = this.getScene().getEngine();
  23104. // Wireframe
  23105. var indexToBind;
  23106. if (this._unIndexed) {
  23107. indexToBind = null;
  23108. }
  23109. else {
  23110. switch (fillMode) {
  23111. case BABYLON.Material.PointFillMode:
  23112. indexToBind = null;
  23113. break;
  23114. case BABYLON.Material.WireFrameFillMode:
  23115. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23116. break;
  23117. default:
  23118. case BABYLON.Material.TriangleFillMode:
  23119. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23120. break;
  23121. }
  23122. }
  23123. // VBOs
  23124. this._geometry._bind(effect, indexToBind);
  23125. return this;
  23126. };
  23127. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23128. if (alternate === void 0) { alternate = false; }
  23129. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23130. return this;
  23131. }
  23132. this.onBeforeDrawObservable.notifyObservers(this);
  23133. var scene = this.getScene();
  23134. var engine = scene.getEngine();
  23135. // Draw order
  23136. switch (fillMode) {
  23137. case BABYLON.Material.PointFillMode:
  23138. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23139. break;
  23140. case BABYLON.Material.WireFrameFillMode:
  23141. if (this._unIndexed) {
  23142. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23143. }
  23144. else {
  23145. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23146. }
  23147. break;
  23148. default:
  23149. if (this._unIndexed) {
  23150. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23151. }
  23152. else {
  23153. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23154. }
  23155. }
  23156. if (scene._isAlternateRenderingEnabled && !alternate) {
  23157. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23158. if (!effect || !scene.activeCamera) {
  23159. return this;
  23160. }
  23161. scene._switchToAlternateCameraConfiguration(true);
  23162. this._effectiveMaterial.bindView(effect);
  23163. this._effectiveMaterial.bindViewProjection(effect);
  23164. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23165. this._draw(subMesh, fillMode, instancesCount, true);
  23166. engine.setViewport(scene.activeCamera.viewport);
  23167. scene._switchToAlternateCameraConfiguration(false);
  23168. this._effectiveMaterial.bindView(effect);
  23169. this._effectiveMaterial.bindViewProjection(effect);
  23170. }
  23171. return this;
  23172. };
  23173. /**
  23174. * Registers for this mesh a javascript function called just before the rendering process.
  23175. * This function is passed the current mesh.
  23176. * Return the Mesh.
  23177. */
  23178. Mesh.prototype.registerBeforeRender = function (func) {
  23179. this.onBeforeRenderObservable.add(func);
  23180. return this;
  23181. };
  23182. /**
  23183. * Disposes a previously registered javascript function called before the rendering.
  23184. * This function is passed the current mesh.
  23185. * Returns the Mesh.
  23186. */
  23187. Mesh.prototype.unregisterBeforeRender = function (func) {
  23188. this.onBeforeRenderObservable.removeCallback(func);
  23189. return this;
  23190. };
  23191. /**
  23192. * Registers for this mesh a javascript function called just after the rendering is complete.
  23193. * This function is passed the current mesh.
  23194. * Returns the Mesh.
  23195. */
  23196. Mesh.prototype.registerAfterRender = function (func) {
  23197. this.onAfterRenderObservable.add(func);
  23198. return this;
  23199. };
  23200. /**
  23201. * Disposes a previously registered javascript function called after the rendering.
  23202. * This function is passed the current mesh.
  23203. * Return the Mesh.
  23204. */
  23205. Mesh.prototype.unregisterAfterRender = function (func) {
  23206. this.onAfterRenderObservable.removeCallback(func);
  23207. return this;
  23208. };
  23209. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23210. var scene = this.getScene();
  23211. this._batchCache.mustReturn = false;
  23212. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23213. this._batchCache.visibleInstances[subMeshId] = null;
  23214. if (this._visibleInstances) {
  23215. var currentRenderId = scene.getRenderId();
  23216. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23217. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23218. var selfRenderId = this._renderId;
  23219. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23220. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23221. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23222. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23223. }
  23224. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23225. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23226. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23227. this._batchCache.mustReturn = true;
  23228. return this._batchCache;
  23229. }
  23230. if (currentRenderId !== selfRenderId) {
  23231. this._batchCache.renderSelf[subMeshId] = false;
  23232. }
  23233. }
  23234. this._renderIdForInstances[subMeshId] = currentRenderId;
  23235. }
  23236. return this._batchCache;
  23237. };
  23238. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23239. var visibleInstances = batch.visibleInstances[subMesh._id];
  23240. if (!visibleInstances) {
  23241. return this;
  23242. }
  23243. var matricesCount = visibleInstances.length + 1;
  23244. var bufferSize = matricesCount * 16 * 4;
  23245. var currentInstancesBufferSize = this._instancesBufferSize;
  23246. var instancesBuffer = this._instancesBuffer;
  23247. while (this._instancesBufferSize < bufferSize) {
  23248. this._instancesBufferSize *= 2;
  23249. }
  23250. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23251. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23252. }
  23253. var offset = 0;
  23254. var instancesCount = 0;
  23255. var world = this.getWorldMatrix();
  23256. if (batch.renderSelf[subMesh._id]) {
  23257. world.copyToArray(this._instancesData, offset);
  23258. offset += 16;
  23259. instancesCount++;
  23260. }
  23261. if (visibleInstances) {
  23262. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23263. var instance = visibleInstances[instanceIndex];
  23264. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23265. offset += 16;
  23266. instancesCount++;
  23267. }
  23268. }
  23269. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23270. if (instancesBuffer) {
  23271. instancesBuffer.dispose();
  23272. }
  23273. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23274. this._instancesBuffer = instancesBuffer;
  23275. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23276. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23277. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23278. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23279. }
  23280. else {
  23281. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23282. }
  23283. this._bind(subMesh, effect, fillMode);
  23284. this._draw(subMesh, fillMode, instancesCount);
  23285. engine.unbindInstanceAttributes();
  23286. return this;
  23287. };
  23288. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23289. var scene = this.getScene();
  23290. var engine = scene.getEngine();
  23291. if (hardwareInstancedRendering) {
  23292. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23293. }
  23294. else {
  23295. if (batch.renderSelf[subMesh._id]) {
  23296. // Draw
  23297. if (onBeforeDraw) {
  23298. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23299. }
  23300. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23301. }
  23302. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23303. if (visibleInstancesForSubMesh) {
  23304. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23305. var instance = visibleInstancesForSubMesh[instanceIndex];
  23306. // World
  23307. var world = instance.getWorldMatrix();
  23308. if (onBeforeDraw) {
  23309. onBeforeDraw(true, world, effectiveMaterial);
  23310. }
  23311. // Draw
  23312. this._draw(subMesh, fillMode);
  23313. }
  23314. }
  23315. }
  23316. return this;
  23317. };
  23318. /**
  23319. * Triggers the draw call for the mesh.
  23320. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23321. * Returns the Mesh.
  23322. */
  23323. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23324. this.checkOcclusionQuery();
  23325. if (this._isOccluded) {
  23326. return this;
  23327. }
  23328. var scene = this.getScene();
  23329. // Managing instances
  23330. var batch = this._getInstancesRenderList(subMesh._id);
  23331. if (batch.mustReturn) {
  23332. return this;
  23333. }
  23334. // Checking geometry state
  23335. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23336. return this;
  23337. }
  23338. this.onBeforeRenderObservable.notifyObservers(this);
  23339. var engine = scene.getEngine();
  23340. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23341. // Material
  23342. var material = subMesh.getMaterial();
  23343. if (!material) {
  23344. return this;
  23345. }
  23346. this._effectiveMaterial = material;
  23347. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23348. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23349. return this;
  23350. }
  23351. }
  23352. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23353. return this;
  23354. }
  23355. // Alpha mode
  23356. if (enableAlphaMode) {
  23357. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23358. }
  23359. // Outline - step 1
  23360. var savedDepthWrite = engine.getDepthWrite();
  23361. if (this.renderOutline) {
  23362. engine.setDepthWrite(false);
  23363. scene.getOutlineRenderer().render(subMesh, batch);
  23364. engine.setDepthWrite(savedDepthWrite);
  23365. }
  23366. var effect;
  23367. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23368. effect = subMesh.effect;
  23369. }
  23370. else {
  23371. effect = this._effectiveMaterial.getEffect();
  23372. }
  23373. if (!effect) {
  23374. return this;
  23375. }
  23376. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23377. if (this._effectiveMaterial.forceDepthWrite) {
  23378. engine.setDepthWrite(true);
  23379. }
  23380. // Bind
  23381. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  23382. if (!hardwareInstancedRendering) {
  23383. this._bind(subMesh, effect, fillMode);
  23384. }
  23385. var world = this.getWorldMatrix();
  23386. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23387. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  23388. }
  23389. else {
  23390. this._effectiveMaterial.bind(world, this);
  23391. }
  23392. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  23393. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  23394. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23395. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  23396. }
  23397. // Draw
  23398. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23399. // Unbind
  23400. this._effectiveMaterial.unbind();
  23401. // Outline - step 2
  23402. if (this.renderOutline && savedDepthWrite) {
  23403. engine.setDepthWrite(true);
  23404. engine.setColorWrite(false);
  23405. scene.getOutlineRenderer().render(subMesh, batch);
  23406. engine.setColorWrite(true);
  23407. }
  23408. // Overlay
  23409. if (this.renderOverlay) {
  23410. var currentMode = engine.getAlphaMode();
  23411. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23412. scene.getOutlineRenderer().render(subMesh, batch, true);
  23413. engine.setAlphaMode(currentMode);
  23414. }
  23415. this.onAfterRenderObservable.notifyObservers(this);
  23416. return this;
  23417. };
  23418. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23419. if (isInstance) {
  23420. effectiveMaterial.bindOnlyWorldMatrix(world);
  23421. }
  23422. return this;
  23423. };
  23424. /**
  23425. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23426. */
  23427. Mesh.prototype.getEmittedParticleSystems = function () {
  23428. var results = new Array();
  23429. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23430. var particleSystem = this.getScene().particleSystems[index];
  23431. if (particleSystem.emitter === this) {
  23432. results.push(particleSystem);
  23433. }
  23434. }
  23435. return results;
  23436. };
  23437. /**
  23438. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23439. */
  23440. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23441. var results = new Array();
  23442. var descendants = this.getDescendants();
  23443. descendants.push(this);
  23444. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23445. var particleSystem = this.getScene().particleSystems[index];
  23446. var emitter = particleSystem.emitter;
  23447. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23448. results.push(particleSystem);
  23449. }
  23450. }
  23451. return results;
  23452. };
  23453. Mesh.prototype._checkDelayState = function () {
  23454. var scene = this.getScene();
  23455. if (this._geometry) {
  23456. this._geometry.load(scene);
  23457. }
  23458. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23459. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23460. this._queueLoad(this, scene);
  23461. }
  23462. return this;
  23463. };
  23464. Mesh.prototype._queueLoad = function (mesh, scene) {
  23465. var _this = this;
  23466. scene._addPendingData(mesh);
  23467. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23468. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23469. if (data instanceof ArrayBuffer) {
  23470. _this._delayLoadingFunction(data, _this);
  23471. }
  23472. else {
  23473. _this._delayLoadingFunction(JSON.parse(data), _this);
  23474. }
  23475. _this.instances.forEach(function (instance) {
  23476. instance._syncSubMeshes();
  23477. });
  23478. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23479. scene._removePendingData(_this);
  23480. }, function () { }, scene.database, getBinaryData);
  23481. return this;
  23482. };
  23483. /**
  23484. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23485. */
  23486. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23487. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23488. return false;
  23489. }
  23490. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23491. return false;
  23492. }
  23493. this._checkDelayState();
  23494. return true;
  23495. };
  23496. /**
  23497. * Sets the mesh material by the material or multiMaterial `id` property.
  23498. * The material `id` is a string identifying the material or the multiMaterial.
  23499. * This method returns the Mesh.
  23500. */
  23501. Mesh.prototype.setMaterialByID = function (id) {
  23502. var materials = this.getScene().materials;
  23503. var index;
  23504. for (index = materials.length - 1; index > -1; index--) {
  23505. if (materials[index].id === id) {
  23506. this.material = materials[index];
  23507. return this;
  23508. }
  23509. }
  23510. // Multi
  23511. var multiMaterials = this.getScene().multiMaterials;
  23512. for (index = multiMaterials.length - 1; index > -1; index--) {
  23513. if (multiMaterials[index].id === id) {
  23514. this.material = multiMaterials[index];
  23515. return this;
  23516. }
  23517. }
  23518. return this;
  23519. };
  23520. /**
  23521. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23522. */
  23523. Mesh.prototype.getAnimatables = function () {
  23524. var results = new Array();
  23525. if (this.material) {
  23526. results.push(this.material);
  23527. }
  23528. if (this.skeleton) {
  23529. results.push(this.skeleton);
  23530. }
  23531. return results;
  23532. };
  23533. /**
  23534. * Modifies the mesh geometry according to the passed transformation matrix.
  23535. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23536. * The mesh normals are modified accordingly the same transformation.
  23537. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23538. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23539. * Returns the Mesh.
  23540. */
  23541. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23542. // Position
  23543. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23544. return this;
  23545. }
  23546. var submeshes = this.subMeshes.splice(0);
  23547. this._resetPointsArrayCache();
  23548. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23549. var temp = new Array();
  23550. var index;
  23551. for (index = 0; index < data.length; index += 3) {
  23552. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23553. }
  23554. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23555. // Normals
  23556. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23557. return this;
  23558. }
  23559. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23560. temp = [];
  23561. for (index = 0; index < data.length; index += 3) {
  23562. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23563. }
  23564. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23565. // flip faces?
  23566. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23567. this.flipFaces();
  23568. }
  23569. // Restore submeshes
  23570. this.releaseSubMeshes();
  23571. this.subMeshes = submeshes;
  23572. return this;
  23573. };
  23574. /**
  23575. * Modifies the mesh geometry according to its own current World Matrix.
  23576. * The mesh World Matrix is then reset.
  23577. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23578. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23579. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23580. * Returns the Mesh.
  23581. */
  23582. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23583. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23584. this.scaling.copyFromFloats(1, 1, 1);
  23585. this.position.copyFromFloats(0, 0, 0);
  23586. this.rotation.copyFromFloats(0, 0, 0);
  23587. //only if quaternion is already set
  23588. if (this.rotationQuaternion) {
  23589. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23590. }
  23591. this._worldMatrix = BABYLON.Matrix.Identity();
  23592. return this;
  23593. };
  23594. Object.defineProperty(Mesh.prototype, "_positions", {
  23595. // Cache
  23596. get: function () {
  23597. if (this._geometry) {
  23598. return this._geometry._positions;
  23599. }
  23600. return null;
  23601. },
  23602. enumerable: true,
  23603. configurable: true
  23604. });
  23605. Mesh.prototype._resetPointsArrayCache = function () {
  23606. if (this._geometry) {
  23607. this._geometry._resetPointsArrayCache();
  23608. }
  23609. return this;
  23610. };
  23611. Mesh.prototype._generatePointsArray = function () {
  23612. if (this._geometry) {
  23613. return this._geometry._generatePointsArray();
  23614. }
  23615. return false;
  23616. };
  23617. /**
  23618. * Returns a new Mesh object generated from the current mesh properties.
  23619. * This method must not get confused with createInstance().
  23620. * The parameter `name` is a string, the name given to the new mesh.
  23621. * The optional parameter `newParent` can be any Node object (default `null`).
  23622. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23623. * 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.
  23624. */
  23625. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23626. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23627. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23628. };
  23629. /**
  23630. * Disposes the mesh.
  23631. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23632. */
  23633. Mesh.prototype.dispose = function (doNotRecurse) {
  23634. var _this = this;
  23635. this.morphTargetManager = null;
  23636. if (this._geometry) {
  23637. this._geometry.releaseForMesh(this, true);
  23638. }
  23639. // Sources
  23640. var meshes = this.getScene().meshes;
  23641. meshes.forEach(function (mesh) {
  23642. if (mesh._source && mesh._source === _this) {
  23643. mesh._source = null;
  23644. }
  23645. });
  23646. this._source = null;
  23647. // Instances
  23648. if (this._instancesBuffer) {
  23649. this._instancesBuffer.dispose();
  23650. this._instancesBuffer = null;
  23651. }
  23652. while (this.instances.length) {
  23653. this.instances[0].dispose();
  23654. }
  23655. // Highlight layers.
  23656. var highlightLayers = this.getScene().highlightLayers;
  23657. for (var i = 0; i < highlightLayers.length; i++) {
  23658. var highlightLayer = highlightLayers[i];
  23659. if (highlightLayer) {
  23660. highlightLayer.removeMesh(this);
  23661. highlightLayer.removeExcludedMesh(this);
  23662. }
  23663. }
  23664. _super.prototype.dispose.call(this, doNotRecurse);
  23665. };
  23666. /**
  23667. * Modifies the mesh geometry according to a displacement map.
  23668. * 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.
  23669. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23670. * This method returns nothing.
  23671. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23672. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23673. * 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.
  23674. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23675. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23676. *
  23677. * Returns the Mesh.
  23678. */
  23679. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23680. var _this = this;
  23681. var scene = this.getScene();
  23682. var onload = function (img) {
  23683. // Getting height map data
  23684. var canvas = document.createElement("canvas");
  23685. var context = canvas.getContext("2d");
  23686. var heightMapWidth = img.width;
  23687. var heightMapHeight = img.height;
  23688. canvas.width = heightMapWidth;
  23689. canvas.height = heightMapHeight;
  23690. context.drawImage(img, 0, 0);
  23691. // Create VertexData from map data
  23692. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23693. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23694. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23695. //execute success callback, if set
  23696. if (onSuccess) {
  23697. onSuccess(_this);
  23698. }
  23699. };
  23700. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23701. return this;
  23702. };
  23703. /**
  23704. * Modifies the mesh geometry according to a displacementMap buffer.
  23705. * 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.
  23706. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23707. * This method returns nothing.
  23708. * 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.
  23709. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23710. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23711. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23712. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23713. *
  23714. * Returns the Mesh.
  23715. */
  23716. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23717. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23718. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23719. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23720. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23721. return this;
  23722. }
  23723. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23724. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23725. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23726. var position = BABYLON.Vector3.Zero();
  23727. var normal = BABYLON.Vector3.Zero();
  23728. var uv = BABYLON.Vector2.Zero();
  23729. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23730. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23731. for (var index = 0; index < positions.length; index += 3) {
  23732. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23733. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23734. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23735. // Compute height
  23736. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23737. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23738. var pos = (u + v * heightMapWidth) * 4;
  23739. var r = buffer[pos] / 255.0;
  23740. var g = buffer[pos + 1] / 255.0;
  23741. var b = buffer[pos + 2] / 255.0;
  23742. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23743. normal.normalize();
  23744. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23745. position = position.add(normal);
  23746. position.toArray(positions, index);
  23747. }
  23748. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23749. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23750. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23751. return this;
  23752. };
  23753. /**
  23754. * Modify the mesh to get a flat shading rendering.
  23755. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23756. * This method returns the Mesh.
  23757. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23758. */
  23759. Mesh.prototype.convertToFlatShadedMesh = function () {
  23760. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23761. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23762. var kinds = this.getVerticesDataKinds();
  23763. var vbs = {};
  23764. var data = {};
  23765. var newdata = {};
  23766. var updatableNormals = false;
  23767. var kindIndex;
  23768. var kind;
  23769. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23770. kind = kinds[kindIndex];
  23771. var vertexBuffer = this.getVertexBuffer(kind);
  23772. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23773. updatableNormals = vertexBuffer.isUpdatable();
  23774. kinds.splice(kindIndex, 1);
  23775. kindIndex--;
  23776. continue;
  23777. }
  23778. vbs[kind] = vertexBuffer;
  23779. data[kind] = vbs[kind].getData();
  23780. newdata[kind] = [];
  23781. }
  23782. // Save previous submeshes
  23783. var previousSubmeshes = this.subMeshes.slice(0);
  23784. var indices = this.getIndices();
  23785. var totalIndices = this.getTotalIndices();
  23786. // Generating unique vertices per face
  23787. var index;
  23788. for (index = 0; index < totalIndices; index++) {
  23789. var vertexIndex = indices[index];
  23790. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23791. kind = kinds[kindIndex];
  23792. var stride = vbs[kind].getStrideSize();
  23793. for (var offset = 0; offset < stride; offset++) {
  23794. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23795. }
  23796. }
  23797. }
  23798. // Updating faces & normal
  23799. var normals = [];
  23800. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23801. for (index = 0; index < totalIndices; index += 3) {
  23802. indices[index] = index;
  23803. indices[index + 1] = index + 1;
  23804. indices[index + 2] = index + 2;
  23805. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23806. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23807. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23808. var p1p2 = p1.subtract(p2);
  23809. var p3p2 = p3.subtract(p2);
  23810. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23811. // Store same normals for every vertex
  23812. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23813. normals.push(normal.x);
  23814. normals.push(normal.y);
  23815. normals.push(normal.z);
  23816. }
  23817. }
  23818. this.setIndices(indices);
  23819. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23820. // Updating vertex buffers
  23821. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23822. kind = kinds[kindIndex];
  23823. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23824. }
  23825. // Updating submeshes
  23826. this.releaseSubMeshes();
  23827. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23828. var previousOne = previousSubmeshes[submeshIndex];
  23829. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23830. }
  23831. this.synchronizeInstances();
  23832. return this;
  23833. };
  23834. /**
  23835. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23836. * In other words, more vertices, no more indices and a single bigger VBO.
  23837. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23838. * Returns the Mesh.
  23839. */
  23840. Mesh.prototype.convertToUnIndexedMesh = function () {
  23841. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23842. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23843. var kinds = this.getVerticesDataKinds();
  23844. var vbs = {};
  23845. var data = {};
  23846. var newdata = {};
  23847. var kindIndex;
  23848. var kind;
  23849. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23850. kind = kinds[kindIndex];
  23851. var vertexBuffer = this.getVertexBuffer(kind);
  23852. vbs[kind] = vertexBuffer;
  23853. data[kind] = vbs[kind].getData();
  23854. newdata[kind] = [];
  23855. }
  23856. // Save previous submeshes
  23857. var previousSubmeshes = this.subMeshes.slice(0);
  23858. var indices = this.getIndices();
  23859. var totalIndices = this.getTotalIndices();
  23860. // Generating unique vertices per face
  23861. var index;
  23862. for (index = 0; index < totalIndices; index++) {
  23863. var vertexIndex = indices[index];
  23864. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23865. kind = kinds[kindIndex];
  23866. var stride = vbs[kind].getStrideSize();
  23867. for (var offset = 0; offset < stride; offset++) {
  23868. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23869. }
  23870. }
  23871. }
  23872. // Updating indices
  23873. for (index = 0; index < totalIndices; index += 3) {
  23874. indices[index] = index;
  23875. indices[index + 1] = index + 1;
  23876. indices[index + 2] = index + 2;
  23877. }
  23878. this.setIndices(indices);
  23879. // Updating vertex buffers
  23880. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23881. kind = kinds[kindIndex];
  23882. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23883. }
  23884. // Updating submeshes
  23885. this.releaseSubMeshes();
  23886. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23887. var previousOne = previousSubmeshes[submeshIndex];
  23888. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23889. }
  23890. this._unIndexed = true;
  23891. this.synchronizeInstances();
  23892. return this;
  23893. };
  23894. /**
  23895. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23896. * This method returns the Mesh.
  23897. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23898. */
  23899. Mesh.prototype.flipFaces = function (flipNormals) {
  23900. if (flipNormals === void 0) { flipNormals = false; }
  23901. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23902. var i;
  23903. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  23904. for (i = 0; i < vertex_data.normals.length; i++) {
  23905. vertex_data.normals[i] *= -1;
  23906. }
  23907. }
  23908. if (vertex_data.indices) {
  23909. var temp;
  23910. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23911. // reassign indices
  23912. temp = vertex_data.indices[i + 1];
  23913. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23914. vertex_data.indices[i + 2] = temp;
  23915. }
  23916. }
  23917. vertex_data.applyToMesh(this);
  23918. return this;
  23919. };
  23920. // Instances
  23921. /**
  23922. * Creates a new InstancedMesh object from the mesh model.
  23923. * An instance shares the same properties and the same material than its model.
  23924. * Only these properties of each instance can then be set individually :
  23925. * - position
  23926. * - rotation
  23927. * - rotationQuaternion
  23928. * - setPivotMatrix
  23929. * - scaling
  23930. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23931. * Warning : this method is not supported for Line mesh and LineSystem
  23932. */
  23933. Mesh.prototype.createInstance = function (name) {
  23934. return new BABYLON.InstancedMesh(name, this);
  23935. };
  23936. /**
  23937. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  23938. * After this call, all the mesh instances have the same submeshes than the current mesh.
  23939. * This method returns the Mesh.
  23940. */
  23941. Mesh.prototype.synchronizeInstances = function () {
  23942. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  23943. var instance = this.instances[instanceIndex];
  23944. instance._syncSubMeshes();
  23945. }
  23946. return this;
  23947. };
  23948. /**
  23949. * Simplify the mesh according to the given array of settings.
  23950. * Function will return immediately and will simplify async. It returns the Mesh.
  23951. * @param settings a collection of simplification settings.
  23952. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23953. * @param type the type of simplification to run.
  23954. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23955. */
  23956. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23957. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23958. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23959. this.getScene().simplificationQueue.addTask({
  23960. settings: settings,
  23961. parallelProcessing: parallelProcessing,
  23962. mesh: this,
  23963. simplificationType: simplificationType,
  23964. successCallback: successCallback
  23965. });
  23966. return this;
  23967. };
  23968. /**
  23969. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23970. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23971. * This should be used together with the simplification to avoid disappearing triangles.
  23972. * Returns the Mesh.
  23973. * @param successCallback an optional success callback to be called after the optimization finished.
  23974. */
  23975. Mesh.prototype.optimizeIndices = function (successCallback) {
  23976. var _this = this;
  23977. var indices = this.getIndices();
  23978. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23979. if (!positions || !indices) {
  23980. return this;
  23981. }
  23982. var vectorPositions = new Array();
  23983. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23984. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23985. }
  23986. var dupes = new Array();
  23987. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23988. var realPos = vectorPositions.length - 1 - iteration;
  23989. var testedPosition = vectorPositions[realPos];
  23990. for (var j = 0; j < realPos; ++j) {
  23991. var againstPosition = vectorPositions[j];
  23992. if (testedPosition.equals(againstPosition)) {
  23993. dupes[realPos] = j;
  23994. break;
  23995. }
  23996. }
  23997. }, function () {
  23998. for (var i = 0; i < indices.length; ++i) {
  23999. indices[i] = dupes[indices[i]] || indices[i];
  24000. }
  24001. //indices are now reordered
  24002. var originalSubMeshes = _this.subMeshes.slice(0);
  24003. _this.setIndices(indices);
  24004. _this.subMeshes = originalSubMeshes;
  24005. if (successCallback) {
  24006. successCallback(_this);
  24007. }
  24008. });
  24009. return this;
  24010. };
  24011. Mesh.prototype.serialize = function (serializationObject) {
  24012. serializationObject.name = this.name;
  24013. serializationObject.id = this.id;
  24014. serializationObject.type = this.getClassName();
  24015. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24016. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24017. }
  24018. serializationObject.position = this.position.asArray();
  24019. if (this.rotationQuaternion) {
  24020. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24021. }
  24022. else if (this.rotation) {
  24023. serializationObject.rotation = this.rotation.asArray();
  24024. }
  24025. serializationObject.scaling = this.scaling.asArray();
  24026. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24027. serializationObject.isEnabled = this.isEnabled();
  24028. serializationObject.isVisible = this.isVisible;
  24029. serializationObject.infiniteDistance = this.infiniteDistance;
  24030. serializationObject.pickable = this.isPickable;
  24031. serializationObject.receiveShadows = this.receiveShadows;
  24032. serializationObject.billboardMode = this.billboardMode;
  24033. serializationObject.visibility = this.visibility;
  24034. serializationObject.checkCollisions = this.checkCollisions;
  24035. serializationObject.isBlocker = this.isBlocker;
  24036. // Parent
  24037. if (this.parent) {
  24038. serializationObject.parentId = this.parent.id;
  24039. }
  24040. // Geometry
  24041. var geometry = this._geometry;
  24042. if (geometry) {
  24043. var geometryId = geometry.id;
  24044. serializationObject.geometryId = geometryId;
  24045. // SubMeshes
  24046. serializationObject.subMeshes = [];
  24047. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24048. var subMesh = this.subMeshes[subIndex];
  24049. serializationObject.subMeshes.push({
  24050. materialIndex: subMesh.materialIndex,
  24051. verticesStart: subMesh.verticesStart,
  24052. verticesCount: subMesh.verticesCount,
  24053. indexStart: subMesh.indexStart,
  24054. indexCount: subMesh.indexCount
  24055. });
  24056. }
  24057. }
  24058. // Material
  24059. if (this.material) {
  24060. serializationObject.materialId = this.material.id;
  24061. }
  24062. else {
  24063. this.material = null;
  24064. }
  24065. // Morph targets
  24066. if (this.morphTargetManager) {
  24067. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24068. }
  24069. // Skeleton
  24070. if (this.skeleton) {
  24071. serializationObject.skeletonId = this.skeleton.id;
  24072. }
  24073. // Physics
  24074. //TODO implement correct serialization for physics impostors.
  24075. var impostor = this.getPhysicsImpostor();
  24076. if (impostor) {
  24077. serializationObject.physicsMass = impostor.getParam("mass");
  24078. serializationObject.physicsFriction = impostor.getParam("friction");
  24079. serializationObject.physicsRestitution = impostor.getParam("mass");
  24080. serializationObject.physicsImpostor = impostor.type;
  24081. }
  24082. // Metadata
  24083. if (this.metadata) {
  24084. serializationObject.metadata = this.metadata;
  24085. }
  24086. // Instances
  24087. serializationObject.instances = [];
  24088. for (var index = 0; index < this.instances.length; index++) {
  24089. var instance = this.instances[index];
  24090. var serializationInstance = {
  24091. name: instance.name,
  24092. position: instance.position.asArray(),
  24093. scaling: instance.scaling.asArray()
  24094. };
  24095. if (instance.rotationQuaternion) {
  24096. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24097. }
  24098. else if (instance.rotation) {
  24099. serializationInstance.rotation = instance.rotation.asArray();
  24100. }
  24101. serializationObject.instances.push(serializationInstance);
  24102. // Animations
  24103. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24104. serializationInstance.ranges = instance.serializeAnimationRanges();
  24105. }
  24106. //
  24107. // Animations
  24108. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24109. serializationObject.ranges = this.serializeAnimationRanges();
  24110. // Layer mask
  24111. serializationObject.layerMask = this.layerMask;
  24112. // Alpha
  24113. serializationObject.alphaIndex = this.alphaIndex;
  24114. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24115. // Overlay
  24116. serializationObject.overlayAlpha = this.overlayAlpha;
  24117. serializationObject.overlayColor = this.overlayColor.asArray();
  24118. serializationObject.renderOverlay = this.renderOverlay;
  24119. // Fog
  24120. serializationObject.applyFog = this.applyFog;
  24121. // Action Manager
  24122. if (this.actionManager) {
  24123. serializationObject.actions = this.actionManager.serialize(this.name);
  24124. }
  24125. };
  24126. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24127. if (!this.geometry) {
  24128. return;
  24129. }
  24130. this._markSubMeshesAsAttributesDirty();
  24131. var morphTargetManager = this._morphTargetManager;
  24132. if (morphTargetManager && morphTargetManager.vertexCount) {
  24133. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24134. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24135. this.morphTargetManager = null;
  24136. return;
  24137. }
  24138. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24139. var morphTarget = morphTargetManager.getActiveTarget(index);
  24140. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  24141. if (morphTarget.hasNormals) {
  24142. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  24143. }
  24144. if (morphTarget.hasTangents) {
  24145. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  24146. }
  24147. }
  24148. }
  24149. else {
  24150. var index = 0;
  24151. // Positions
  24152. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24153. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24154. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24155. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24156. }
  24157. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24158. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24159. }
  24160. index++;
  24161. }
  24162. }
  24163. };
  24164. // Statics
  24165. /**
  24166. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24167. * The parameter `parsedMesh` is the mesh to be copied.
  24168. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24169. */
  24170. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24171. var mesh;
  24172. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24173. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24174. }
  24175. else {
  24176. mesh = new Mesh(parsedMesh.name, scene);
  24177. }
  24178. mesh.id = parsedMesh.id;
  24179. if (BABYLON.Tags) {
  24180. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24181. }
  24182. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24183. if (parsedMesh.metadata !== undefined) {
  24184. mesh.metadata = parsedMesh.metadata;
  24185. }
  24186. if (parsedMesh.rotationQuaternion) {
  24187. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24188. }
  24189. else if (parsedMesh.rotation) {
  24190. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24191. }
  24192. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24193. if (parsedMesh.localMatrix) {
  24194. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24195. }
  24196. else if (parsedMesh.pivotMatrix) {
  24197. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24198. }
  24199. mesh.setEnabled(parsedMesh.isEnabled);
  24200. mesh.isVisible = parsedMesh.isVisible;
  24201. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24202. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24203. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24204. if (parsedMesh.applyFog !== undefined) {
  24205. mesh.applyFog = parsedMesh.applyFog;
  24206. }
  24207. if (parsedMesh.pickable !== undefined) {
  24208. mesh.isPickable = parsedMesh.pickable;
  24209. }
  24210. if (parsedMesh.alphaIndex !== undefined) {
  24211. mesh.alphaIndex = parsedMesh.alphaIndex;
  24212. }
  24213. mesh.receiveShadows = parsedMesh.receiveShadows;
  24214. mesh.billboardMode = parsedMesh.billboardMode;
  24215. if (parsedMesh.visibility !== undefined) {
  24216. mesh.visibility = parsedMesh.visibility;
  24217. }
  24218. mesh.checkCollisions = parsedMesh.checkCollisions;
  24219. if (parsedMesh.isBlocker !== undefined) {
  24220. mesh.isBlocker = parsedMesh.isBlocker;
  24221. }
  24222. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24223. // freezeWorldMatrix
  24224. if (parsedMesh.freezeWorldMatrix) {
  24225. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24226. }
  24227. // Parent
  24228. if (parsedMesh.parentId) {
  24229. mesh._waitingParentId = parsedMesh.parentId;
  24230. }
  24231. // Actions
  24232. if (parsedMesh.actions !== undefined) {
  24233. mesh._waitingActions = parsedMesh.actions;
  24234. }
  24235. // Overlay
  24236. if (parsedMesh.overlayAlpha !== undefined) {
  24237. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24238. }
  24239. if (parsedMesh.overlayColor !== undefined) {
  24240. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24241. }
  24242. if (parsedMesh.renderOverlay !== undefined) {
  24243. mesh.renderOverlay = parsedMesh.renderOverlay;
  24244. }
  24245. // Geometry
  24246. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24247. if (parsedMesh.delayLoadingFile) {
  24248. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24249. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24250. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24251. if (parsedMesh._binaryInfo) {
  24252. mesh._binaryInfo = parsedMesh._binaryInfo;
  24253. }
  24254. mesh._delayInfo = [];
  24255. if (parsedMesh.hasUVs) {
  24256. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24257. }
  24258. if (parsedMesh.hasUVs2) {
  24259. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24260. }
  24261. if (parsedMesh.hasUVs3) {
  24262. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24263. }
  24264. if (parsedMesh.hasUVs4) {
  24265. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24266. }
  24267. if (parsedMesh.hasUVs5) {
  24268. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24269. }
  24270. if (parsedMesh.hasUVs6) {
  24271. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24272. }
  24273. if (parsedMesh.hasColors) {
  24274. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24275. }
  24276. if (parsedMesh.hasMatricesIndices) {
  24277. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24278. }
  24279. if (parsedMesh.hasMatricesWeights) {
  24280. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24281. }
  24282. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24283. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24284. mesh._checkDelayState();
  24285. }
  24286. }
  24287. else {
  24288. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24289. }
  24290. // Material
  24291. if (parsedMesh.materialId) {
  24292. mesh.setMaterialByID(parsedMesh.materialId);
  24293. }
  24294. else {
  24295. mesh.material = null;
  24296. }
  24297. // Morph targets
  24298. if (parsedMesh.morphTargetManagerId > -1) {
  24299. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24300. }
  24301. // Skeleton
  24302. if (parsedMesh.skeletonId > -1) {
  24303. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24304. if (parsedMesh.numBoneInfluencers) {
  24305. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24306. }
  24307. }
  24308. // Animations
  24309. if (parsedMesh.animations) {
  24310. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24311. var parsedAnimation = parsedMesh.animations[animationIndex];
  24312. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24313. }
  24314. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24315. }
  24316. if (parsedMesh.autoAnimate) {
  24317. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24318. }
  24319. // Layer Mask
  24320. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24321. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24322. }
  24323. else {
  24324. mesh.layerMask = 0x0FFFFFFF;
  24325. }
  24326. // Physics
  24327. if (parsedMesh.physicsImpostor) {
  24328. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24329. mass: parsedMesh.physicsMass,
  24330. friction: parsedMesh.physicsFriction,
  24331. restitution: parsedMesh.physicsRestitution
  24332. }, scene);
  24333. }
  24334. // Instances
  24335. if (parsedMesh.instances) {
  24336. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24337. var parsedInstance = parsedMesh.instances[index];
  24338. var instance = mesh.createInstance(parsedInstance.name);
  24339. if (BABYLON.Tags) {
  24340. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24341. }
  24342. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24343. if (parsedInstance.parentId) {
  24344. instance._waitingParentId = parsedInstance.parentId;
  24345. }
  24346. if (parsedInstance.rotationQuaternion) {
  24347. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24348. }
  24349. else if (parsedInstance.rotation) {
  24350. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24351. }
  24352. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24353. instance.checkCollisions = mesh.checkCollisions;
  24354. if (parsedMesh.animations) {
  24355. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24356. parsedAnimation = parsedMesh.animations[animationIndex];
  24357. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24358. }
  24359. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24360. }
  24361. }
  24362. }
  24363. return mesh;
  24364. };
  24365. /**
  24366. * Creates a ribbon mesh.
  24367. * Please consider using the same method from the MeshBuilder class instead.
  24368. * 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.
  24369. *
  24370. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24371. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24372. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24373. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24374. * 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.
  24375. * 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.
  24376. * 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
  24377. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24378. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24380. */
  24381. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24382. if (closeArray === void 0) { closeArray = false; }
  24383. if (updatable === void 0) { updatable = false; }
  24384. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24385. pathArray: pathArray,
  24386. closeArray: closeArray,
  24387. closePath: closePath,
  24388. offset: offset,
  24389. updatable: updatable,
  24390. sideOrientation: sideOrientation,
  24391. instance: instance
  24392. }, scene);
  24393. };
  24394. /**
  24395. * Creates a plane polygonal mesh. By default, this is a disc.
  24396. * Please consider using the same method from the MeshBuilder class instead.
  24397. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24398. * 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.
  24399. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24400. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24401. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24402. */
  24403. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24404. if (scene === void 0) { scene = null; }
  24405. var options = {
  24406. radius: radius,
  24407. tessellation: tessellation,
  24408. sideOrientation: sideOrientation,
  24409. updatable: updatable
  24410. };
  24411. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24412. };
  24413. /**
  24414. * Creates a box mesh.
  24415. * Please consider using the same method from the MeshBuilder class instead.
  24416. * The parameter `size` sets the size (float) of each box side (default 1).
  24417. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24418. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24420. */
  24421. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24422. if (scene === void 0) { scene = null; }
  24423. var options = {
  24424. size: size,
  24425. sideOrientation: sideOrientation,
  24426. updatable: updatable
  24427. };
  24428. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24429. };
  24430. /**
  24431. * Creates a sphere mesh.
  24432. * Please consider using the same method from the MeshBuilder class instead.
  24433. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24434. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24435. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24436. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24437. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24438. */
  24439. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24440. var options = {
  24441. segments: segments,
  24442. diameterX: diameter,
  24443. diameterY: diameter,
  24444. diameterZ: diameter,
  24445. sideOrientation: sideOrientation,
  24446. updatable: updatable
  24447. };
  24448. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24449. };
  24450. /**
  24451. * Creates a cylinder or a cone mesh.
  24452. * Please consider using the same method from the MeshBuilder class instead.
  24453. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24454. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24455. * 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.
  24456. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24457. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24458. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24459. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24460. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24461. */
  24462. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24463. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24464. if (scene !== undefined) {
  24465. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24466. updatable = scene;
  24467. }
  24468. scene = subdivisions;
  24469. subdivisions = 1;
  24470. }
  24471. var options = {
  24472. height: height,
  24473. diameterTop: diameterTop,
  24474. diameterBottom: diameterBottom,
  24475. tessellation: tessellation,
  24476. subdivisions: subdivisions,
  24477. sideOrientation: sideOrientation,
  24478. updatable: updatable
  24479. };
  24480. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24481. };
  24482. // Torus (Code from SharpDX.org)
  24483. /**
  24484. * Creates a torus mesh.
  24485. * Please consider using the same method from the MeshBuilder class instead.
  24486. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24487. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24488. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24489. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24490. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24492. */
  24493. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24494. var options = {
  24495. diameter: diameter,
  24496. thickness: thickness,
  24497. tessellation: tessellation,
  24498. sideOrientation: sideOrientation,
  24499. updatable: updatable
  24500. };
  24501. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24502. };
  24503. /**
  24504. * Creates a torus knot mesh.
  24505. * Please consider using the same method from the MeshBuilder class instead.
  24506. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24507. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24508. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24509. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24511. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24513. */
  24514. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24515. var options = {
  24516. radius: radius,
  24517. tube: tube,
  24518. radialSegments: radialSegments,
  24519. tubularSegments: tubularSegments,
  24520. p: p,
  24521. q: q,
  24522. sideOrientation: sideOrientation,
  24523. updatable: updatable
  24524. };
  24525. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24526. };
  24527. /**
  24528. * Creates a line mesh.
  24529. * Please consider using the same method from the MeshBuilder class instead.
  24530. * 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.
  24531. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24532. * The parameter `points` is an array successive Vector3.
  24533. * 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
  24534. * When updating an instance, remember that only point positions can change, not the number of points.
  24535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24536. */
  24537. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24538. if (scene === void 0) { scene = null; }
  24539. if (updatable === void 0) { updatable = false; }
  24540. if (instance === void 0) { instance = null; }
  24541. var options = {
  24542. points: points,
  24543. updatable: updatable,
  24544. instance: instance
  24545. };
  24546. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24547. };
  24548. /**
  24549. * Creates a dashed line mesh.
  24550. * Please consider using the same method from the MeshBuilder class instead.
  24551. * 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.
  24552. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24553. * The parameter `points` is an array successive Vector3.
  24554. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24555. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24556. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24557. * 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
  24558. * When updating an instance, remember that only point positions can change, not the number of points.
  24559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24560. */
  24561. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24562. if (scene === void 0) { scene = null; }
  24563. var options = {
  24564. points: points,
  24565. dashSize: dashSize,
  24566. gapSize: gapSize,
  24567. dashNb: dashNb,
  24568. updatable: updatable,
  24569. instance: instance
  24570. };
  24571. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24572. };
  24573. /**
  24574. * Creates a polygon mesh.
  24575. * Please consider using the same method from the MeshBuilder class instead.
  24576. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24577. * 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.
  24578. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24580. * Remember you can only change the shape positions, not their number when updating a polygon.
  24581. */
  24582. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24583. var options = {
  24584. shape: shape,
  24585. holes: holes,
  24586. updatable: updatable,
  24587. sideOrientation: sideOrientation
  24588. };
  24589. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24590. };
  24591. /**
  24592. * Creates an extruded polygon mesh, with depth in the Y direction.
  24593. * Please consider using the same method from the MeshBuilder class instead.
  24594. */
  24595. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24596. var options = {
  24597. shape: shape,
  24598. holes: holes,
  24599. depth: depth,
  24600. updatable: updatable,
  24601. sideOrientation: sideOrientation
  24602. };
  24603. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24604. };
  24605. /**
  24606. * Creates an extruded shape mesh.
  24607. * 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.
  24608. * Please consider using the same method from the MeshBuilder class instead.
  24609. *
  24610. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24611. * 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
  24612. * extruded along the Z axis.
  24613. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24614. * 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.
  24615. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24616. * 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
  24617. * 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
  24618. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24619. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24620. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24622. */
  24623. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24624. if (scene === void 0) { scene = null; }
  24625. var options = {
  24626. shape: shape,
  24627. path: path,
  24628. scale: scale,
  24629. rotation: rotation,
  24630. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24631. sideOrientation: sideOrientation,
  24632. instance: instance,
  24633. updatable: updatable
  24634. };
  24635. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24636. };
  24637. /**
  24638. * Creates an custom extruded shape mesh.
  24639. * 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.
  24640. * Please consider using the same method from the MeshBuilder class instead.
  24641. *
  24642. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24643. * 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
  24644. * extruded along the Z axis.
  24645. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24646. * 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
  24647. * and the distance of this point from the begining of the path :
  24648. * ```javascript
  24649. * var rotationFunction = function(i, distance) {
  24650. * // do things
  24651. * return rotationValue; }
  24652. * ```
  24653. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24654. * 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
  24655. * and the distance of this point from the begining of the path :
  24656. * ```javascript
  24657. * var scaleFunction = function(i, distance) {
  24658. * // do things
  24659. * return scaleValue;}
  24660. * ```
  24661. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24662. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24663. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24664. * 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
  24665. * 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
  24666. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24667. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24668. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24669. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24670. */
  24671. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24672. var options = {
  24673. shape: shape,
  24674. path: path,
  24675. scaleFunction: scaleFunction,
  24676. rotationFunction: rotationFunction,
  24677. ribbonCloseArray: ribbonCloseArray,
  24678. ribbonClosePath: ribbonClosePath,
  24679. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24680. sideOrientation: sideOrientation,
  24681. instance: instance,
  24682. updatable: updatable
  24683. };
  24684. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24685. };
  24686. /**
  24687. * Creates lathe mesh.
  24688. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24689. * Please consider using the same method from the MeshBuilder class instead.
  24690. * 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
  24691. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24692. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24693. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24694. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24695. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24696. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24697. */
  24698. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24699. var options = {
  24700. shape: shape,
  24701. radius: radius,
  24702. tessellation: tessellation,
  24703. sideOrientation: sideOrientation,
  24704. updatable: updatable
  24705. };
  24706. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24707. };
  24708. /**
  24709. * Creates a plane mesh.
  24710. * Please consider using the same method from the MeshBuilder class instead.
  24711. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24712. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24713. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24714. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24715. */
  24716. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24717. var options = {
  24718. size: size,
  24719. width: size,
  24720. height: size,
  24721. sideOrientation: sideOrientation,
  24722. updatable: updatable
  24723. };
  24724. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24725. };
  24726. /**
  24727. * Creates a ground mesh.
  24728. * Please consider using the same method from the MeshBuilder class instead.
  24729. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24730. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24732. */
  24733. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24734. var options = {
  24735. width: width,
  24736. height: height,
  24737. subdivisions: subdivisions,
  24738. updatable: updatable
  24739. };
  24740. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24741. };
  24742. /**
  24743. * Creates a tiled ground mesh.
  24744. * Please consider using the same method from the MeshBuilder class instead.
  24745. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24746. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24747. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24748. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24749. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24750. * numbers of subdivisions on the ground width and height of each tile.
  24751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24752. */
  24753. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24754. var options = {
  24755. xmin: xmin,
  24756. zmin: zmin,
  24757. xmax: xmax,
  24758. zmax: zmax,
  24759. subdivisions: subdivisions,
  24760. precision: precision,
  24761. updatable: updatable
  24762. };
  24763. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24764. };
  24765. /**
  24766. * Creates a ground mesh from a height map.
  24767. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24768. * Please consider using the same method from the MeshBuilder class instead.
  24769. * The parameter `url` sets the URL of the height map image resource.
  24770. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24771. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24772. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24773. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24774. * 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).
  24775. * This function is passed the newly built mesh :
  24776. * ```javascript
  24777. * function(mesh) { // do things
  24778. * return; }
  24779. * ```
  24780. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24781. */
  24782. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24783. var options = {
  24784. width: width,
  24785. height: height,
  24786. subdivisions: subdivisions,
  24787. minHeight: minHeight,
  24788. maxHeight: maxHeight,
  24789. updatable: updatable,
  24790. onReady: onReady
  24791. };
  24792. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24793. };
  24794. /**
  24795. * Creates a tube mesh.
  24796. * 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.
  24797. * Please consider using the same method from the MeshBuilder class instead.
  24798. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24799. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24800. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24801. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24802. * 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.
  24803. * It must return a radius value (positive float) :
  24804. * ```javascript
  24805. * var radiusFunction = function(i, distance) {
  24806. * // do things
  24807. * return radius; }
  24808. * ```
  24809. * 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
  24810. * 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
  24811. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24812. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24813. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24814. */
  24815. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24816. var options = {
  24817. path: path,
  24818. radius: radius,
  24819. tessellation: tessellation,
  24820. radiusFunction: radiusFunction,
  24821. arc: 1,
  24822. cap: cap,
  24823. updatable: updatable,
  24824. sideOrientation: sideOrientation,
  24825. instance: instance
  24826. };
  24827. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24828. };
  24829. /**
  24830. * Creates a polyhedron mesh.
  24831. * Please consider using the same method from the MeshBuilder class instead.
  24832. * 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
  24833. * to choose the wanted type.
  24834. * The parameter `size` (positive float, default 1) sets the polygon size.
  24835. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24836. * 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`.
  24837. * 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
  24838. * 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)`).
  24839. * 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
  24840. * 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.
  24841. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24842. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24843. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24844. */
  24845. Mesh.CreatePolyhedron = function (name, options, scene) {
  24846. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24847. };
  24848. /**
  24849. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24850. * Please consider using the same method from the MeshBuilder class instead.
  24851. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24852. * 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`).
  24853. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24854. * 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.
  24855. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24856. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24857. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24858. */
  24859. Mesh.CreateIcoSphere = function (name, options, scene) {
  24860. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24861. };
  24862. /**
  24863. * Creates a decal mesh.
  24864. * Please consider using the same method from the MeshBuilder class instead.
  24865. * 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.
  24866. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  24867. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  24868. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  24869. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  24870. */
  24871. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  24872. var options = {
  24873. position: position,
  24874. normal: normal,
  24875. size: size,
  24876. angle: angle
  24877. };
  24878. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24879. };
  24880. // Skeletons
  24881. /**
  24882. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24883. */
  24884. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24885. if (!this._sourcePositions) {
  24886. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24887. if (!source) {
  24888. return this._sourcePositions;
  24889. }
  24890. this._sourcePositions = new Float32Array(source);
  24891. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  24892. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24893. }
  24894. }
  24895. return this._sourcePositions;
  24896. };
  24897. /**
  24898. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24899. */
  24900. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24901. if (!this._sourceNormals) {
  24902. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24903. if (!source) {
  24904. return this._sourceNormals;
  24905. }
  24906. this._sourceNormals = new Float32Array(source);
  24907. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  24908. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24909. }
  24910. }
  24911. return this._sourceNormals;
  24912. };
  24913. /**
  24914. * Updates the vertex buffer by applying transformation from the bones.
  24915. * Returns the Mesh.
  24916. *
  24917. * @param {skeleton} skeleton to apply
  24918. */
  24919. Mesh.prototype.applySkeleton = function (skeleton) {
  24920. if (!this.geometry) {
  24921. return this;
  24922. }
  24923. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24924. return this;
  24925. }
  24926. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24927. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24928. return this;
  24929. }
  24930. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24931. return this;
  24932. }
  24933. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24934. return this;
  24935. }
  24936. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24937. return this;
  24938. }
  24939. if (!this._sourcePositions) {
  24940. var submeshes = this.subMeshes.slice();
  24941. this.setPositionsForCPUSkinning();
  24942. this.subMeshes = submeshes;
  24943. }
  24944. if (!this._sourceNormals) {
  24945. this.setNormalsForCPUSkinning();
  24946. }
  24947. // positionsData checks for not being Float32Array will only pass at most once
  24948. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24949. if (!positionsData) {
  24950. return this;
  24951. }
  24952. if (!(positionsData instanceof Float32Array)) {
  24953. positionsData = new Float32Array(positionsData);
  24954. }
  24955. // normalsData checks for not being Float32Array will only pass at most once
  24956. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24957. if (!normalsData) {
  24958. return this;
  24959. }
  24960. if (!(normalsData instanceof Float32Array)) {
  24961. normalsData = new Float32Array(normalsData);
  24962. }
  24963. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24964. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24965. if (!matricesWeightsData || !matricesIndicesData) {
  24966. return this;
  24967. }
  24968. var needExtras = this.numBoneInfluencers > 4;
  24969. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24970. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24971. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  24972. return this;
  24973. }
  24974. var skeletonMatrices = skeleton.getTransformMatrices(this);
  24975. var tempVector3 = BABYLON.Vector3.Zero();
  24976. var finalMatrix = new BABYLON.Matrix();
  24977. var tempMatrix = new BABYLON.Matrix();
  24978. var matWeightIdx = 0;
  24979. var inf;
  24980. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24981. var weight;
  24982. for (inf = 0; inf < 4; inf++) {
  24983. weight = matricesWeightsData[matWeightIdx + inf];
  24984. if (weight > 0) {
  24985. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24986. finalMatrix.addToSelf(tempMatrix);
  24987. }
  24988. else
  24989. break;
  24990. }
  24991. if (needExtras) {
  24992. for (inf = 0; inf < 4; inf++) {
  24993. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24994. if (weight > 0) {
  24995. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24996. finalMatrix.addToSelf(tempMatrix);
  24997. }
  24998. else
  24999. break;
  25000. }
  25001. }
  25002. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25003. tempVector3.toArray(positionsData, index);
  25004. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25005. tempVector3.toArray(normalsData, index);
  25006. finalMatrix.reset();
  25007. }
  25008. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25009. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25010. return this;
  25011. };
  25012. // Tools
  25013. /**
  25014. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25015. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25016. */
  25017. Mesh.MinMax = function (meshes) {
  25018. var minVector = null;
  25019. var maxVector = null;
  25020. meshes.forEach(function (mesh, index, array) {
  25021. var boundingInfo = mesh.getBoundingInfo();
  25022. if (!boundingInfo) {
  25023. return;
  25024. }
  25025. var boundingBox = boundingInfo.boundingBox;
  25026. if (!minVector || !maxVector) {
  25027. minVector = boundingBox.minimumWorld;
  25028. maxVector = boundingBox.maximumWorld;
  25029. }
  25030. else {
  25031. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25032. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25033. }
  25034. });
  25035. if (!minVector || !maxVector) {
  25036. return {
  25037. min: BABYLON.Vector3.Zero(),
  25038. max: BABYLON.Vector3.Zero()
  25039. };
  25040. }
  25041. return {
  25042. min: minVector,
  25043. max: maxVector
  25044. };
  25045. };
  25046. /**
  25047. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25048. */
  25049. Mesh.Center = function (meshesOrMinMaxVector) {
  25050. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25051. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25052. };
  25053. /**
  25054. * Merge the array of meshes into a single mesh for performance reasons.
  25055. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25056. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25057. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25058. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25059. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25060. */
  25061. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25062. if (disposeSource === void 0) { disposeSource = true; }
  25063. var index;
  25064. if (!allow32BitsIndices) {
  25065. var totalVertices = 0;
  25066. // Counting vertices
  25067. for (index = 0; index < meshes.length; index++) {
  25068. if (meshes[index]) {
  25069. totalVertices += meshes[index].getTotalVertices();
  25070. if (totalVertices > 65536) {
  25071. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25072. return null;
  25073. }
  25074. }
  25075. }
  25076. }
  25077. // Merge
  25078. var vertexData = null;
  25079. var otherVertexData;
  25080. var indiceArray = new Array();
  25081. var source = null;
  25082. for (index = 0; index < meshes.length; index++) {
  25083. if (meshes[index]) {
  25084. meshes[index].computeWorldMatrix(true);
  25085. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25086. otherVertexData.transform(meshes[index].getWorldMatrix());
  25087. if (vertexData) {
  25088. vertexData.merge(otherVertexData);
  25089. }
  25090. else {
  25091. vertexData = otherVertexData;
  25092. source = meshes[index];
  25093. }
  25094. if (subdivideWithSubMeshes) {
  25095. indiceArray.push(meshes[index].getTotalIndices());
  25096. }
  25097. }
  25098. }
  25099. source = source;
  25100. if (!meshSubclass) {
  25101. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25102. }
  25103. vertexData.applyToMesh(meshSubclass);
  25104. // Setting properties
  25105. meshSubclass.material = source.material;
  25106. meshSubclass.checkCollisions = source.checkCollisions;
  25107. // Cleaning
  25108. if (disposeSource) {
  25109. for (index = 0; index < meshes.length; index++) {
  25110. if (meshes[index]) {
  25111. meshes[index].dispose();
  25112. }
  25113. }
  25114. }
  25115. // Subdivide
  25116. if (subdivideWithSubMeshes) {
  25117. //-- Suppresions du submesh global
  25118. meshSubclass.releaseSubMeshes();
  25119. index = 0;
  25120. var offset = 0;
  25121. //-- aplique la subdivision en fonction du tableau d'indices
  25122. while (index < indiceArray.length) {
  25123. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25124. offset += indiceArray[index];
  25125. index++;
  25126. }
  25127. }
  25128. return meshSubclass;
  25129. };
  25130. // Consts
  25131. Mesh._FRONTSIDE = 0;
  25132. Mesh._BACKSIDE = 1;
  25133. Mesh._DOUBLESIDE = 2;
  25134. Mesh._DEFAULTSIDE = 0;
  25135. Mesh._NO_CAP = 0;
  25136. Mesh._CAP_START = 1;
  25137. Mesh._CAP_END = 2;
  25138. Mesh._CAP_ALL = 3;
  25139. return Mesh;
  25140. }(BABYLON.AbstractMesh));
  25141. BABYLON.Mesh = Mesh;
  25142. })(BABYLON || (BABYLON = {}));
  25143. //# sourceMappingURL=babylon.mesh.js.map
  25144. var BABYLON;
  25145. (function (BABYLON) {
  25146. var BaseSubMesh = /** @class */ (function () {
  25147. function BaseSubMesh() {
  25148. }
  25149. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25150. get: function () {
  25151. return this._materialEffect;
  25152. },
  25153. enumerable: true,
  25154. configurable: true
  25155. });
  25156. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25157. if (defines === void 0) { defines = null; }
  25158. if (this._materialEffect === effect) {
  25159. if (!effect) {
  25160. this._materialDefines = null;
  25161. }
  25162. return;
  25163. }
  25164. this._materialDefines = defines;
  25165. this._materialEffect = effect;
  25166. };
  25167. return BaseSubMesh;
  25168. }());
  25169. BABYLON.BaseSubMesh = BaseSubMesh;
  25170. var SubMesh = /** @class */ (function (_super) {
  25171. __extends(SubMesh, _super);
  25172. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25173. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25174. var _this = _super.call(this) || this;
  25175. _this.materialIndex = materialIndex;
  25176. _this.verticesStart = verticesStart;
  25177. _this.verticesCount = verticesCount;
  25178. _this.indexStart = indexStart;
  25179. _this.indexCount = indexCount;
  25180. _this._renderId = 0;
  25181. _this._mesh = mesh;
  25182. _this._renderingMesh = renderingMesh || mesh;
  25183. mesh.subMeshes.push(_this);
  25184. _this._trianglePlanes = [];
  25185. _this._id = mesh.subMeshes.length - 1;
  25186. if (createBoundingBox) {
  25187. _this.refreshBoundingInfo();
  25188. mesh.computeWorldMatrix(true);
  25189. }
  25190. return _this;
  25191. }
  25192. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25193. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25194. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25195. };
  25196. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25197. get: function () {
  25198. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25199. },
  25200. enumerable: true,
  25201. configurable: true
  25202. });
  25203. /**
  25204. * Returns the submesh BoudingInfo object.
  25205. */
  25206. SubMesh.prototype.getBoundingInfo = function () {
  25207. if (this.IsGlobal) {
  25208. return this._mesh.getBoundingInfo();
  25209. }
  25210. return this._boundingInfo;
  25211. };
  25212. /**
  25213. * Sets the submesh BoundingInfo.
  25214. * Return the SubMesh.
  25215. */
  25216. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25217. this._boundingInfo = boundingInfo;
  25218. return this;
  25219. };
  25220. /**
  25221. * Returns the mesh of the current submesh.
  25222. */
  25223. SubMesh.prototype.getMesh = function () {
  25224. return this._mesh;
  25225. };
  25226. /**
  25227. * Returns the rendering mesh of the submesh.
  25228. */
  25229. SubMesh.prototype.getRenderingMesh = function () {
  25230. return this._renderingMesh;
  25231. };
  25232. /**
  25233. * Returns the submesh material.
  25234. */
  25235. SubMesh.prototype.getMaterial = function () {
  25236. var rootMaterial = this._renderingMesh.material;
  25237. if (rootMaterial && rootMaterial.getSubMaterial) {
  25238. var multiMaterial = rootMaterial;
  25239. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25240. if (this._currentMaterial !== effectiveMaterial) {
  25241. this._currentMaterial = effectiveMaterial;
  25242. this._materialDefines = null;
  25243. }
  25244. return effectiveMaterial;
  25245. }
  25246. if (!rootMaterial) {
  25247. return this._mesh.getScene().defaultMaterial;
  25248. }
  25249. return rootMaterial;
  25250. };
  25251. // Methods
  25252. /**
  25253. * Sets a new updated BoundingInfo object to the submesh.
  25254. * Returns the SubMesh.
  25255. */
  25256. SubMesh.prototype.refreshBoundingInfo = function () {
  25257. this._lastColliderWorldVertices = null;
  25258. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25259. return this;
  25260. }
  25261. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25262. if (!data) {
  25263. this._boundingInfo = this._mesh._boundingInfo;
  25264. return this;
  25265. }
  25266. var indices = this._renderingMesh.getIndices();
  25267. var extend;
  25268. //is this the only submesh?
  25269. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25270. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25271. if (!boundingInfo) {
  25272. return this;
  25273. }
  25274. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25275. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25276. }
  25277. else {
  25278. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25279. }
  25280. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25281. return this;
  25282. };
  25283. SubMesh.prototype._checkCollision = function (collider) {
  25284. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25285. if (!boundingInfo) {
  25286. return false;
  25287. }
  25288. return boundingInfo._checkCollision(collider);
  25289. };
  25290. /**
  25291. * Updates the submesh BoundingInfo.
  25292. * Returns the Submesh.
  25293. */
  25294. SubMesh.prototype.updateBoundingInfo = function (world) {
  25295. var boundingInfo = this.getBoundingInfo();
  25296. if (!boundingInfo) {
  25297. this.refreshBoundingInfo();
  25298. }
  25299. boundingInfo.update(world);
  25300. return this;
  25301. };
  25302. /**
  25303. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25304. * Boolean returned.
  25305. */
  25306. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25307. var boundingInfo = this.getBoundingInfo();
  25308. if (!boundingInfo) {
  25309. return false;
  25310. }
  25311. return boundingInfo.isInFrustum(frustumPlanes);
  25312. };
  25313. /**
  25314. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25315. * Boolean returned.
  25316. */
  25317. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25318. var boundingInfo = this.getBoundingInfo();
  25319. if (!boundingInfo) {
  25320. return false;
  25321. }
  25322. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25323. };
  25324. /**
  25325. * Renders the submesh.
  25326. * Returns it.
  25327. */
  25328. SubMesh.prototype.render = function (enableAlphaMode) {
  25329. this._renderingMesh.render(this, enableAlphaMode);
  25330. return this;
  25331. };
  25332. /**
  25333. * Returns a new Index Buffer.
  25334. * Type returned : WebGLBuffer.
  25335. */
  25336. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25337. if (!this._linesIndexBuffer) {
  25338. var linesIndices = [];
  25339. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25340. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25341. }
  25342. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25343. this.linesIndexCount = linesIndices.length;
  25344. }
  25345. return this._linesIndexBuffer;
  25346. };
  25347. /**
  25348. * True is the passed Ray intersects the submesh bounding box.
  25349. * Boolean returned.
  25350. */
  25351. SubMesh.prototype.canIntersects = function (ray) {
  25352. var boundingInfo = this.getBoundingInfo();
  25353. if (!boundingInfo) {
  25354. return false;
  25355. }
  25356. return ray.intersectsBox(boundingInfo.boundingBox);
  25357. };
  25358. /**
  25359. * Returns an object IntersectionInfo.
  25360. */
  25361. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25362. var intersectInfo = null;
  25363. // LineMesh first as it's also a Mesh...
  25364. if (this._mesh instanceof BABYLON.LinesMesh) {
  25365. var lineMesh = this._mesh;
  25366. // Line test
  25367. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25368. var p0 = positions[indices[index]];
  25369. var p1 = positions[indices[index + 1]];
  25370. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25371. if (length < 0) {
  25372. continue;
  25373. }
  25374. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25375. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25376. if (fastCheck) {
  25377. break;
  25378. }
  25379. }
  25380. }
  25381. }
  25382. else {
  25383. // Triangles test
  25384. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25385. var p0 = positions[indices[index]];
  25386. var p1 = positions[indices[index + 1]];
  25387. var p2 = positions[indices[index + 2]];
  25388. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25389. if (currentIntersectInfo) {
  25390. if (currentIntersectInfo.distance < 0) {
  25391. continue;
  25392. }
  25393. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25394. intersectInfo = currentIntersectInfo;
  25395. intersectInfo.faceId = index / 3;
  25396. if (fastCheck) {
  25397. break;
  25398. }
  25399. }
  25400. }
  25401. }
  25402. }
  25403. return intersectInfo;
  25404. };
  25405. SubMesh.prototype._rebuild = function () {
  25406. if (this._linesIndexBuffer) {
  25407. this._linesIndexBuffer = null;
  25408. }
  25409. };
  25410. // Clone
  25411. /**
  25412. * Creates a new Submesh from the passed Mesh.
  25413. */
  25414. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25415. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25416. if (!this.IsGlobal) {
  25417. var boundingInfo = this.getBoundingInfo();
  25418. if (!boundingInfo) {
  25419. return result;
  25420. }
  25421. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  25422. }
  25423. return result;
  25424. };
  25425. // Dispose
  25426. /**
  25427. * Disposes the Submesh.
  25428. * Returns nothing.
  25429. */
  25430. SubMesh.prototype.dispose = function () {
  25431. if (this._linesIndexBuffer) {
  25432. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25433. this._linesIndexBuffer = null;
  25434. }
  25435. // Remove from mesh
  25436. var index = this._mesh.subMeshes.indexOf(this);
  25437. this._mesh.subMeshes.splice(index, 1);
  25438. };
  25439. // Statics
  25440. /**
  25441. * Creates a new Submesh from the passed parameters :
  25442. * - materialIndex (integer) : the index of the main mesh material.
  25443. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25444. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25445. * - mesh (Mesh) : the main mesh to create the submesh from.
  25446. * - renderingMesh (optional Mesh) : rendering mesh.
  25447. */
  25448. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25449. var minVertexIndex = Number.MAX_VALUE;
  25450. var maxVertexIndex = -Number.MAX_VALUE;
  25451. renderingMesh = (renderingMesh || mesh);
  25452. var indices = renderingMesh.getIndices();
  25453. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25454. var vertexIndex = indices[index];
  25455. if (vertexIndex < minVertexIndex)
  25456. minVertexIndex = vertexIndex;
  25457. if (vertexIndex > maxVertexIndex)
  25458. maxVertexIndex = vertexIndex;
  25459. }
  25460. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25461. };
  25462. return SubMesh;
  25463. }(BaseSubMesh));
  25464. BABYLON.SubMesh = SubMesh;
  25465. })(BABYLON || (BABYLON = {}));
  25466. //# sourceMappingURL=babylon.subMesh.js.map
  25467. var BABYLON;
  25468. (function (BABYLON) {
  25469. var EffectFallbacks = /** @class */ (function () {
  25470. function EffectFallbacks() {
  25471. this._defines = {};
  25472. this._currentRank = 32;
  25473. this._maxRank = -1;
  25474. }
  25475. EffectFallbacks.prototype.unBindMesh = function () {
  25476. this._mesh = null;
  25477. };
  25478. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25479. if (!this._defines[rank]) {
  25480. if (rank < this._currentRank) {
  25481. this._currentRank = rank;
  25482. }
  25483. if (rank > this._maxRank) {
  25484. this._maxRank = rank;
  25485. }
  25486. this._defines[rank] = new Array();
  25487. }
  25488. this._defines[rank].push(define);
  25489. };
  25490. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25491. this._meshRank = rank;
  25492. this._mesh = mesh;
  25493. if (rank < this._currentRank) {
  25494. this._currentRank = rank;
  25495. }
  25496. if (rank > this._maxRank) {
  25497. this._maxRank = rank;
  25498. }
  25499. };
  25500. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25501. get: function () {
  25502. return this._currentRank <= this._maxRank;
  25503. },
  25504. enumerable: true,
  25505. configurable: true
  25506. });
  25507. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25508. // First we try to switch to CPU skinning
  25509. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25510. this._mesh.computeBonesUsingShaders = false;
  25511. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25512. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25513. var scene = this._mesh.getScene();
  25514. for (var index = 0; index < scene.meshes.length; index++) {
  25515. var otherMesh = scene.meshes[index];
  25516. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25517. otherMesh.computeBonesUsingShaders = false;
  25518. }
  25519. }
  25520. }
  25521. else {
  25522. var currentFallbacks = this._defines[this._currentRank];
  25523. if (currentFallbacks) {
  25524. for (var index = 0; index < currentFallbacks.length; index++) {
  25525. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25526. }
  25527. }
  25528. this._currentRank++;
  25529. }
  25530. return currentDefines;
  25531. };
  25532. return EffectFallbacks;
  25533. }());
  25534. BABYLON.EffectFallbacks = EffectFallbacks;
  25535. var EffectCreationOptions = /** @class */ (function () {
  25536. function EffectCreationOptions() {
  25537. }
  25538. return EffectCreationOptions;
  25539. }());
  25540. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25541. var Effect = /** @class */ (function () {
  25542. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25543. if (samplers === void 0) { samplers = null; }
  25544. if (defines === void 0) { defines = null; }
  25545. if (fallbacks === void 0) { fallbacks = null; }
  25546. if (onCompiled === void 0) { onCompiled = null; }
  25547. if (onError === void 0) { onError = null; }
  25548. var _this = this;
  25549. this.uniqueId = 0;
  25550. this.onCompileObservable = new BABYLON.Observable();
  25551. this.onErrorObservable = new BABYLON.Observable();
  25552. this.onBindObservable = new BABYLON.Observable();
  25553. this._uniformBuffersNames = {};
  25554. this._isReady = false;
  25555. this._compilationError = "";
  25556. this.name = baseName;
  25557. if (attributesNamesOrOptions.attributes) {
  25558. var options = attributesNamesOrOptions;
  25559. this._engine = uniformsNamesOrEngine;
  25560. this._attributesNames = options.attributes;
  25561. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25562. this._samplers = options.samplers;
  25563. this.defines = options.defines;
  25564. this.onError = options.onError;
  25565. this.onCompiled = options.onCompiled;
  25566. this._fallbacks = options.fallbacks;
  25567. this._indexParameters = options.indexParameters;
  25568. if (options.uniformBuffersNames) {
  25569. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25570. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25571. }
  25572. }
  25573. }
  25574. else {
  25575. this._engine = engine;
  25576. this.defines = defines;
  25577. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25578. this._samplers = samplers;
  25579. this._attributesNames = attributesNamesOrOptions;
  25580. this.onError = onError;
  25581. this.onCompiled = onCompiled;
  25582. this._indexParameters = indexParameters;
  25583. this._fallbacks = fallbacks;
  25584. }
  25585. this.uniqueId = Effect._uniqueIdSeed++;
  25586. var vertexSource;
  25587. var fragmentSource;
  25588. if (baseName.vertexElement) {
  25589. vertexSource = document.getElementById(baseName.vertexElement);
  25590. if (!vertexSource) {
  25591. vertexSource = baseName.vertexElement;
  25592. }
  25593. }
  25594. else {
  25595. vertexSource = baseName.vertex || baseName;
  25596. }
  25597. if (baseName.fragmentElement) {
  25598. fragmentSource = document.getElementById(baseName.fragmentElement);
  25599. if (!fragmentSource) {
  25600. fragmentSource = baseName.fragmentElement;
  25601. }
  25602. }
  25603. else {
  25604. fragmentSource = baseName.fragment || baseName;
  25605. }
  25606. this._loadVertexShader(vertexSource, function (vertexCode) {
  25607. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25608. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25609. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25610. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25611. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25612. if (baseName) {
  25613. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25614. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25615. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25616. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25617. }
  25618. else {
  25619. _this._vertexSourceCode = migratedVertexCode;
  25620. _this._fragmentSourceCode = migratedFragmentCode;
  25621. }
  25622. _this._prepareEffect();
  25623. });
  25624. });
  25625. });
  25626. });
  25627. });
  25628. });
  25629. }
  25630. Object.defineProperty(Effect.prototype, "key", {
  25631. get: function () {
  25632. return this._key;
  25633. },
  25634. enumerable: true,
  25635. configurable: true
  25636. });
  25637. // Properties
  25638. Effect.prototype.isReady = function () {
  25639. return this._isReady;
  25640. };
  25641. Effect.prototype.getEngine = function () {
  25642. return this._engine;
  25643. };
  25644. Effect.prototype.getProgram = function () {
  25645. return this._program;
  25646. };
  25647. Effect.prototype.getAttributesNames = function () {
  25648. return this._attributesNames;
  25649. };
  25650. Effect.prototype.getAttributeLocation = function (index) {
  25651. return this._attributes[index];
  25652. };
  25653. Effect.prototype.getAttributeLocationByName = function (name) {
  25654. var index = this._attributesNames.indexOf(name);
  25655. return this._attributes[index];
  25656. };
  25657. Effect.prototype.getAttributesCount = function () {
  25658. return this._attributes.length;
  25659. };
  25660. Effect.prototype.getUniformIndex = function (uniformName) {
  25661. return this._uniformsNames.indexOf(uniformName);
  25662. };
  25663. Effect.prototype.getUniform = function (uniformName) {
  25664. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25665. };
  25666. Effect.prototype.getSamplers = function () {
  25667. return this._samplers;
  25668. };
  25669. Effect.prototype.getCompilationError = function () {
  25670. return this._compilationError;
  25671. };
  25672. // Methods
  25673. Effect.prototype.executeWhenCompiled = function (func) {
  25674. if (this.isReady()) {
  25675. func(this);
  25676. return;
  25677. }
  25678. this.onCompileObservable.add(function (effect) {
  25679. func(effect);
  25680. });
  25681. };
  25682. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25683. if (BABYLON.Tools.IsWindowObjectExist()) {
  25684. // DOM element ?
  25685. if (vertex instanceof HTMLElement) {
  25686. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25687. callback(vertexCode);
  25688. return;
  25689. }
  25690. }
  25691. // Base64 encoded ?
  25692. if (vertex.substr(0, 7) === "base64:") {
  25693. var vertexBinary = window.atob(vertex.substr(7));
  25694. callback(vertexBinary);
  25695. return;
  25696. }
  25697. // Is in local store ?
  25698. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25699. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25700. return;
  25701. }
  25702. var vertexShaderUrl;
  25703. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25704. vertexShaderUrl = vertex;
  25705. }
  25706. else {
  25707. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25708. }
  25709. // Vertex shader
  25710. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25711. };
  25712. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25713. if (BABYLON.Tools.IsWindowObjectExist()) {
  25714. // DOM element ?
  25715. if (fragment instanceof HTMLElement) {
  25716. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25717. callback(fragmentCode);
  25718. return;
  25719. }
  25720. }
  25721. // Base64 encoded ?
  25722. if (fragment.substr(0, 7) === "base64:") {
  25723. var fragmentBinary = window.atob(fragment.substr(7));
  25724. callback(fragmentBinary);
  25725. return;
  25726. }
  25727. // Is in local store ?
  25728. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25729. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25730. return;
  25731. }
  25732. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25733. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25734. return;
  25735. }
  25736. var fragmentShaderUrl;
  25737. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25738. fragmentShaderUrl = fragment;
  25739. }
  25740. else {
  25741. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25742. }
  25743. // Fragment shader
  25744. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25745. };
  25746. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  25747. // Rebuild shaders source code
  25748. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  25749. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  25750. vertexCode = prefix + vertexCode;
  25751. fragmentCode = prefix + fragmentCode;
  25752. // Number lines of shaders source code
  25753. var i = 2;
  25754. var regex = /\n/gm;
  25755. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25756. i = 2;
  25757. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25758. // Dump shaders name and formatted source code
  25759. if (this.name.vertexElement) {
  25760. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  25761. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  25762. }
  25763. else if (this.name.vertex) {
  25764. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  25765. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  25766. }
  25767. else {
  25768. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  25769. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  25770. }
  25771. };
  25772. ;
  25773. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25774. var preparedSourceCode = this._processPrecision(sourceCode);
  25775. if (this._engine.webGLVersion == 1) {
  25776. callback(preparedSourceCode);
  25777. return;
  25778. }
  25779. // Already converted
  25780. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25781. callback(preparedSourceCode.replace("#version 300 es", ""));
  25782. return;
  25783. }
  25784. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  25785. // Remove extensions
  25786. // #extension GL_OES_standard_derivatives : enable
  25787. // #extension GL_EXT_shader_texture_lod : enable
  25788. // #extension GL_EXT_frag_depth : enable
  25789. // #extension GL_EXT_draw_buffers : require
  25790. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  25791. var result = preparedSourceCode.replace(regex, "");
  25792. // Migrate to GLSL v300
  25793. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  25794. result = result.replace(/attribute[ \t]/g, "in ");
  25795. result = result.replace(/[ \t]attribute/g, " in");
  25796. if (isFragment) {
  25797. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  25798. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  25799. result = result.replace(/texture2D\s*\(/g, "texture(");
  25800. result = result.replace(/textureCube\s*\(/g, "texture(");
  25801. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25802. result = result.replace(/gl_FragColor/g, "glFragColor");
  25803. result = result.replace(/gl_FragData/g, "glFragData");
  25804. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  25805. }
  25806. callback(result);
  25807. };
  25808. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25809. var _this = this;
  25810. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25811. var match = regex.exec(sourceCode);
  25812. var returnValue = new String(sourceCode);
  25813. while (match != null) {
  25814. var includeFile = match[1];
  25815. // Uniform declaration
  25816. if (includeFile.indexOf("__decl__") !== -1) {
  25817. includeFile = includeFile.replace(/__decl__/, "");
  25818. if (this._engine.supportsUniformBuffers) {
  25819. includeFile = includeFile.replace(/Vertex/, "Ubo");
  25820. includeFile = includeFile.replace(/Fragment/, "Ubo");
  25821. }
  25822. includeFile = includeFile + "Declaration";
  25823. }
  25824. if (Effect.IncludesShadersStore[includeFile]) {
  25825. // Substitution
  25826. var includeContent = Effect.IncludesShadersStore[includeFile];
  25827. if (match[2]) {
  25828. var splits = match[3].split(",");
  25829. for (var index = 0; index < splits.length; index += 2) {
  25830. var source = new RegExp(splits[index], "g");
  25831. var dest = splits[index + 1];
  25832. includeContent = includeContent.replace(source, dest);
  25833. }
  25834. }
  25835. if (match[4]) {
  25836. var indexString = match[5];
  25837. if (indexString.indexOf("..") !== -1) {
  25838. var indexSplits = indexString.split("..");
  25839. var minIndex = parseInt(indexSplits[0]);
  25840. var maxIndex = parseInt(indexSplits[1]);
  25841. var sourceIncludeContent = includeContent.slice(0);
  25842. includeContent = "";
  25843. if (isNaN(maxIndex)) {
  25844. maxIndex = this._indexParameters[indexSplits[1]];
  25845. }
  25846. for (var i = minIndex; i < maxIndex; i++) {
  25847. if (!this._engine.supportsUniformBuffers) {
  25848. // Ubo replacement
  25849. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25850. return p1 + "{X}";
  25851. });
  25852. }
  25853. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  25854. }
  25855. }
  25856. else {
  25857. if (!this._engine.supportsUniformBuffers) {
  25858. // Ubo replacement
  25859. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25860. return p1 + "{X}";
  25861. });
  25862. }
  25863. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25864. }
  25865. }
  25866. // Replace
  25867. returnValue = returnValue.replace(match[0], includeContent);
  25868. }
  25869. else {
  25870. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25871. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25872. Effect.IncludesShadersStore[includeFile] = fileContent;
  25873. _this._processIncludes(returnValue, callback);
  25874. });
  25875. return;
  25876. }
  25877. match = regex.exec(sourceCode);
  25878. }
  25879. callback(returnValue);
  25880. };
  25881. Effect.prototype._processPrecision = function (source) {
  25882. if (source.indexOf("precision highp float") === -1) {
  25883. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25884. source = "precision mediump float;\n" + source;
  25885. }
  25886. else {
  25887. source = "precision highp float;\n" + source;
  25888. }
  25889. }
  25890. else {
  25891. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25892. source = source.replace("precision highp float", "precision mediump float");
  25893. }
  25894. }
  25895. return source;
  25896. };
  25897. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  25898. var _this = this;
  25899. this._isReady = false;
  25900. this._vertexSourceCodeOverride = vertexSourceCode;
  25901. this._fragmentSourceCodeOverride = fragmentSourceCode;
  25902. this.onError = function (effect, error) {
  25903. if (onError) {
  25904. onError(error);
  25905. }
  25906. };
  25907. this.onCompiled = function () {
  25908. var scenes = _this.getEngine().scenes;
  25909. for (var i = 0; i < scenes.length; i++) {
  25910. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25911. }
  25912. if (onCompiled) {
  25913. onCompiled(_this._program);
  25914. }
  25915. };
  25916. this._fallbacks = null;
  25917. this._prepareEffect();
  25918. };
  25919. Effect.prototype._prepareEffect = function () {
  25920. var attributesNames = this._attributesNames;
  25921. var defines = this.defines;
  25922. var fallbacks = this._fallbacks;
  25923. this._valueCache = {};
  25924. var previousProgram = this._program;
  25925. try {
  25926. var engine = this._engine;
  25927. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  25928. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride);
  25929. }
  25930. else {
  25931. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25932. }
  25933. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  25934. if (engine.webGLVersion > 1) {
  25935. for (var name in this._uniformBuffersNames) {
  25936. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  25937. }
  25938. }
  25939. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25940. this._attributes = engine.getAttributes(this._program, attributesNames);
  25941. var index;
  25942. for (index = 0; index < this._samplers.length; index++) {
  25943. var sampler = this.getUniform(this._samplers[index]);
  25944. if (sampler == null) {
  25945. this._samplers.splice(index, 1);
  25946. index--;
  25947. }
  25948. }
  25949. engine.bindSamplers(this);
  25950. this._compilationError = "";
  25951. this._isReady = true;
  25952. if (this.onCompiled) {
  25953. this.onCompiled(this);
  25954. }
  25955. this.onCompileObservable.notifyObservers(this);
  25956. this.onCompileObservable.clear();
  25957. // Unbind mesh reference in fallbacks
  25958. if (this._fallbacks) {
  25959. this._fallbacks.unBindMesh();
  25960. }
  25961. if (previousProgram) {
  25962. this.getEngine()._deleteProgram(previousProgram);
  25963. }
  25964. }
  25965. catch (e) {
  25966. this._compilationError = e.message;
  25967. // Let's go through fallbacks then
  25968. BABYLON.Tools.Error("Unable to compile effect:");
  25969. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  25970. return " " + uniform;
  25971. }));
  25972. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  25973. return " " + attribute;
  25974. }));
  25975. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25976. BABYLON.Tools.Error("Error: " + this._compilationError);
  25977. if (previousProgram) {
  25978. this._program = previousProgram;
  25979. this._isReady = true;
  25980. if (this.onError) {
  25981. this.onError(this, this._compilationError);
  25982. }
  25983. this.onErrorObservable.notifyObservers(this);
  25984. }
  25985. if (fallbacks && fallbacks.isMoreFallbacks) {
  25986. BABYLON.Tools.Error("Trying next fallback.");
  25987. this.defines = fallbacks.reduce(this.defines);
  25988. this._prepareEffect();
  25989. }
  25990. else {
  25991. if (this.onError) {
  25992. this.onError(this, this._compilationError);
  25993. }
  25994. this.onErrorObservable.notifyObservers(this);
  25995. this.onErrorObservable.clear();
  25996. // Unbind mesh reference in fallbacks
  25997. if (this._fallbacks) {
  25998. this._fallbacks.unBindMesh();
  25999. }
  26000. }
  26001. }
  26002. };
  26003. Object.defineProperty(Effect.prototype, "isSupported", {
  26004. get: function () {
  26005. return this._compilationError === "";
  26006. },
  26007. enumerable: true,
  26008. configurable: true
  26009. });
  26010. Effect.prototype._bindTexture = function (channel, texture) {
  26011. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26012. };
  26013. Effect.prototype.setTexture = function (channel, texture) {
  26014. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26015. };
  26016. Effect.prototype.setTextureArray = function (channel, textures) {
  26017. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26018. var initialPos = this._samplers.indexOf(channel);
  26019. for (var index = 1; index < textures.length; index++) {
  26020. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26021. }
  26022. }
  26023. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26024. };
  26025. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26026. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26027. };
  26028. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26029. var cache = this._valueCache[uniformName];
  26030. var flag = matrix.updateFlag;
  26031. if (cache !== undefined && cache === flag) {
  26032. return false;
  26033. }
  26034. this._valueCache[uniformName] = flag;
  26035. return true;
  26036. };
  26037. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26038. var cache = this._valueCache[uniformName];
  26039. if (!cache) {
  26040. cache = [x, y];
  26041. this._valueCache[uniformName] = cache;
  26042. return true;
  26043. }
  26044. var changed = false;
  26045. if (cache[0] !== x) {
  26046. cache[0] = x;
  26047. changed = true;
  26048. }
  26049. if (cache[1] !== y) {
  26050. cache[1] = y;
  26051. changed = true;
  26052. }
  26053. return changed;
  26054. };
  26055. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26056. var cache = this._valueCache[uniformName];
  26057. if (!cache) {
  26058. cache = [x, y, z];
  26059. this._valueCache[uniformName] = cache;
  26060. return true;
  26061. }
  26062. var changed = false;
  26063. if (cache[0] !== x) {
  26064. cache[0] = x;
  26065. changed = true;
  26066. }
  26067. if (cache[1] !== y) {
  26068. cache[1] = y;
  26069. changed = true;
  26070. }
  26071. if (cache[2] !== z) {
  26072. cache[2] = z;
  26073. changed = true;
  26074. }
  26075. return changed;
  26076. };
  26077. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26078. var cache = this._valueCache[uniformName];
  26079. if (!cache) {
  26080. cache = [x, y, z, w];
  26081. this._valueCache[uniformName] = cache;
  26082. return true;
  26083. }
  26084. var changed = false;
  26085. if (cache[0] !== x) {
  26086. cache[0] = x;
  26087. changed = true;
  26088. }
  26089. if (cache[1] !== y) {
  26090. cache[1] = y;
  26091. changed = true;
  26092. }
  26093. if (cache[2] !== z) {
  26094. cache[2] = z;
  26095. changed = true;
  26096. }
  26097. if (cache[3] !== w) {
  26098. cache[3] = w;
  26099. changed = true;
  26100. }
  26101. return changed;
  26102. };
  26103. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26104. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  26105. return;
  26106. }
  26107. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  26108. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  26109. };
  26110. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26111. this._engine.bindUniformBlock(this._program, blockName, index);
  26112. };
  26113. Effect.prototype.setIntArray = function (uniformName, array) {
  26114. this._valueCache[uniformName] = null;
  26115. this._engine.setIntArray(this.getUniform(uniformName), array);
  26116. return this;
  26117. };
  26118. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26119. this._valueCache[uniformName] = null;
  26120. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26121. return this;
  26122. };
  26123. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26124. this._valueCache[uniformName] = null;
  26125. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26126. return this;
  26127. };
  26128. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26129. this._valueCache[uniformName] = null;
  26130. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26131. return this;
  26132. };
  26133. Effect.prototype.setFloatArray = function (uniformName, array) {
  26134. this._valueCache[uniformName] = null;
  26135. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26136. return this;
  26137. };
  26138. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26139. this._valueCache[uniformName] = null;
  26140. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26141. return this;
  26142. };
  26143. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26144. this._valueCache[uniformName] = null;
  26145. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26146. return this;
  26147. };
  26148. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26149. this._valueCache[uniformName] = null;
  26150. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26151. return this;
  26152. };
  26153. Effect.prototype.setArray = function (uniformName, array) {
  26154. this._valueCache[uniformName] = null;
  26155. this._engine.setArray(this.getUniform(uniformName), array);
  26156. return this;
  26157. };
  26158. Effect.prototype.setArray2 = function (uniformName, array) {
  26159. this._valueCache[uniformName] = null;
  26160. this._engine.setArray2(this.getUniform(uniformName), array);
  26161. return this;
  26162. };
  26163. Effect.prototype.setArray3 = function (uniformName, array) {
  26164. this._valueCache[uniformName] = null;
  26165. this._engine.setArray3(this.getUniform(uniformName), array);
  26166. return this;
  26167. };
  26168. Effect.prototype.setArray4 = function (uniformName, array) {
  26169. this._valueCache[uniformName] = null;
  26170. this._engine.setArray4(this.getUniform(uniformName), array);
  26171. return this;
  26172. };
  26173. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26174. if (!matrices) {
  26175. return this;
  26176. }
  26177. this._valueCache[uniformName] = null;
  26178. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26179. return this;
  26180. };
  26181. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26182. if (this._cacheMatrix(uniformName, matrix)) {
  26183. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26184. }
  26185. return this;
  26186. };
  26187. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26188. this._valueCache[uniformName] = null;
  26189. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26190. return this;
  26191. };
  26192. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26193. this._valueCache[uniformName] = null;
  26194. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26195. return this;
  26196. };
  26197. Effect.prototype.setFloat = function (uniformName, value) {
  26198. var cache = this._valueCache[uniformName];
  26199. if (cache !== undefined && cache === value)
  26200. return this;
  26201. this._valueCache[uniformName] = value;
  26202. this._engine.setFloat(this.getUniform(uniformName), value);
  26203. return this;
  26204. };
  26205. Effect.prototype.setBool = function (uniformName, bool) {
  26206. var cache = this._valueCache[uniformName];
  26207. if (cache !== undefined && cache === bool)
  26208. return this;
  26209. this._valueCache[uniformName] = bool;
  26210. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26211. return this;
  26212. };
  26213. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26214. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26215. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26216. }
  26217. return this;
  26218. };
  26219. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26220. if (this._cacheFloat2(uniformName, x, y)) {
  26221. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26222. }
  26223. return this;
  26224. };
  26225. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26226. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26227. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26228. }
  26229. return this;
  26230. };
  26231. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26232. if (this._cacheFloat3(uniformName, x, y, z)) {
  26233. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26234. }
  26235. return this;
  26236. };
  26237. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26238. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26239. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26240. }
  26241. return this;
  26242. };
  26243. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26244. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26245. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26246. }
  26247. return this;
  26248. };
  26249. Effect.prototype.setColor3 = function (uniformName, color3) {
  26250. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26251. this._engine.setColor3(this.getUniform(uniformName), color3);
  26252. }
  26253. return this;
  26254. };
  26255. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26256. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26257. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26258. }
  26259. return this;
  26260. };
  26261. Effect.ResetCache = function () {
  26262. Effect._baseCache = {};
  26263. };
  26264. Effect._uniqueIdSeed = 0;
  26265. Effect._baseCache = {};
  26266. // Statics
  26267. Effect.ShadersStore = {};
  26268. Effect.IncludesShadersStore = {};
  26269. return Effect;
  26270. }());
  26271. BABYLON.Effect = Effect;
  26272. })(BABYLON || (BABYLON = {}));
  26273. //# sourceMappingURL=babylon.effect.js.map
  26274. var BABYLON;
  26275. (function (BABYLON) {
  26276. var MaterialHelper = /** @class */ (function () {
  26277. function MaterialHelper() {
  26278. }
  26279. MaterialHelper.BindEyePosition = function (effect, scene) {
  26280. if (scene._forcedViewPosition) {
  26281. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26282. return;
  26283. }
  26284. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26285. };
  26286. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26287. defines._needUVs = true;
  26288. defines[key] = true;
  26289. if (texture.getTextureMatrix().isIdentity(true)) {
  26290. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26291. if (texture.coordinatesIndex === 0) {
  26292. defines["MAINUV1"] = true;
  26293. }
  26294. else {
  26295. defines["MAINUV2"] = true;
  26296. }
  26297. }
  26298. else {
  26299. defines[key + "DIRECTUV"] = 0;
  26300. }
  26301. };
  26302. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26303. var matrix = texture.getTextureMatrix();
  26304. if (!matrix.isIdentity(true)) {
  26305. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26306. }
  26307. };
  26308. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26309. if (defines._areMiscDirty) {
  26310. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26311. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26312. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26313. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26314. }
  26315. };
  26316. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26317. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26318. var changed = false;
  26319. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26320. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26321. changed = true;
  26322. }
  26323. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26324. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26325. changed = true;
  26326. }
  26327. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26328. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26329. changed = true;
  26330. }
  26331. if (defines["INSTANCES"] !== useInstances) {
  26332. defines["INSTANCES"] = useInstances;
  26333. changed = true;
  26334. }
  26335. if (changed) {
  26336. defines.markAsUnprocessed();
  26337. }
  26338. };
  26339. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  26340. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26341. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26342. return false;
  26343. }
  26344. defines._normals = defines._needNormals;
  26345. defines._uvs = defines._needUVs;
  26346. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26347. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26348. defines["TANGENT"] = true;
  26349. }
  26350. if (defines._needUVs) {
  26351. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26352. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26353. }
  26354. else {
  26355. defines["UV1"] = false;
  26356. defines["UV2"] = false;
  26357. }
  26358. if (useVertexColor) {
  26359. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26360. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  26361. }
  26362. if (useBones) {
  26363. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26364. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26365. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26366. }
  26367. else {
  26368. defines["NUM_BONE_INFLUENCERS"] = 0;
  26369. defines["BonesPerMesh"] = 0;
  26370. }
  26371. }
  26372. if (useMorphTargets) {
  26373. var manager = mesh.morphTargetManager;
  26374. if (manager) {
  26375. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  26376. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  26377. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  26378. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  26379. }
  26380. else {
  26381. defines["MORPHTARGETS_TANGENT"] = false;
  26382. defines["MORPHTARGETS_NORMAL"] = false;
  26383. defines["MORPHTARGETS"] = false;
  26384. defines["NUM_MORPH_INFLUENCERS"] = 0;
  26385. }
  26386. }
  26387. return true;
  26388. };
  26389. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  26390. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26391. if (disableLighting === void 0) { disableLighting = false; }
  26392. if (!defines._areLightsDirty) {
  26393. return defines._needNormals;
  26394. }
  26395. var lightIndex = 0;
  26396. var needNormals = false;
  26397. var needRebuild = false;
  26398. var lightmapMode = false;
  26399. var shadowEnabled = false;
  26400. var specularEnabled = false;
  26401. if (scene.lightsEnabled && !disableLighting) {
  26402. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26403. var light = _a[_i];
  26404. needNormals = true;
  26405. if (defines["LIGHT" + lightIndex] === undefined) {
  26406. needRebuild = true;
  26407. }
  26408. defines["LIGHT" + lightIndex] = true;
  26409. defines["SPOTLIGHT" + lightIndex] = false;
  26410. defines["HEMILIGHT" + lightIndex] = false;
  26411. defines["POINTLIGHT" + lightIndex] = false;
  26412. defines["DIRLIGHT" + lightIndex] = false;
  26413. var type;
  26414. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  26415. type = "SPOTLIGHT" + lightIndex;
  26416. }
  26417. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  26418. type = "HEMILIGHT" + lightIndex;
  26419. }
  26420. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  26421. type = "POINTLIGHT" + lightIndex;
  26422. }
  26423. else {
  26424. type = "DIRLIGHT" + lightIndex;
  26425. }
  26426. defines[type] = true;
  26427. // Specular
  26428. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  26429. specularEnabled = true;
  26430. }
  26431. // Shadows
  26432. defines["SHADOW" + lightIndex] = false;
  26433. defines["SHADOWPCF" + lightIndex] = false;
  26434. defines["SHADOWESM" + lightIndex] = false;
  26435. defines["SHADOWCUBE" + lightIndex] = false;
  26436. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  26437. var shadowGenerator = light.getShadowGenerator();
  26438. if (shadowGenerator) {
  26439. shadowEnabled = true;
  26440. shadowGenerator.prepareDefines(defines, lightIndex);
  26441. }
  26442. }
  26443. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26444. lightmapMode = true;
  26445. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26446. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  26447. }
  26448. else {
  26449. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  26450. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  26451. }
  26452. lightIndex++;
  26453. if (lightIndex === maxSimultaneousLights)
  26454. break;
  26455. }
  26456. }
  26457. defines["SPECULARTERM"] = specularEnabled;
  26458. defines["SHADOWS"] = shadowEnabled;
  26459. // Resetting all other lights if any
  26460. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26461. if (defines["LIGHT" + index] !== undefined) {
  26462. defines["LIGHT" + index] = false;
  26463. defines["HEMILIGHT" + lightIndex] = false;
  26464. defines["POINTLIGHT" + lightIndex] = false;
  26465. defines["DIRLIGHT" + lightIndex] = false;
  26466. defines["SPOTLIGHT" + lightIndex] = false;
  26467. defines["SHADOW" + lightIndex] = false;
  26468. }
  26469. }
  26470. var caps = scene.getEngine().getCaps();
  26471. if (defines["SHADOWFLOAT"] === undefined) {
  26472. needRebuild = true;
  26473. }
  26474. defines["SHADOWFLOAT"] = shadowEnabled &&
  26475. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26476. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26477. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26478. if (needRebuild) {
  26479. defines.rebuild();
  26480. }
  26481. return needNormals;
  26482. };
  26483. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26484. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26485. var uniformsList;
  26486. var uniformBuffersList = null;
  26487. if (uniformsListOrOptions.uniformsNames) {
  26488. var options = uniformsListOrOptions;
  26489. uniformsList = options.uniformsNames;
  26490. uniformBuffersList = options.uniformBuffersNames;
  26491. samplersList = options.samplers;
  26492. defines = options.defines;
  26493. maxSimultaneousLights = options.maxSimultaneousLights;
  26494. }
  26495. else {
  26496. uniformsList = uniformsListOrOptions;
  26497. if (!samplersList) {
  26498. samplersList = [];
  26499. }
  26500. }
  26501. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26502. if (!defines["LIGHT" + lightIndex]) {
  26503. break;
  26504. }
  26505. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26506. if (uniformBuffersList) {
  26507. uniformBuffersList.push("Light" + lightIndex);
  26508. }
  26509. samplersList.push("shadowSampler" + lightIndex);
  26510. }
  26511. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26512. uniformsList.push("morphTargetInfluences");
  26513. }
  26514. };
  26515. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  26516. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26517. if (!defines["SHADOWS"]) {
  26518. return;
  26519. }
  26520. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26521. if (!defines["LIGHT" + lightIndex]) {
  26522. break;
  26523. }
  26524. if (lightIndex > 0) {
  26525. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  26526. }
  26527. if (defines["SHADOW" + lightIndex]) {
  26528. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  26529. }
  26530. if (defines["SHADOWPCF" + lightIndex]) {
  26531. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  26532. }
  26533. if (defines["SHADOWESM" + lightIndex]) {
  26534. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  26535. }
  26536. }
  26537. };
  26538. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26539. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26540. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  26541. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26542. var manager = mesh.morphTargetManager;
  26543. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  26544. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  26545. for (var index = 0; index < influencers; index++) {
  26546. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26547. if (normal) {
  26548. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26549. }
  26550. if (tangent) {
  26551. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26552. }
  26553. if (attribs.length > maxAttributesCount) {
  26554. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26555. }
  26556. }
  26557. }
  26558. };
  26559. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26560. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26561. fallbacks.addCPUSkinningFallback(0, mesh);
  26562. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26563. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26564. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26565. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26566. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26567. }
  26568. }
  26569. };
  26570. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26571. if (defines["INSTANCES"]) {
  26572. attribs.push("world0");
  26573. attribs.push("world1");
  26574. attribs.push("world2");
  26575. attribs.push("world3");
  26576. }
  26577. };
  26578. // Bindings
  26579. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26580. if (light.shadowEnabled && mesh.receiveShadows) {
  26581. var shadowGenerator = light.getShadowGenerator();
  26582. if (shadowGenerator) {
  26583. shadowGenerator.bindShadowLight(lightIndex, effect);
  26584. }
  26585. }
  26586. };
  26587. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26588. light.transferToEffect(effect, lightIndex + "");
  26589. };
  26590. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26591. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26592. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26593. var lightIndex = 0;
  26594. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26595. var light = _a[_i];
  26596. var scaledIntensity = light.getScaledIntensity();
  26597. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26598. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26599. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26600. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26601. if (defines["SPECULARTERM"]) {
  26602. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26603. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26604. }
  26605. // Shadows
  26606. if (scene.shadowsEnabled) {
  26607. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26608. }
  26609. light._uniformBuffer.update();
  26610. lightIndex++;
  26611. if (lightIndex === maxSimultaneousLights)
  26612. break;
  26613. }
  26614. };
  26615. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26616. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26617. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26618. effect.setColor3("vFogColor", scene.fogColor);
  26619. }
  26620. };
  26621. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26622. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26623. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26624. if (matrices && effect) {
  26625. effect.setMatrices("mBones", matrices);
  26626. }
  26627. }
  26628. };
  26629. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26630. var manager = abstractMesh.morphTargetManager;
  26631. if (!abstractMesh || !manager) {
  26632. return;
  26633. }
  26634. effect.setFloatArray("morphTargetInfluences", manager.influences);
  26635. };
  26636. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26637. if (defines["LOGARITHMICDEPTH"]) {
  26638. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26639. }
  26640. };
  26641. MaterialHelper.BindClipPlane = function (effect, scene) {
  26642. if (scene.clipPlane) {
  26643. var clipPlane = scene.clipPlane;
  26644. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26645. }
  26646. };
  26647. return MaterialHelper;
  26648. }());
  26649. BABYLON.MaterialHelper = MaterialHelper;
  26650. })(BABYLON || (BABYLON = {}));
  26651. //# sourceMappingURL=babylon.materialHelper.js.map
  26652. var BABYLON;
  26653. (function (BABYLON) {
  26654. var MaterialDefines = /** @class */ (function () {
  26655. function MaterialDefines() {
  26656. this._isDirty = true;
  26657. this._areLightsDirty = true;
  26658. this._areAttributesDirty = true;
  26659. this._areTexturesDirty = true;
  26660. this._areFresnelDirty = true;
  26661. this._areMiscDirty = true;
  26662. this._areImageProcessingDirty = true;
  26663. this._normals = false;
  26664. this._uvs = false;
  26665. this._needNormals = false;
  26666. this._needUVs = false;
  26667. }
  26668. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26669. get: function () {
  26670. return this._isDirty;
  26671. },
  26672. enumerable: true,
  26673. configurable: true
  26674. });
  26675. MaterialDefines.prototype.markAsProcessed = function () {
  26676. this._isDirty = false;
  26677. this._areAttributesDirty = false;
  26678. this._areTexturesDirty = false;
  26679. this._areFresnelDirty = false;
  26680. this._areLightsDirty = false;
  26681. this._areMiscDirty = false;
  26682. this._areImageProcessingDirty = false;
  26683. };
  26684. MaterialDefines.prototype.markAsUnprocessed = function () {
  26685. this._isDirty = true;
  26686. };
  26687. MaterialDefines.prototype.markAllAsDirty = function () {
  26688. this._areTexturesDirty = true;
  26689. this._areAttributesDirty = true;
  26690. this._areLightsDirty = true;
  26691. this._areFresnelDirty = true;
  26692. this._areMiscDirty = true;
  26693. this._areImageProcessingDirty = true;
  26694. this._isDirty = true;
  26695. };
  26696. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  26697. this._areImageProcessingDirty = true;
  26698. this._isDirty = true;
  26699. };
  26700. MaterialDefines.prototype.markAsLightDirty = function () {
  26701. this._areLightsDirty = true;
  26702. this._isDirty = true;
  26703. };
  26704. MaterialDefines.prototype.markAsAttributesDirty = function () {
  26705. this._areAttributesDirty = true;
  26706. this._isDirty = true;
  26707. };
  26708. MaterialDefines.prototype.markAsTexturesDirty = function () {
  26709. this._areTexturesDirty = true;
  26710. this._isDirty = true;
  26711. };
  26712. MaterialDefines.prototype.markAsFresnelDirty = function () {
  26713. this._areFresnelDirty = true;
  26714. this._isDirty = true;
  26715. };
  26716. MaterialDefines.prototype.markAsMiscDirty = function () {
  26717. this._areMiscDirty = true;
  26718. this._isDirty = true;
  26719. };
  26720. MaterialDefines.prototype.rebuild = function () {
  26721. if (this._keys) {
  26722. delete this._keys;
  26723. }
  26724. this._keys = [];
  26725. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  26726. var key = _a[_i];
  26727. if (key[0] === "_") {
  26728. continue;
  26729. }
  26730. this._keys.push(key);
  26731. }
  26732. };
  26733. MaterialDefines.prototype.isEqual = function (other) {
  26734. if (this._keys.length !== other._keys.length) {
  26735. return false;
  26736. }
  26737. for (var index = 0; index < this._keys.length; index++) {
  26738. var prop = this._keys[index];
  26739. if (this[prop] !== other[prop]) {
  26740. return false;
  26741. }
  26742. }
  26743. return true;
  26744. };
  26745. MaterialDefines.prototype.cloneTo = function (other) {
  26746. if (this._keys.length !== other._keys.length) {
  26747. other._keys = this._keys.slice(0);
  26748. }
  26749. for (var index = 0; index < this._keys.length; index++) {
  26750. var prop = this._keys[index];
  26751. other[prop] = this[prop];
  26752. }
  26753. };
  26754. MaterialDefines.prototype.reset = function () {
  26755. for (var index = 0; index < this._keys.length; index++) {
  26756. var prop = this._keys[index];
  26757. if (typeof (this[prop]) === "number") {
  26758. this[prop] = 0;
  26759. }
  26760. else {
  26761. this[prop] = false;
  26762. }
  26763. }
  26764. };
  26765. MaterialDefines.prototype.toString = function () {
  26766. var result = "";
  26767. for (var index = 0; index < this._keys.length; index++) {
  26768. var prop = this._keys[index];
  26769. var value = this[prop];
  26770. if (typeof (value) === "number") {
  26771. result += "#define " + prop + " " + this[prop] + "\n";
  26772. }
  26773. else if (value) {
  26774. result += "#define " + prop + "\n";
  26775. }
  26776. }
  26777. return result;
  26778. };
  26779. return MaterialDefines;
  26780. }());
  26781. BABYLON.MaterialDefines = MaterialDefines;
  26782. var Material = /** @class */ (function () {
  26783. function Material(name, scene, doNotAdd) {
  26784. this.checkReadyOnEveryCall = false;
  26785. this.checkReadyOnlyOnce = false;
  26786. this.state = "";
  26787. this.alpha = 1.0;
  26788. this._backFaceCulling = true;
  26789. this.doNotSerialize = false;
  26790. this.storeEffectOnSubMeshes = false;
  26791. /**
  26792. * An event triggered when the material is disposed.
  26793. * @type {BABYLON.Observable}
  26794. */
  26795. this.onDisposeObservable = new BABYLON.Observable();
  26796. /**
  26797. * An event triggered when the material is bound.
  26798. * @type {BABYLON.Observable}
  26799. */
  26800. this.onBindObservable = new BABYLON.Observable();
  26801. /**
  26802. * An event triggered when the material is unbound.
  26803. * @type {BABYLON.Observable}
  26804. */
  26805. this.onUnBindObservable = new BABYLON.Observable();
  26806. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26807. this._needDepthPrePass = false;
  26808. this.disableDepthWrite = false;
  26809. this.forceDepthWrite = false;
  26810. this.separateCullingPass = false;
  26811. this._fogEnabled = true;
  26812. this.pointSize = 1.0;
  26813. this.zOffset = 0;
  26814. this._wasPreviouslyReady = false;
  26815. this._fillMode = Material.TriangleFillMode;
  26816. this.name = name;
  26817. this.id = name || BABYLON.Tools.RandomId();
  26818. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26819. if (this._scene.useRightHandedSystem) {
  26820. this.sideOrientation = Material.ClockWiseSideOrientation;
  26821. }
  26822. else {
  26823. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26824. }
  26825. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  26826. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  26827. if (!doNotAdd) {
  26828. this._scene.materials.push(this);
  26829. }
  26830. }
  26831. Object.defineProperty(Material, "TriangleFillMode", {
  26832. get: function () {
  26833. return Material._TriangleFillMode;
  26834. },
  26835. enumerable: true,
  26836. configurable: true
  26837. });
  26838. Object.defineProperty(Material, "WireFrameFillMode", {
  26839. get: function () {
  26840. return Material._WireFrameFillMode;
  26841. },
  26842. enumerable: true,
  26843. configurable: true
  26844. });
  26845. Object.defineProperty(Material, "PointFillMode", {
  26846. get: function () {
  26847. return Material._PointFillMode;
  26848. },
  26849. enumerable: true,
  26850. configurable: true
  26851. });
  26852. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26853. get: function () {
  26854. return Material._ClockWiseSideOrientation;
  26855. },
  26856. enumerable: true,
  26857. configurable: true
  26858. });
  26859. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26860. get: function () {
  26861. return Material._CounterClockWiseSideOrientation;
  26862. },
  26863. enumerable: true,
  26864. configurable: true
  26865. });
  26866. Object.defineProperty(Material, "TextureDirtyFlag", {
  26867. get: function () {
  26868. return Material._TextureDirtyFlag;
  26869. },
  26870. enumerable: true,
  26871. configurable: true
  26872. });
  26873. Object.defineProperty(Material, "LightDirtyFlag", {
  26874. get: function () {
  26875. return Material._LightDirtyFlag;
  26876. },
  26877. enumerable: true,
  26878. configurable: true
  26879. });
  26880. Object.defineProperty(Material, "FresnelDirtyFlag", {
  26881. get: function () {
  26882. return Material._FresnelDirtyFlag;
  26883. },
  26884. enumerable: true,
  26885. configurable: true
  26886. });
  26887. Object.defineProperty(Material, "AttributesDirtyFlag", {
  26888. get: function () {
  26889. return Material._AttributesDirtyFlag;
  26890. },
  26891. enumerable: true,
  26892. configurable: true
  26893. });
  26894. Object.defineProperty(Material, "MiscDirtyFlag", {
  26895. get: function () {
  26896. return Material._MiscDirtyFlag;
  26897. },
  26898. enumerable: true,
  26899. configurable: true
  26900. });
  26901. Object.defineProperty(Material.prototype, "backFaceCulling", {
  26902. get: function () {
  26903. return this._backFaceCulling;
  26904. },
  26905. set: function (value) {
  26906. if (this._backFaceCulling === value) {
  26907. return;
  26908. }
  26909. this._backFaceCulling = value;
  26910. this.markAsDirty(Material.TextureDirtyFlag);
  26911. },
  26912. enumerable: true,
  26913. configurable: true
  26914. });
  26915. Object.defineProperty(Material.prototype, "onDispose", {
  26916. set: function (callback) {
  26917. if (this._onDisposeObserver) {
  26918. this.onDisposeObservable.remove(this._onDisposeObserver);
  26919. }
  26920. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26921. },
  26922. enumerable: true,
  26923. configurable: true
  26924. });
  26925. Object.defineProperty(Material.prototype, "onBind", {
  26926. set: function (callback) {
  26927. if (this._onBindObserver) {
  26928. this.onBindObservable.remove(this._onBindObserver);
  26929. }
  26930. this._onBindObserver = this.onBindObservable.add(callback);
  26931. },
  26932. enumerable: true,
  26933. configurable: true
  26934. });
  26935. Object.defineProperty(Material.prototype, "alphaMode", {
  26936. get: function () {
  26937. return this._alphaMode;
  26938. },
  26939. set: function (value) {
  26940. if (this._alphaMode === value) {
  26941. return;
  26942. }
  26943. this._alphaMode = value;
  26944. this.markAsDirty(Material.TextureDirtyFlag);
  26945. },
  26946. enumerable: true,
  26947. configurable: true
  26948. });
  26949. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  26950. get: function () {
  26951. return this._needDepthPrePass;
  26952. },
  26953. set: function (value) {
  26954. if (this._needDepthPrePass === value) {
  26955. return;
  26956. }
  26957. this._needDepthPrePass = value;
  26958. if (this._needDepthPrePass) {
  26959. this.checkReadyOnEveryCall = true;
  26960. }
  26961. },
  26962. enumerable: true,
  26963. configurable: true
  26964. });
  26965. Object.defineProperty(Material.prototype, "fogEnabled", {
  26966. get: function () {
  26967. return this._fogEnabled;
  26968. },
  26969. set: function (value) {
  26970. if (this._fogEnabled === value) {
  26971. return;
  26972. }
  26973. this._fogEnabled = value;
  26974. this.markAsDirty(Material.MiscDirtyFlag);
  26975. },
  26976. enumerable: true,
  26977. configurable: true
  26978. });
  26979. Object.defineProperty(Material.prototype, "wireframe", {
  26980. get: function () {
  26981. return this._fillMode === Material.WireFrameFillMode;
  26982. },
  26983. set: function (value) {
  26984. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26985. },
  26986. enumerable: true,
  26987. configurable: true
  26988. });
  26989. Object.defineProperty(Material.prototype, "pointsCloud", {
  26990. get: function () {
  26991. return this._fillMode === Material.PointFillMode;
  26992. },
  26993. set: function (value) {
  26994. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26995. },
  26996. enumerable: true,
  26997. configurable: true
  26998. });
  26999. Object.defineProperty(Material.prototype, "fillMode", {
  27000. get: function () {
  27001. return this._fillMode;
  27002. },
  27003. set: function (value) {
  27004. if (this._fillMode === value) {
  27005. return;
  27006. }
  27007. this._fillMode = value;
  27008. this.markAsDirty(Material.MiscDirtyFlag);
  27009. },
  27010. enumerable: true,
  27011. configurable: true
  27012. });
  27013. /**
  27014. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27015. * subclasses should override adding information pertainent to themselves
  27016. */
  27017. Material.prototype.toString = function (fullDetails) {
  27018. var ret = "Name: " + this.name;
  27019. if (fullDetails) {
  27020. }
  27021. return ret;
  27022. };
  27023. /**
  27024. * Child classes can use it to update shaders
  27025. */
  27026. Material.prototype.getClassName = function () {
  27027. return "Material";
  27028. };
  27029. Object.defineProperty(Material.prototype, "isFrozen", {
  27030. get: function () {
  27031. return this.checkReadyOnlyOnce;
  27032. },
  27033. enumerable: true,
  27034. configurable: true
  27035. });
  27036. Material.prototype.freeze = function () {
  27037. this.checkReadyOnlyOnce = true;
  27038. };
  27039. Material.prototype.unfreeze = function () {
  27040. this.checkReadyOnlyOnce = false;
  27041. };
  27042. Material.prototype.isReady = function (mesh, useInstances) {
  27043. return true;
  27044. };
  27045. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27046. return false;
  27047. };
  27048. Material.prototype.getEffect = function () {
  27049. return this._effect;
  27050. };
  27051. Material.prototype.getScene = function () {
  27052. return this._scene;
  27053. };
  27054. Material.prototype.needAlphaBlending = function () {
  27055. return (this.alpha < 1.0);
  27056. };
  27057. Material.prototype.needAlphaTesting = function () {
  27058. return false;
  27059. };
  27060. Material.prototype.getAlphaTestTexture = function () {
  27061. return null;
  27062. };
  27063. Material.prototype.markDirty = function () {
  27064. this._wasPreviouslyReady = false;
  27065. };
  27066. Material.prototype._preBind = function (effect, overrideOrientation) {
  27067. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27068. var engine = this._scene.getEngine();
  27069. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27070. var reverse = orientation === Material.ClockWiseSideOrientation;
  27071. engine.enableEffect(effect ? effect : this._effect);
  27072. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27073. return reverse;
  27074. };
  27075. Material.prototype.bind = function (world, mesh) {
  27076. };
  27077. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27078. };
  27079. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27080. };
  27081. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27082. sceneUbo.bindToEffect(effect, "Scene");
  27083. };
  27084. Material.prototype.bindView = function (effect) {
  27085. if (!this._useUBO) {
  27086. effect.setMatrix("view", this.getScene().getViewMatrix());
  27087. }
  27088. else {
  27089. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27090. }
  27091. };
  27092. Material.prototype.bindViewProjection = function (effect) {
  27093. if (!this._useUBO) {
  27094. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27095. }
  27096. else {
  27097. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27098. }
  27099. };
  27100. Material.prototype._afterBind = function (mesh) {
  27101. this._scene._cachedMaterial = this;
  27102. if (mesh) {
  27103. this._scene._cachedVisibility = mesh.visibility;
  27104. }
  27105. else {
  27106. this._scene._cachedVisibility = 1;
  27107. }
  27108. if (mesh) {
  27109. this.onBindObservable.notifyObservers(mesh);
  27110. }
  27111. if (this.disableDepthWrite) {
  27112. var engine = this._scene.getEngine();
  27113. this._cachedDepthWriteState = engine.getDepthWrite();
  27114. engine.setDepthWrite(false);
  27115. }
  27116. };
  27117. Material.prototype.unbind = function () {
  27118. this.onUnBindObservable.notifyObservers(this);
  27119. if (this.disableDepthWrite) {
  27120. var engine = this._scene.getEngine();
  27121. engine.setDepthWrite(this._cachedDepthWriteState);
  27122. }
  27123. };
  27124. Material.prototype.getActiveTextures = function () {
  27125. return [];
  27126. };
  27127. Material.prototype.hasTexture = function (texture) {
  27128. return false;
  27129. };
  27130. Material.prototype.clone = function (name) {
  27131. return null;
  27132. };
  27133. Material.prototype.getBindedMeshes = function () {
  27134. var result = new Array();
  27135. for (var index = 0; index < this._scene.meshes.length; index++) {
  27136. var mesh = this._scene.meshes[index];
  27137. if (mesh.material === this) {
  27138. result.push(mesh);
  27139. }
  27140. }
  27141. return result;
  27142. };
  27143. /**
  27144. * Force shader compilation including textures ready check
  27145. */
  27146. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27147. var _this = this;
  27148. var subMesh = new BABYLON.BaseSubMesh();
  27149. var scene = this.getScene();
  27150. var engine = scene.getEngine();
  27151. var checkReady = function () {
  27152. if (!_this._scene || !_this._scene.getEngine()) {
  27153. return;
  27154. }
  27155. if (subMesh._materialDefines) {
  27156. subMesh._materialDefines._renderId = -1;
  27157. }
  27158. var alphaTestState = engine.getAlphaTesting();
  27159. var clipPlaneState = scene.clipPlane;
  27160. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  27161. if (options && options.clipPlane) {
  27162. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27163. }
  27164. if (_this.storeEffectOnSubMeshes) {
  27165. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27166. if (onCompiled) {
  27167. onCompiled(_this);
  27168. }
  27169. }
  27170. else {
  27171. setTimeout(checkReady, 16);
  27172. }
  27173. }
  27174. else {
  27175. if (_this.isReady(mesh)) {
  27176. if (onCompiled) {
  27177. onCompiled(_this);
  27178. }
  27179. }
  27180. else {
  27181. setTimeout(checkReady, 16);
  27182. }
  27183. }
  27184. engine.setAlphaTesting(alphaTestState);
  27185. if (options && options.clipPlane) {
  27186. scene.clipPlane = clipPlaneState;
  27187. }
  27188. };
  27189. checkReady();
  27190. };
  27191. Material.prototype.markAsDirty = function (flag) {
  27192. if (flag & Material.TextureDirtyFlag) {
  27193. this._markAllSubMeshesAsTexturesDirty();
  27194. }
  27195. if (flag & Material.LightDirtyFlag) {
  27196. this._markAllSubMeshesAsLightsDirty();
  27197. }
  27198. if (flag & Material.FresnelDirtyFlag) {
  27199. this._markAllSubMeshesAsFresnelDirty();
  27200. }
  27201. if (flag & Material.AttributesDirtyFlag) {
  27202. this._markAllSubMeshesAsAttributesDirty();
  27203. }
  27204. if (flag & Material.MiscDirtyFlag) {
  27205. this._markAllSubMeshesAsMiscDirty();
  27206. }
  27207. this.getScene().resetCachedMaterial();
  27208. };
  27209. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27210. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27211. var mesh = _a[_i];
  27212. if (!mesh.subMeshes) {
  27213. continue;
  27214. }
  27215. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27216. var subMesh = _c[_b];
  27217. if (subMesh.getMaterial() !== this) {
  27218. continue;
  27219. }
  27220. if (!subMesh._materialDefines) {
  27221. continue;
  27222. }
  27223. func(subMesh._materialDefines);
  27224. }
  27225. }
  27226. };
  27227. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27228. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27229. };
  27230. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27231. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27232. };
  27233. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27234. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27235. };
  27236. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27237. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27238. };
  27239. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27240. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27241. };
  27242. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27243. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27244. };
  27245. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27246. // Animations
  27247. this.getScene().stopAnimation(this);
  27248. // Remove from scene
  27249. var index = this._scene.materials.indexOf(this);
  27250. if (index >= 0) {
  27251. this._scene.materials.splice(index, 1);
  27252. }
  27253. // Remove from meshes
  27254. for (index = 0; index < this._scene.meshes.length; index++) {
  27255. var mesh = this._scene.meshes[index];
  27256. if (mesh.material === this) {
  27257. mesh.material = null;
  27258. if (mesh.geometry) {
  27259. var geometry = (mesh.geometry);
  27260. if (this.storeEffectOnSubMeshes) {
  27261. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27262. var subMesh = _a[_i];
  27263. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27264. if (forceDisposeEffect && subMesh._materialEffect) {
  27265. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27266. }
  27267. }
  27268. }
  27269. else {
  27270. geometry._releaseVertexArrayObject(this._effect);
  27271. }
  27272. }
  27273. }
  27274. }
  27275. this._uniformBuffer.dispose();
  27276. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27277. if (forceDisposeEffect && this._effect) {
  27278. if (!this.storeEffectOnSubMeshes) {
  27279. this._scene.getEngine()._releaseEffect(this._effect);
  27280. }
  27281. this._effect = null;
  27282. }
  27283. // Callback
  27284. this.onDisposeObservable.notifyObservers(this);
  27285. this.onDisposeObservable.clear();
  27286. this.onBindObservable.clear();
  27287. this.onUnBindObservable.clear();
  27288. };
  27289. Material.prototype.serialize = function () {
  27290. return BABYLON.SerializationHelper.Serialize(this);
  27291. };
  27292. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27293. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27294. multiMaterial.id = parsedMultiMaterial.id;
  27295. if (BABYLON.Tags) {
  27296. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27297. }
  27298. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27299. var subMatId = parsedMultiMaterial.materials[matIndex];
  27300. if (subMatId) {
  27301. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27302. }
  27303. else {
  27304. multiMaterial.subMaterials.push(null);
  27305. }
  27306. }
  27307. return multiMaterial;
  27308. };
  27309. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27310. if (!parsedMaterial.customType) {
  27311. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27312. }
  27313. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27314. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27315. if (!BABYLON.LegacyPBRMaterial) {
  27316. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27317. return;
  27318. }
  27319. }
  27320. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27321. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27322. ;
  27323. };
  27324. Material._TriangleFillMode = 0;
  27325. Material._WireFrameFillMode = 1;
  27326. Material._PointFillMode = 2;
  27327. Material._ClockWiseSideOrientation = 0;
  27328. Material._CounterClockWiseSideOrientation = 1;
  27329. Material._TextureDirtyFlag = 1;
  27330. Material._LightDirtyFlag = 2;
  27331. Material._FresnelDirtyFlag = 4;
  27332. Material._AttributesDirtyFlag = 8;
  27333. Material._MiscDirtyFlag = 16;
  27334. __decorate([
  27335. BABYLON.serialize()
  27336. ], Material.prototype, "id", void 0);
  27337. __decorate([
  27338. BABYLON.serialize()
  27339. ], Material.prototype, "name", void 0);
  27340. __decorate([
  27341. BABYLON.serialize()
  27342. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27343. __decorate([
  27344. BABYLON.serialize()
  27345. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27346. __decorate([
  27347. BABYLON.serialize()
  27348. ], Material.prototype, "state", void 0);
  27349. __decorate([
  27350. BABYLON.serialize()
  27351. ], Material.prototype, "alpha", void 0);
  27352. __decorate([
  27353. BABYLON.serialize("backFaceCulling")
  27354. ], Material.prototype, "_backFaceCulling", void 0);
  27355. __decorate([
  27356. BABYLON.serialize()
  27357. ], Material.prototype, "sideOrientation", void 0);
  27358. __decorate([
  27359. BABYLON.serialize("alphaMode")
  27360. ], Material.prototype, "_alphaMode", void 0);
  27361. __decorate([
  27362. BABYLON.serialize()
  27363. ], Material.prototype, "_needDepthPrePass", void 0);
  27364. __decorate([
  27365. BABYLON.serialize()
  27366. ], Material.prototype, "disableDepthWrite", void 0);
  27367. __decorate([
  27368. BABYLON.serialize()
  27369. ], Material.prototype, "forceDepthWrite", void 0);
  27370. __decorate([
  27371. BABYLON.serialize()
  27372. ], Material.prototype, "separateCullingPass", void 0);
  27373. __decorate([
  27374. BABYLON.serialize("fogEnabled")
  27375. ], Material.prototype, "_fogEnabled", void 0);
  27376. __decorate([
  27377. BABYLON.serialize()
  27378. ], Material.prototype, "pointSize", void 0);
  27379. __decorate([
  27380. BABYLON.serialize()
  27381. ], Material.prototype, "zOffset", void 0);
  27382. __decorate([
  27383. BABYLON.serialize()
  27384. ], Material.prototype, "wireframe", null);
  27385. __decorate([
  27386. BABYLON.serialize()
  27387. ], Material.prototype, "pointsCloud", null);
  27388. __decorate([
  27389. BABYLON.serialize()
  27390. ], Material.prototype, "fillMode", null);
  27391. return Material;
  27392. }());
  27393. BABYLON.Material = Material;
  27394. })(BABYLON || (BABYLON = {}));
  27395. //# sourceMappingURL=babylon.material.js.map
  27396. var BABYLON;
  27397. (function (BABYLON) {
  27398. var UniformBuffer = /** @class */ (function () {
  27399. /**
  27400. * Uniform buffer objects.
  27401. *
  27402. * Handles blocks of uniform on the GPU.
  27403. *
  27404. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  27405. *
  27406. * For more information, please refer to :
  27407. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  27408. */
  27409. function UniformBuffer(engine, data, dynamic) {
  27410. this._engine = engine;
  27411. this._noUBO = !engine.supportsUniformBuffers;
  27412. this._dynamic = dynamic;
  27413. this._data = data || [];
  27414. this._uniformLocations = {};
  27415. this._uniformSizes = {};
  27416. this._uniformLocationPointer = 0;
  27417. this._needSync = false;
  27418. if (this._noUBO) {
  27419. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  27420. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  27421. this.updateFloat = this._updateFloatForEffect;
  27422. this.updateFloat2 = this._updateFloat2ForEffect;
  27423. this.updateFloat3 = this._updateFloat3ForEffect;
  27424. this.updateFloat4 = this._updateFloat4ForEffect;
  27425. this.updateMatrix = this._updateMatrixForEffect;
  27426. this.updateVector3 = this._updateVector3ForEffect;
  27427. this.updateVector4 = this._updateVector4ForEffect;
  27428. this.updateColor3 = this._updateColor3ForEffect;
  27429. this.updateColor4 = this._updateColor4ForEffect;
  27430. }
  27431. else {
  27432. this._engine._uniformBuffers.push(this);
  27433. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  27434. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  27435. this.updateFloat = this._updateFloatForUniform;
  27436. this.updateFloat2 = this._updateFloat2ForUniform;
  27437. this.updateFloat3 = this._updateFloat3ForUniform;
  27438. this.updateFloat4 = this._updateFloat4ForUniform;
  27439. this.updateMatrix = this._updateMatrixForUniform;
  27440. this.updateVector3 = this._updateVector3ForUniform;
  27441. this.updateVector4 = this._updateVector4ForUniform;
  27442. this.updateColor3 = this._updateColor3ForUniform;
  27443. this.updateColor4 = this._updateColor4ForUniform;
  27444. }
  27445. }
  27446. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  27447. // Properties
  27448. /**
  27449. * Indicates if the buffer is using the WebGL2 UBO implementation,
  27450. * or just falling back on setUniformXXX calls.
  27451. */
  27452. get: function () {
  27453. return !this._noUBO;
  27454. },
  27455. enumerable: true,
  27456. configurable: true
  27457. });
  27458. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  27459. /**
  27460. * Indicates if the WebGL underlying uniform buffer is in sync
  27461. * with the javascript cache data.
  27462. */
  27463. get: function () {
  27464. return !this._needSync;
  27465. },
  27466. enumerable: true,
  27467. configurable: true
  27468. });
  27469. /**
  27470. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27471. * Also, a dynamic UniformBuffer will disable cache verification and always
  27472. * update the underlying WebGL uniform buffer to the GPU.
  27473. */
  27474. UniformBuffer.prototype.isDynamic = function () {
  27475. return this._dynamic !== undefined;
  27476. };
  27477. /**
  27478. * The data cache on JS side.
  27479. */
  27480. UniformBuffer.prototype.getData = function () {
  27481. return this._bufferData;
  27482. };
  27483. /**
  27484. * The underlying WebGL Uniform buffer.
  27485. */
  27486. UniformBuffer.prototype.getBuffer = function () {
  27487. return this._buffer;
  27488. };
  27489. /**
  27490. * std140 layout specifies how to align data within an UBO structure.
  27491. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27492. * for specs.
  27493. */
  27494. UniformBuffer.prototype._fillAlignment = function (size) {
  27495. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27496. // and 4x4 matrices
  27497. // TODO : change if other types are used
  27498. var alignment;
  27499. if (size <= 2) {
  27500. alignment = size;
  27501. }
  27502. else {
  27503. alignment = 4;
  27504. }
  27505. if ((this._uniformLocationPointer % alignment) !== 0) {
  27506. var oldPointer = this._uniformLocationPointer;
  27507. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27508. var diff = this._uniformLocationPointer - oldPointer;
  27509. for (var i = 0; i < diff; i++) {
  27510. this._data.push(0);
  27511. }
  27512. }
  27513. };
  27514. /**
  27515. * Adds an uniform in the buffer.
  27516. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27517. * for the layout to be correct !
  27518. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27519. * @param {number|number[]} size Data size, or data directly.
  27520. */
  27521. UniformBuffer.prototype.addUniform = function (name, size) {
  27522. if (this._noUBO) {
  27523. return;
  27524. }
  27525. if (this._uniformLocations[name] !== undefined) {
  27526. // Already existing uniform
  27527. return;
  27528. }
  27529. // This function must be called in the order of the shader layout !
  27530. // size can be the size of the uniform, or data directly
  27531. var data;
  27532. if (size instanceof Array) {
  27533. data = size;
  27534. size = data.length;
  27535. }
  27536. else {
  27537. size = size;
  27538. data = [];
  27539. // Fill with zeros
  27540. for (var i = 0; i < size; i++) {
  27541. data.push(0);
  27542. }
  27543. }
  27544. this._fillAlignment(size);
  27545. this._uniformSizes[name] = size;
  27546. this._uniformLocations[name] = this._uniformLocationPointer;
  27547. this._uniformLocationPointer += size;
  27548. for (var i = 0; i < size; i++) {
  27549. this._data.push(data[i]);
  27550. }
  27551. this._needSync = true;
  27552. };
  27553. /**
  27554. * Wrapper for addUniform.
  27555. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27556. * @param {Matrix} mat A 4x4 matrix.
  27557. */
  27558. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27559. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27560. };
  27561. /**
  27562. * Wrapper for addUniform.
  27563. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27564. * @param {number} x
  27565. * @param {number} y
  27566. */
  27567. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27568. var temp = [x, y];
  27569. this.addUniform(name, temp);
  27570. };
  27571. /**
  27572. * Wrapper for addUniform.
  27573. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27574. * @param {number} x
  27575. * @param {number} y
  27576. * @param {number} z
  27577. */
  27578. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27579. var temp = [x, y, z];
  27580. this.addUniform(name, temp);
  27581. };
  27582. /**
  27583. * Wrapper for addUniform.
  27584. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27585. * @param {Color3} color
  27586. */
  27587. UniformBuffer.prototype.addColor3 = function (name, color) {
  27588. var temp = new Array();
  27589. color.toArray(temp);
  27590. this.addUniform(name, temp);
  27591. };
  27592. /**
  27593. * Wrapper for addUniform.
  27594. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27595. * @param {Color3} color
  27596. * @param {number} alpha
  27597. */
  27598. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27599. var temp = new Array();
  27600. color.toArray(temp);
  27601. temp.push(alpha);
  27602. this.addUniform(name, temp);
  27603. };
  27604. /**
  27605. * Wrapper for addUniform.
  27606. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27607. * @param {Vector3} vector
  27608. */
  27609. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27610. var temp = new Array();
  27611. vector.toArray(temp);
  27612. this.addUniform(name, temp);
  27613. };
  27614. /**
  27615. * Wrapper for addUniform.
  27616. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27617. */
  27618. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27619. this.addUniform(name, 12);
  27620. };
  27621. /**
  27622. * Wrapper for addUniform.
  27623. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27624. */
  27625. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27626. this.addUniform(name, 8);
  27627. };
  27628. /**
  27629. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27630. */
  27631. UniformBuffer.prototype.create = function () {
  27632. if (this._noUBO) {
  27633. return;
  27634. }
  27635. if (this._buffer) {
  27636. return; // nothing to do
  27637. }
  27638. // See spec, alignment must be filled as a vec4
  27639. this._fillAlignment(4);
  27640. this._bufferData = new Float32Array(this._data);
  27641. this._rebuild();
  27642. this._needSync = true;
  27643. };
  27644. UniformBuffer.prototype._rebuild = function () {
  27645. if (this._noUBO) {
  27646. return;
  27647. }
  27648. if (this._dynamic) {
  27649. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27650. }
  27651. else {
  27652. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27653. }
  27654. };
  27655. /**
  27656. * Updates the WebGL Uniform Buffer on the GPU.
  27657. * If the `dynamic` flag is set to true, no cache comparison is done.
  27658. * Otherwise, the buffer will be updated only if the cache differs.
  27659. */
  27660. UniformBuffer.prototype.update = function () {
  27661. if (!this._buffer) {
  27662. this.create();
  27663. return;
  27664. }
  27665. if (!this._dynamic && !this._needSync) {
  27666. return;
  27667. }
  27668. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27669. this._needSync = false;
  27670. };
  27671. /**
  27672. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  27673. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27674. * @param {number[]|Float32Array} data Flattened data
  27675. * @param {number} size Size of the data.
  27676. */
  27677. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  27678. var location = this._uniformLocations[uniformName];
  27679. if (location === undefined) {
  27680. if (this._buffer) {
  27681. // Cannot add an uniform if the buffer is already created
  27682. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  27683. return;
  27684. }
  27685. this.addUniform(uniformName, size);
  27686. location = this._uniformLocations[uniformName];
  27687. }
  27688. if (!this._buffer) {
  27689. this.create();
  27690. }
  27691. if (!this._dynamic) {
  27692. // Cache for static uniform buffers
  27693. var changed = false;
  27694. for (var i = 0; i < size; i++) {
  27695. if (this._bufferData[location + i] !== data[i]) {
  27696. changed = true;
  27697. this._bufferData[location + i] = data[i];
  27698. }
  27699. }
  27700. this._needSync = this._needSync || changed;
  27701. }
  27702. else {
  27703. // No cache for dynamic
  27704. for (var i = 0; i < size; i++) {
  27705. this._bufferData[location + i] = data[i];
  27706. }
  27707. }
  27708. };
  27709. // Update methods
  27710. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  27711. // To match std140, matrix must be realigned
  27712. for (var i = 0; i < 3; i++) {
  27713. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  27714. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  27715. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  27716. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27717. }
  27718. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  27719. };
  27720. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  27721. this._currentEffect.setMatrix3x3(name, matrix);
  27722. };
  27723. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  27724. this._currentEffect.setMatrix2x2(name, matrix);
  27725. };
  27726. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  27727. // To match std140, matrix must be realigned
  27728. for (var i = 0; i < 2; i++) {
  27729. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  27730. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  27731. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  27732. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27733. }
  27734. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  27735. };
  27736. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  27737. this._currentEffect.setFloat(name, x);
  27738. };
  27739. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  27740. UniformBuffer._tempBuffer[0] = x;
  27741. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  27742. };
  27743. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  27744. if (suffix === void 0) { suffix = ""; }
  27745. this._currentEffect.setFloat2(name + suffix, x, y);
  27746. };
  27747. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  27748. if (suffix === void 0) { suffix = ""; }
  27749. UniformBuffer._tempBuffer[0] = x;
  27750. UniformBuffer._tempBuffer[1] = y;
  27751. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  27752. };
  27753. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  27754. if (suffix === void 0) { suffix = ""; }
  27755. this._currentEffect.setFloat3(name + suffix, x, y, z);
  27756. };
  27757. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  27758. if (suffix === void 0) { suffix = ""; }
  27759. UniformBuffer._tempBuffer[0] = x;
  27760. UniformBuffer._tempBuffer[1] = y;
  27761. UniformBuffer._tempBuffer[2] = z;
  27762. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27763. };
  27764. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  27765. if (suffix === void 0) { suffix = ""; }
  27766. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  27767. };
  27768. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  27769. if (suffix === void 0) { suffix = ""; }
  27770. UniformBuffer._tempBuffer[0] = x;
  27771. UniformBuffer._tempBuffer[1] = y;
  27772. UniformBuffer._tempBuffer[2] = z;
  27773. UniformBuffer._tempBuffer[3] = w;
  27774. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27775. };
  27776. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  27777. this._currentEffect.setMatrix(name, mat);
  27778. };
  27779. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  27780. this.updateUniform(name, mat.toArray(), 16);
  27781. };
  27782. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  27783. this._currentEffect.setVector3(name, vector);
  27784. };
  27785. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  27786. vector.toArray(UniformBuffer._tempBuffer);
  27787. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27788. };
  27789. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  27790. this._currentEffect.setVector4(name, vector);
  27791. };
  27792. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  27793. vector.toArray(UniformBuffer._tempBuffer);
  27794. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27795. };
  27796. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  27797. if (suffix === void 0) { suffix = ""; }
  27798. this._currentEffect.setColor3(name + suffix, color);
  27799. };
  27800. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  27801. if (suffix === void 0) { suffix = ""; }
  27802. color.toArray(UniformBuffer._tempBuffer);
  27803. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27804. };
  27805. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  27806. if (suffix === void 0) { suffix = ""; }
  27807. this._currentEffect.setColor4(name + suffix, color, alpha);
  27808. };
  27809. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  27810. if (suffix === void 0) { suffix = ""; }
  27811. color.toArray(UniformBuffer._tempBuffer);
  27812. UniformBuffer._tempBuffer[3] = alpha;
  27813. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27814. };
  27815. /**
  27816. * Sets a sampler uniform on the effect.
  27817. * @param {string} name Name of the sampler.
  27818. * @param {Texture} texture
  27819. */
  27820. UniformBuffer.prototype.setTexture = function (name, texture) {
  27821. this._currentEffect.setTexture(name, texture);
  27822. };
  27823. /**
  27824. * Directly updates the value of the uniform in the cache AND on the GPU.
  27825. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27826. * @param {number[]|Float32Array} data Flattened data
  27827. */
  27828. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  27829. this.updateUniform(uniformName, data, data.length);
  27830. this.update();
  27831. };
  27832. /**
  27833. * Binds this uniform buffer to an effect.
  27834. * @param {Effect} effect
  27835. * @param {string} name Name of the uniform block in the shader.
  27836. */
  27837. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  27838. this._currentEffect = effect;
  27839. if (this._noUBO || !this._buffer) {
  27840. return;
  27841. }
  27842. effect.bindUniformBuffer(this._buffer, name);
  27843. };
  27844. /**
  27845. * Disposes the uniform buffer.
  27846. */
  27847. UniformBuffer.prototype.dispose = function () {
  27848. if (this._noUBO) {
  27849. return;
  27850. }
  27851. var index = this._engine._uniformBuffers.indexOf(this);
  27852. if (index !== -1) {
  27853. this._engine._uniformBuffers.splice(index, 1);
  27854. }
  27855. if (!this._buffer) {
  27856. return;
  27857. }
  27858. if (this._engine._releaseBuffer(this._buffer)) {
  27859. this._buffer = null;
  27860. }
  27861. };
  27862. // Pool for avoiding memory leaks
  27863. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  27864. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  27865. return UniformBuffer;
  27866. }());
  27867. BABYLON.UniformBuffer = UniformBuffer;
  27868. })(BABYLON || (BABYLON = {}));
  27869. //# sourceMappingURL=babylon.uniformBuffer.js.map
  27870. var BABYLON;
  27871. (function (BABYLON) {
  27872. var PushMaterial = /** @class */ (function (_super) {
  27873. __extends(PushMaterial, _super);
  27874. function PushMaterial(name, scene) {
  27875. var _this = _super.call(this, name, scene) || this;
  27876. _this.storeEffectOnSubMeshes = true;
  27877. return _this;
  27878. }
  27879. PushMaterial.prototype.getEffect = function () {
  27880. return this._activeEffect;
  27881. };
  27882. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  27883. if (!mesh) {
  27884. return false;
  27885. }
  27886. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27887. return true;
  27888. }
  27889. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  27890. };
  27891. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27892. this._activeEffect.setMatrix("world", world);
  27893. };
  27894. PushMaterial.prototype.bind = function (world, mesh) {
  27895. if (!mesh) {
  27896. return;
  27897. }
  27898. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  27899. };
  27900. PushMaterial.prototype._afterBind = function (mesh, effect) {
  27901. if (effect === void 0) { effect = null; }
  27902. _super.prototype._afterBind.call(this, mesh);
  27903. this.getScene()._cachedEffect = effect;
  27904. };
  27905. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  27906. if (visibility === void 0) { visibility = 1; }
  27907. return scene.isCachedMaterialInvalid(this, effect, visibility);
  27908. };
  27909. return PushMaterial;
  27910. }(BABYLON.Material));
  27911. BABYLON.PushMaterial = PushMaterial;
  27912. })(BABYLON || (BABYLON = {}));
  27913. //# sourceMappingURL=babylon.pushMaterial.js.map
  27914. var BABYLON;
  27915. (function (BABYLON) {
  27916. var VertexData = /** @class */ (function () {
  27917. function VertexData() {
  27918. }
  27919. VertexData.prototype.set = function (data, kind) {
  27920. switch (kind) {
  27921. case BABYLON.VertexBuffer.PositionKind:
  27922. this.positions = data;
  27923. break;
  27924. case BABYLON.VertexBuffer.NormalKind:
  27925. this.normals = data;
  27926. break;
  27927. case BABYLON.VertexBuffer.TangentKind:
  27928. this.tangents = data;
  27929. break;
  27930. case BABYLON.VertexBuffer.UVKind:
  27931. this.uvs = data;
  27932. break;
  27933. case BABYLON.VertexBuffer.UV2Kind:
  27934. this.uvs2 = data;
  27935. break;
  27936. case BABYLON.VertexBuffer.UV3Kind:
  27937. this.uvs3 = data;
  27938. break;
  27939. case BABYLON.VertexBuffer.UV4Kind:
  27940. this.uvs4 = data;
  27941. break;
  27942. case BABYLON.VertexBuffer.UV5Kind:
  27943. this.uvs5 = data;
  27944. break;
  27945. case BABYLON.VertexBuffer.UV6Kind:
  27946. this.uvs6 = data;
  27947. break;
  27948. case BABYLON.VertexBuffer.ColorKind:
  27949. this.colors = data;
  27950. break;
  27951. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27952. this.matricesIndices = data;
  27953. break;
  27954. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27955. this.matricesWeights = data;
  27956. break;
  27957. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27958. this.matricesIndicesExtra = data;
  27959. break;
  27960. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27961. this.matricesWeightsExtra = data;
  27962. break;
  27963. }
  27964. };
  27965. /**
  27966. * Associates the vertexData to the passed Mesh.
  27967. * Sets it as updatable or not (default `false`).
  27968. * Returns the VertexData.
  27969. */
  27970. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27971. this._applyTo(mesh, updatable);
  27972. return this;
  27973. };
  27974. /**
  27975. * Associates the vertexData to the passed Geometry.
  27976. * Sets it as updatable or not (default `false`).
  27977. * Returns the VertexData.
  27978. */
  27979. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27980. this._applyTo(geometry, updatable);
  27981. return this;
  27982. };
  27983. /**
  27984. * Updates the associated mesh.
  27985. * Returns the VertexData.
  27986. */
  27987. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27988. this._update(mesh);
  27989. return this;
  27990. };
  27991. /**
  27992. * Updates the associated geometry.
  27993. * Returns the VertexData.
  27994. */
  27995. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27996. this._update(geometry);
  27997. return this;
  27998. };
  27999. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28000. if (updatable === void 0) { updatable = false; }
  28001. if (this.positions) {
  28002. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28003. }
  28004. if (this.normals) {
  28005. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28006. }
  28007. if (this.tangents) {
  28008. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28009. }
  28010. if (this.uvs) {
  28011. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28012. }
  28013. if (this.uvs2) {
  28014. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28015. }
  28016. if (this.uvs3) {
  28017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28018. }
  28019. if (this.uvs4) {
  28020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28021. }
  28022. if (this.uvs5) {
  28023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28024. }
  28025. if (this.uvs6) {
  28026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28027. }
  28028. if (this.colors) {
  28029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28030. }
  28031. if (this.matricesIndices) {
  28032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28033. }
  28034. if (this.matricesWeights) {
  28035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28036. }
  28037. if (this.matricesIndicesExtra) {
  28038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28039. }
  28040. if (this.matricesWeightsExtra) {
  28041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28042. }
  28043. if (this.indices) {
  28044. meshOrGeometry.setIndices(this.indices, null, updatable);
  28045. }
  28046. return this;
  28047. };
  28048. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28049. if (this.positions) {
  28050. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28051. }
  28052. if (this.normals) {
  28053. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28054. }
  28055. if (this.tangents) {
  28056. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28057. }
  28058. if (this.uvs) {
  28059. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28060. }
  28061. if (this.uvs2) {
  28062. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28063. }
  28064. if (this.uvs3) {
  28065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28066. }
  28067. if (this.uvs4) {
  28068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28069. }
  28070. if (this.uvs5) {
  28071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28072. }
  28073. if (this.uvs6) {
  28074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28075. }
  28076. if (this.colors) {
  28077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28078. }
  28079. if (this.matricesIndices) {
  28080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28081. }
  28082. if (this.matricesWeights) {
  28083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28084. }
  28085. if (this.matricesIndicesExtra) {
  28086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28087. }
  28088. if (this.matricesWeightsExtra) {
  28089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28090. }
  28091. if (this.indices) {
  28092. meshOrGeometry.setIndices(this.indices, null);
  28093. }
  28094. return this;
  28095. };
  28096. /**
  28097. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28098. * Returns the VertexData.
  28099. */
  28100. VertexData.prototype.transform = function (matrix) {
  28101. var transformed = BABYLON.Vector3.Zero();
  28102. var index;
  28103. if (this.positions) {
  28104. var position = BABYLON.Vector3.Zero();
  28105. for (index = 0; index < this.positions.length; index += 3) {
  28106. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28107. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28108. this.positions[index] = transformed.x;
  28109. this.positions[index + 1] = transformed.y;
  28110. this.positions[index + 2] = transformed.z;
  28111. }
  28112. }
  28113. if (this.normals) {
  28114. var normal = BABYLON.Vector3.Zero();
  28115. for (index = 0; index < this.normals.length; index += 3) {
  28116. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28117. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28118. this.normals[index] = transformed.x;
  28119. this.normals[index + 1] = transformed.y;
  28120. this.normals[index + 2] = transformed.z;
  28121. }
  28122. }
  28123. if (this.tangents) {
  28124. var tangent = BABYLON.Vector4.Zero();
  28125. var tangentTransformed = BABYLON.Vector4.Zero();
  28126. for (index = 0; index < this.tangents.length; index += 4) {
  28127. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28128. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28129. this.tangents[index] = tangentTransformed.x;
  28130. this.tangents[index + 1] = tangentTransformed.y;
  28131. this.tangents[index + 2] = tangentTransformed.z;
  28132. this.tangents[index + 3] = tangentTransformed.w;
  28133. }
  28134. }
  28135. return this;
  28136. };
  28137. /**
  28138. * Merges the passed VertexData into the current one.
  28139. * Returns the modified VertexData.
  28140. */
  28141. VertexData.prototype.merge = function (other, options) {
  28142. options = options || {};
  28143. if (other.indices) {
  28144. if (!this.indices) {
  28145. this.indices = [];
  28146. }
  28147. var offset = this.positions ? this.positions.length / 3 : 0;
  28148. for (var index = 0; index < other.indices.length; index++) {
  28149. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28150. this.indices.push(other.indices[index] + offset);
  28151. }
  28152. }
  28153. this.positions = this._mergeElement(this.positions, other.positions);
  28154. if (!this.positions) {
  28155. return this;
  28156. }
  28157. var count = this.positions.length / 3;
  28158. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28159. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28160. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28161. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28162. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28163. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28164. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28165. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28166. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28167. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28168. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28169. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28170. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28171. return this;
  28172. };
  28173. VertexData.prototype._mergeElement = function (source, other, length) {
  28174. if (length === void 0) { length = 0; }
  28175. if (!other && !source) {
  28176. return null;
  28177. }
  28178. if (!other) {
  28179. return this._mergeElement(source, new Float32Array(source.length), length);
  28180. }
  28181. if (!source) {
  28182. if (length === 0 || length === other.length) {
  28183. return other;
  28184. }
  28185. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28186. }
  28187. var len = other.length + source.length;
  28188. var isSrcTypedArray = source instanceof Float32Array;
  28189. var isOthTypedArray = other instanceof Float32Array;
  28190. // use non-loop method when the source is Float32Array
  28191. if (isSrcTypedArray) {
  28192. var ret32 = new Float32Array(len);
  28193. ret32.set(source);
  28194. ret32.set(other, source.length);
  28195. return ret32;
  28196. // source is number[], when other is also use concat
  28197. }
  28198. else if (!isOthTypedArray) {
  28199. return source.concat(other);
  28200. // source is a number[], but other is a Float32Array, loop required
  28201. }
  28202. else {
  28203. var ret = source.slice(0); // copy source to a separate array
  28204. for (var i = 0, len = other.length; i < len; i++) {
  28205. ret.push(other[i]);
  28206. }
  28207. return ret;
  28208. }
  28209. };
  28210. /**
  28211. * Serializes the VertexData.
  28212. * Returns a serialized object.
  28213. */
  28214. VertexData.prototype.serialize = function () {
  28215. var serializationObject = this.serialize();
  28216. if (this.positions) {
  28217. serializationObject.positions = this.positions;
  28218. }
  28219. if (this.normals) {
  28220. serializationObject.normals = this.normals;
  28221. }
  28222. if (this.tangents) {
  28223. serializationObject.tangents = this.tangents;
  28224. }
  28225. if (this.uvs) {
  28226. serializationObject.uvs = this.uvs;
  28227. }
  28228. if (this.uvs2) {
  28229. serializationObject.uvs2 = this.uvs2;
  28230. }
  28231. if (this.uvs3) {
  28232. serializationObject.uvs3 = this.uvs3;
  28233. }
  28234. if (this.uvs4) {
  28235. serializationObject.uvs4 = this.uvs4;
  28236. }
  28237. if (this.uvs5) {
  28238. serializationObject.uvs5 = this.uvs5;
  28239. }
  28240. if (this.uvs6) {
  28241. serializationObject.uvs6 = this.uvs6;
  28242. }
  28243. if (this.colors) {
  28244. serializationObject.colors = this.colors;
  28245. }
  28246. if (this.matricesIndices) {
  28247. serializationObject.matricesIndices = this.matricesIndices;
  28248. serializationObject.matricesIndices._isExpanded = true;
  28249. }
  28250. if (this.matricesWeights) {
  28251. serializationObject.matricesWeights = this.matricesWeights;
  28252. }
  28253. if (this.matricesIndicesExtra) {
  28254. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28255. serializationObject.matricesIndicesExtra._isExpanded = true;
  28256. }
  28257. if (this.matricesWeightsExtra) {
  28258. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28259. }
  28260. serializationObject.indices = this.indices;
  28261. return serializationObject;
  28262. };
  28263. // Statics
  28264. /**
  28265. * Returns the object VertexData associated to the passed mesh.
  28266. */
  28267. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28268. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28269. };
  28270. /**
  28271. * Returns the object VertexData associated to the passed geometry.
  28272. */
  28273. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28274. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28275. };
  28276. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28277. var result = new VertexData();
  28278. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28279. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28280. }
  28281. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28282. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28283. }
  28284. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28285. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28286. }
  28287. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28288. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28289. }
  28290. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28291. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28292. }
  28293. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28294. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28295. }
  28296. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28297. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28298. }
  28299. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28300. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28301. }
  28302. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28303. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28304. }
  28305. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28306. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28307. }
  28308. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28309. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28310. }
  28311. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28312. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28313. }
  28314. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28315. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28316. }
  28317. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28318. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28319. }
  28320. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28321. return result;
  28322. };
  28323. /**
  28324. * Creates the vertexData of the Ribbon.
  28325. */
  28326. VertexData.CreateRibbon = function (options) {
  28327. var pathArray = options.pathArray;
  28328. var closeArray = options.closeArray || false;
  28329. var closePath = options.closePath || false;
  28330. var invertUV = options.invertUV || false;
  28331. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28332. var offset = options.offset || defaultOffset;
  28333. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28334. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28335. var customUV = options.uvs;
  28336. var customColors = options.colors;
  28337. var positions = [];
  28338. var indices = [];
  28339. var normals = [];
  28340. var uvs = [];
  28341. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28342. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28343. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28344. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28345. var minlg; // minimal length among all paths from pathArray
  28346. var lg = []; // array of path lengths : nb of vertex per path
  28347. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28348. var p; // path iterator
  28349. var i; // point iterator
  28350. var j; // point iterator
  28351. // if single path in pathArray
  28352. if (pathArray.length < 2) {
  28353. var ar1 = [];
  28354. var ar2 = [];
  28355. for (i = 0; i < pathArray[0].length - offset; i++) {
  28356. ar1.push(pathArray[0][i]);
  28357. ar2.push(pathArray[0][i + offset]);
  28358. }
  28359. pathArray = [ar1, ar2];
  28360. }
  28361. // positions and horizontal distances (u)
  28362. var idc = 0;
  28363. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  28364. var path;
  28365. var l;
  28366. minlg = pathArray[0].length;
  28367. var vectlg;
  28368. var dist;
  28369. for (p = 0; p < pathArray.length; p++) {
  28370. uTotalDistance[p] = 0;
  28371. us[p] = [0];
  28372. path = pathArray[p];
  28373. l = path.length;
  28374. minlg = (minlg < l) ? minlg : l;
  28375. j = 0;
  28376. while (j < l) {
  28377. positions.push(path[j].x, path[j].y, path[j].z);
  28378. if (j > 0) {
  28379. vectlg = path[j].subtract(path[j - 1]).length();
  28380. dist = vectlg + uTotalDistance[p];
  28381. us[p].push(dist);
  28382. uTotalDistance[p] = dist;
  28383. }
  28384. j++;
  28385. }
  28386. if (closePath) {
  28387. j--;
  28388. positions.push(path[0].x, path[0].y, path[0].z);
  28389. vectlg = path[j].subtract(path[0]).length();
  28390. dist = vectlg + uTotalDistance[p];
  28391. us[p].push(dist);
  28392. uTotalDistance[p] = dist;
  28393. }
  28394. lg[p] = l + closePathCorr;
  28395. idx[p] = idc;
  28396. idc += (l + closePathCorr);
  28397. }
  28398. // vertical distances (v)
  28399. var path1;
  28400. var path2;
  28401. var vertex1 = null;
  28402. var vertex2 = null;
  28403. for (i = 0; i < minlg + closePathCorr; i++) {
  28404. vTotalDistance[i] = 0;
  28405. vs[i] = [0];
  28406. for (p = 0; p < pathArray.length - 1; p++) {
  28407. path1 = pathArray[p];
  28408. path2 = pathArray[p + 1];
  28409. if (i === minlg) {
  28410. vertex1 = path1[0];
  28411. vertex2 = path2[0];
  28412. }
  28413. else {
  28414. vertex1 = path1[i];
  28415. vertex2 = path2[i];
  28416. }
  28417. vectlg = vertex2.subtract(vertex1).length();
  28418. dist = vectlg + vTotalDistance[i];
  28419. vs[i].push(dist);
  28420. vTotalDistance[i] = dist;
  28421. }
  28422. if (closeArray && vertex2 && vertex1) {
  28423. path1 = pathArray[p];
  28424. path2 = pathArray[0];
  28425. if (i === minlg) {
  28426. vertex2 = path2[0];
  28427. }
  28428. vectlg = vertex2.subtract(vertex1).length();
  28429. dist = vectlg + vTotalDistance[i];
  28430. vTotalDistance[i] = dist;
  28431. }
  28432. }
  28433. // uvs
  28434. var u;
  28435. var v;
  28436. if (customUV) {
  28437. for (p = 0; p < customUV.length; p++) {
  28438. uvs.push(customUV[p].x, customUV[p].y);
  28439. }
  28440. }
  28441. else {
  28442. for (p = 0; p < pathArray.length; p++) {
  28443. for (i = 0; i < minlg + closePathCorr; i++) {
  28444. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  28445. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  28446. if (invertUV) {
  28447. uvs.push(v, u);
  28448. }
  28449. else {
  28450. uvs.push(u, v);
  28451. }
  28452. }
  28453. }
  28454. }
  28455. // indices
  28456. p = 0; // path index
  28457. var pi = 0; // positions array index
  28458. var l1 = lg[p] - 1; // path1 length
  28459. var l2 = lg[p + 1] - 1; // path2 length
  28460. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28461. var shft = idx[1] - idx[0]; // shift
  28462. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28463. while (pi <= min && p < path1nb) {
  28464. // 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
  28465. indices.push(pi, pi + shft, pi + 1);
  28466. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28467. pi += 1;
  28468. if (pi === min) {
  28469. p++;
  28470. if (p === lg.length - 1) {
  28471. shft = idx[0] - idx[p];
  28472. l1 = lg[p] - 1;
  28473. l2 = lg[0] - 1;
  28474. }
  28475. else {
  28476. shft = idx[p + 1] - idx[p];
  28477. l1 = lg[p] - 1;
  28478. l2 = lg[p + 1] - 1;
  28479. }
  28480. pi = idx[p];
  28481. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28482. }
  28483. }
  28484. // normals
  28485. VertexData.ComputeNormals(positions, indices, normals);
  28486. if (closePath) {
  28487. var indexFirst = 0;
  28488. var indexLast = 0;
  28489. for (p = 0; p < pathArray.length; p++) {
  28490. indexFirst = idx[p] * 3;
  28491. if (p + 1 < pathArray.length) {
  28492. indexLast = (idx[p + 1] - 1) * 3;
  28493. }
  28494. else {
  28495. indexLast = normals.length - 3;
  28496. }
  28497. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28498. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28499. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28500. normals[indexLast] = normals[indexFirst];
  28501. normals[indexLast + 1] = normals[indexFirst + 1];
  28502. normals[indexLast + 2] = normals[indexFirst + 2];
  28503. }
  28504. }
  28505. // sides
  28506. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28507. // Colors
  28508. var colors = null;
  28509. if (customColors) {
  28510. colors = new Float32Array(customColors.length * 4);
  28511. for (var c = 0; c < customColors.length; c++) {
  28512. colors[c * 4] = customColors[c].r;
  28513. colors[c * 4 + 1] = customColors[c].g;
  28514. colors[c * 4 + 2] = customColors[c].b;
  28515. colors[c * 4 + 3] = customColors[c].a;
  28516. }
  28517. }
  28518. // Result
  28519. var vertexData = new VertexData();
  28520. var positions32 = new Float32Array(positions);
  28521. var normals32 = new Float32Array(normals);
  28522. var uvs32 = new Float32Array(uvs);
  28523. vertexData.indices = indices;
  28524. vertexData.positions = positions32;
  28525. vertexData.normals = normals32;
  28526. vertexData.uvs = uvs32;
  28527. if (colors) {
  28528. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28529. }
  28530. if (closePath) {
  28531. vertexData._idx = idx;
  28532. }
  28533. return vertexData;
  28534. };
  28535. /**
  28536. * Creates the VertexData of the Box.
  28537. */
  28538. VertexData.CreateBox = function (options) {
  28539. var normalsSource = [
  28540. new BABYLON.Vector3(0, 0, 1),
  28541. new BABYLON.Vector3(0, 0, -1),
  28542. new BABYLON.Vector3(1, 0, 0),
  28543. new BABYLON.Vector3(-1, 0, 0),
  28544. new BABYLON.Vector3(0, 1, 0),
  28545. new BABYLON.Vector3(0, -1, 0)
  28546. ];
  28547. var indices = [];
  28548. var positions = [];
  28549. var normals = [];
  28550. var uvs = [];
  28551. var width = options.width || options.size || 1;
  28552. var height = options.height || options.size || 1;
  28553. var depth = options.depth || options.size || 1;
  28554. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28555. var faceUV = options.faceUV || new Array(6);
  28556. var faceColors = options.faceColors;
  28557. var colors = [];
  28558. // default face colors and UV if undefined
  28559. for (var f = 0; f < 6; f++) {
  28560. if (faceUV[f] === undefined) {
  28561. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28562. }
  28563. if (faceColors && faceColors[f] === undefined) {
  28564. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28565. }
  28566. }
  28567. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28568. // Create each face in turn.
  28569. for (var index = 0; index < normalsSource.length; index++) {
  28570. var normal = normalsSource[index];
  28571. // Get two vectors perpendicular to the face normal and to each other.
  28572. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28573. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28574. // Six indices (two triangles) per face.
  28575. var verticesLength = positions.length / 3;
  28576. indices.push(verticesLength);
  28577. indices.push(verticesLength + 1);
  28578. indices.push(verticesLength + 2);
  28579. indices.push(verticesLength);
  28580. indices.push(verticesLength + 2);
  28581. indices.push(verticesLength + 3);
  28582. // Four vertices per face.
  28583. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28584. positions.push(vertex.x, vertex.y, vertex.z);
  28585. normals.push(normal.x, normal.y, normal.z);
  28586. uvs.push(faceUV[index].z, faceUV[index].w);
  28587. if (faceColors) {
  28588. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28589. }
  28590. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28591. positions.push(vertex.x, vertex.y, vertex.z);
  28592. normals.push(normal.x, normal.y, normal.z);
  28593. uvs.push(faceUV[index].x, faceUV[index].w);
  28594. if (faceColors) {
  28595. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28596. }
  28597. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28598. positions.push(vertex.x, vertex.y, vertex.z);
  28599. normals.push(normal.x, normal.y, normal.z);
  28600. uvs.push(faceUV[index].x, faceUV[index].y);
  28601. if (faceColors) {
  28602. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28603. }
  28604. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28605. positions.push(vertex.x, vertex.y, vertex.z);
  28606. normals.push(normal.x, normal.y, normal.z);
  28607. uvs.push(faceUV[index].z, faceUV[index].y);
  28608. if (faceColors) {
  28609. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28610. }
  28611. }
  28612. // sides
  28613. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28614. // Result
  28615. var vertexData = new VertexData();
  28616. vertexData.indices = indices;
  28617. vertexData.positions = positions;
  28618. vertexData.normals = normals;
  28619. vertexData.uvs = uvs;
  28620. if (faceColors) {
  28621. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28622. vertexData.colors = totalColors;
  28623. }
  28624. return vertexData;
  28625. };
  28626. /**
  28627. * Creates the VertexData of the Sphere.
  28628. */
  28629. VertexData.CreateSphere = function (options) {
  28630. var segments = options.segments || 32;
  28631. var diameterX = options.diameterX || options.diameter || 1;
  28632. var diameterY = options.diameterY || options.diameter || 1;
  28633. var diameterZ = options.diameterZ || options.diameter || 1;
  28634. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28635. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28636. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28637. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28638. var totalZRotationSteps = 2 + segments;
  28639. var totalYRotationSteps = 2 * totalZRotationSteps;
  28640. var indices = [];
  28641. var positions = [];
  28642. var normals = [];
  28643. var uvs = [];
  28644. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28645. var normalizedZ = zRotationStep / totalZRotationSteps;
  28646. var angleZ = normalizedZ * Math.PI * slice;
  28647. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28648. var normalizedY = yRotationStep / totalYRotationSteps;
  28649. var angleY = normalizedY * Math.PI * 2 * arc;
  28650. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28651. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28652. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28653. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28654. var vertex = complete.multiply(radius);
  28655. var normal = complete.divide(radius).normalize();
  28656. positions.push(vertex.x, vertex.y, vertex.z);
  28657. normals.push(normal.x, normal.y, normal.z);
  28658. uvs.push(normalizedY, normalizedZ);
  28659. }
  28660. if (zRotationStep > 0) {
  28661. var verticesCount = positions.length / 3;
  28662. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28663. indices.push((firstIndex));
  28664. indices.push((firstIndex + 1));
  28665. indices.push(firstIndex + totalYRotationSteps + 1);
  28666. indices.push((firstIndex + totalYRotationSteps + 1));
  28667. indices.push((firstIndex + 1));
  28668. indices.push((firstIndex + totalYRotationSteps + 2));
  28669. }
  28670. }
  28671. }
  28672. // Sides
  28673. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28674. // Result
  28675. var vertexData = new VertexData();
  28676. vertexData.indices = indices;
  28677. vertexData.positions = positions;
  28678. vertexData.normals = normals;
  28679. vertexData.uvs = uvs;
  28680. return vertexData;
  28681. };
  28682. /**
  28683. * Creates the VertexData of the Cylinder or Cone.
  28684. */
  28685. VertexData.CreateCylinder = function (options) {
  28686. var height = options.height || 2;
  28687. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28688. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  28689. var tessellation = options.tessellation || 24;
  28690. var subdivisions = options.subdivisions || 1;
  28691. var hasRings = options.hasRings ? true : false;
  28692. var enclose = options.enclose ? true : false;
  28693. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28694. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28695. var faceUV = options.faceUV || new Array(3);
  28696. var faceColors = options.faceColors;
  28697. // default face colors and UV if undefined
  28698. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28699. var ringNb = (hasRings) ? subdivisions : 1;
  28700. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28701. var f;
  28702. for (f = 0; f < surfaceNb; f++) {
  28703. if (faceColors && faceColors[f] === undefined) {
  28704. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28705. }
  28706. }
  28707. for (f = 0; f < surfaceNb; f++) {
  28708. if (faceUV && faceUV[f] === undefined) {
  28709. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28710. }
  28711. }
  28712. var indices = new Array();
  28713. var positions = new Array();
  28714. var normals = new Array();
  28715. var uvs = new Array();
  28716. var colors = new Array();
  28717. var angle_step = Math.PI * 2 * arc / tessellation;
  28718. var angle;
  28719. var h;
  28720. var radius;
  28721. var tan = (diameterBottom - diameterTop) / 2 / height;
  28722. var ringVertex = BABYLON.Vector3.Zero();
  28723. var ringNormal = BABYLON.Vector3.Zero();
  28724. var ringFirstVertex = BABYLON.Vector3.Zero();
  28725. var ringFirstNormal = BABYLON.Vector3.Zero();
  28726. var quadNormal = BABYLON.Vector3.Zero();
  28727. var Y = BABYLON.Axis.Y;
  28728. // positions, normals, uvs
  28729. var i;
  28730. var j;
  28731. var r;
  28732. var ringIdx = 1;
  28733. var s = 1; // surface index
  28734. var cs = 0;
  28735. var v = 0;
  28736. for (i = 0; i <= subdivisions; i++) {
  28737. h = i / subdivisions;
  28738. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28739. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28740. for (r = 0; r < ringIdx; r++) {
  28741. if (hasRings) {
  28742. s += r;
  28743. }
  28744. if (enclose) {
  28745. s += 2 * r;
  28746. }
  28747. for (j = 0; j <= tessellation; j++) {
  28748. angle = j * angle_step;
  28749. // position
  28750. ringVertex.x = Math.cos(-angle) * radius;
  28751. ringVertex.y = -height / 2 + h * height;
  28752. ringVertex.z = Math.sin(-angle) * radius;
  28753. // normal
  28754. if (diameterTop === 0 && i === subdivisions) {
  28755. // if no top cap, reuse former normals
  28756. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28757. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28758. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28759. }
  28760. else {
  28761. ringNormal.x = ringVertex.x;
  28762. ringNormal.z = ringVertex.z;
  28763. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28764. ringNormal.normalize();
  28765. }
  28766. // keep first ring vertex values for enclose
  28767. if (j === 0) {
  28768. ringFirstVertex.copyFrom(ringVertex);
  28769. ringFirstNormal.copyFrom(ringNormal);
  28770. }
  28771. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28772. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28773. if (hasRings) {
  28774. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28775. }
  28776. else {
  28777. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28778. }
  28779. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28780. if (faceColors) {
  28781. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28782. }
  28783. }
  28784. // if enclose, add four vertices and their dedicated normals
  28785. if (arc !== 1 && enclose) {
  28786. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28787. positions.push(0, ringVertex.y, 0);
  28788. positions.push(0, ringVertex.y, 0);
  28789. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28790. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28791. quadNormal.normalize();
  28792. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28793. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28794. quadNormal.normalize();
  28795. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28796. if (hasRings) {
  28797. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28798. }
  28799. else {
  28800. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28801. }
  28802. uvs.push(faceUV[s + 1].x, v);
  28803. uvs.push(faceUV[s + 1].z, v);
  28804. if (hasRings) {
  28805. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28806. }
  28807. else {
  28808. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28809. }
  28810. uvs.push(faceUV[s + 2].x, v);
  28811. uvs.push(faceUV[s + 2].z, v);
  28812. if (faceColors) {
  28813. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28814. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28815. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28816. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28817. }
  28818. }
  28819. if (cs !== s) {
  28820. cs = s;
  28821. }
  28822. }
  28823. }
  28824. // indices
  28825. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28826. var s;
  28827. i = 0;
  28828. for (s = 0; s < subdivisions; s++) {
  28829. var i0 = 0;
  28830. var i1 = 0;
  28831. var i2 = 0;
  28832. var i3 = 0;
  28833. for (j = 0; j < tessellation; j++) {
  28834. i0 = i * (e + 1) + j;
  28835. i1 = (i + 1) * (e + 1) + j;
  28836. i2 = i * (e + 1) + (j + 1);
  28837. i3 = (i + 1) * (e + 1) + (j + 1);
  28838. indices.push(i0, i1, i2);
  28839. indices.push(i3, i2, i1);
  28840. }
  28841. if (arc !== 1 && enclose) {
  28842. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28843. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28844. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28845. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28846. }
  28847. i = (hasRings) ? (i + 2) : (i + 1);
  28848. }
  28849. // Caps
  28850. var createCylinderCap = function (isTop) {
  28851. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28852. if (radius === 0) {
  28853. return;
  28854. }
  28855. // Cap positions, normals & uvs
  28856. var angle;
  28857. var circleVector;
  28858. var i;
  28859. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28860. var c = null;
  28861. if (faceColors) {
  28862. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28863. }
  28864. // cap center
  28865. var vbase = positions.length / 3;
  28866. var offset = isTop ? height / 2 : -height / 2;
  28867. var center = new BABYLON.Vector3(0, offset, 0);
  28868. positions.push(center.x, center.y, center.z);
  28869. normals.push(0, isTop ? 1 : -1, 0);
  28870. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28871. if (c) {
  28872. colors.push(c.r, c.g, c.b, c.a);
  28873. }
  28874. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28875. for (i = 0; i <= tessellation; i++) {
  28876. angle = Math.PI * 2 * i * arc / tessellation;
  28877. var cos = Math.cos(-angle);
  28878. var sin = Math.sin(-angle);
  28879. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28880. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28881. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28882. normals.push(0, isTop ? 1 : -1, 0);
  28883. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28884. if (c) {
  28885. colors.push(c.r, c.g, c.b, c.a);
  28886. }
  28887. }
  28888. // Cap indices
  28889. for (i = 0; i < tessellation; i++) {
  28890. if (!isTop) {
  28891. indices.push(vbase);
  28892. indices.push(vbase + (i + 1));
  28893. indices.push(vbase + (i + 2));
  28894. }
  28895. else {
  28896. indices.push(vbase);
  28897. indices.push(vbase + (i + 2));
  28898. indices.push(vbase + (i + 1));
  28899. }
  28900. }
  28901. };
  28902. // add caps to geometry
  28903. createCylinderCap(false);
  28904. createCylinderCap(true);
  28905. // Sides
  28906. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28907. var vertexData = new VertexData();
  28908. vertexData.indices = indices;
  28909. vertexData.positions = positions;
  28910. vertexData.normals = normals;
  28911. vertexData.uvs = uvs;
  28912. if (faceColors) {
  28913. vertexData.colors = colors;
  28914. }
  28915. return vertexData;
  28916. };
  28917. /**
  28918. * Creates the VertexData of the Torus.
  28919. */
  28920. VertexData.CreateTorus = function (options) {
  28921. var indices = [];
  28922. var positions = [];
  28923. var normals = [];
  28924. var uvs = [];
  28925. var diameter = options.diameter || 1;
  28926. var thickness = options.thickness || 0.5;
  28927. var tessellation = options.tessellation || 16;
  28928. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28929. var stride = tessellation + 1;
  28930. for (var i = 0; i <= tessellation; i++) {
  28931. var u = i / tessellation;
  28932. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28933. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28934. for (var j = 0; j <= tessellation; j++) {
  28935. var v = 1 - j / tessellation;
  28936. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28937. var dx = Math.cos(innerAngle);
  28938. var dy = Math.sin(innerAngle);
  28939. // Create a vertex.
  28940. var normal = new BABYLON.Vector3(dx, dy, 0);
  28941. var position = normal.scale(thickness / 2);
  28942. var textureCoordinate = new BABYLON.Vector2(u, v);
  28943. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28944. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28945. positions.push(position.x, position.y, position.z);
  28946. normals.push(normal.x, normal.y, normal.z);
  28947. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28948. // And create indices for two triangles.
  28949. var nextI = (i + 1) % stride;
  28950. var nextJ = (j + 1) % stride;
  28951. indices.push(i * stride + j);
  28952. indices.push(i * stride + nextJ);
  28953. indices.push(nextI * stride + j);
  28954. indices.push(i * stride + nextJ);
  28955. indices.push(nextI * stride + nextJ);
  28956. indices.push(nextI * stride + j);
  28957. }
  28958. }
  28959. // Sides
  28960. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28961. // Result
  28962. var vertexData = new VertexData();
  28963. vertexData.indices = indices;
  28964. vertexData.positions = positions;
  28965. vertexData.normals = normals;
  28966. vertexData.uvs = uvs;
  28967. return vertexData;
  28968. };
  28969. /**
  28970. * Creates the VertexData of the LineSystem.
  28971. */
  28972. VertexData.CreateLineSystem = function (options) {
  28973. var indices = [];
  28974. var positions = [];
  28975. var lines = options.lines;
  28976. var idx = 0;
  28977. for (var l = 0; l < lines.length; l++) {
  28978. var points = lines[l];
  28979. for (var index = 0; index < points.length; index++) {
  28980. positions.push(points[index].x, points[index].y, points[index].z);
  28981. if (index > 0) {
  28982. indices.push(idx - 1);
  28983. indices.push(idx);
  28984. }
  28985. idx++;
  28986. }
  28987. }
  28988. var vertexData = new VertexData();
  28989. vertexData.indices = indices;
  28990. vertexData.positions = positions;
  28991. return vertexData;
  28992. };
  28993. /**
  28994. * Create the VertexData of the DashedLines.
  28995. */
  28996. VertexData.CreateDashedLines = function (options) {
  28997. var dashSize = options.dashSize || 3;
  28998. var gapSize = options.gapSize || 1;
  28999. var dashNb = options.dashNb || 200;
  29000. var points = options.points;
  29001. var positions = new Array();
  29002. var indices = new Array();
  29003. var curvect = BABYLON.Vector3.Zero();
  29004. var lg = 0;
  29005. var nb = 0;
  29006. var shft = 0;
  29007. var dashshft = 0;
  29008. var curshft = 0;
  29009. var idx = 0;
  29010. var i = 0;
  29011. for (i = 0; i < points.length - 1; i++) {
  29012. points[i + 1].subtractToRef(points[i], curvect);
  29013. lg += curvect.length();
  29014. }
  29015. shft = lg / dashNb;
  29016. dashshft = dashSize * shft / (dashSize + gapSize);
  29017. for (i = 0; i < points.length - 1; i++) {
  29018. points[i + 1].subtractToRef(points[i], curvect);
  29019. nb = Math.floor(curvect.length() / shft);
  29020. curvect.normalize();
  29021. for (var j = 0; j < nb; j++) {
  29022. curshft = shft * j;
  29023. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29024. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29025. indices.push(idx, idx + 1);
  29026. idx += 2;
  29027. }
  29028. }
  29029. // Result
  29030. var vertexData = new VertexData();
  29031. vertexData.positions = positions;
  29032. vertexData.indices = indices;
  29033. return vertexData;
  29034. };
  29035. /**
  29036. * Creates the VertexData of the Ground.
  29037. */
  29038. VertexData.CreateGround = function (options) {
  29039. var indices = [];
  29040. var positions = [];
  29041. var normals = [];
  29042. var uvs = [];
  29043. var row, col;
  29044. var width = options.width || 1;
  29045. var height = options.height || 1;
  29046. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29047. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29048. for (row = 0; row <= subdivisionsY; row++) {
  29049. for (col = 0; col <= subdivisionsX; col++) {
  29050. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29051. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29052. positions.push(position.x, position.y, position.z);
  29053. normals.push(normal.x, normal.y, normal.z);
  29054. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29055. }
  29056. }
  29057. for (row = 0; row < subdivisionsY; row++) {
  29058. for (col = 0; col < subdivisionsX; col++) {
  29059. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29060. indices.push(col + 1 + row * (subdivisionsX + 1));
  29061. indices.push(col + row * (subdivisionsX + 1));
  29062. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29063. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29064. indices.push(col + row * (subdivisionsX + 1));
  29065. }
  29066. }
  29067. // Result
  29068. var vertexData = new VertexData();
  29069. vertexData.indices = indices;
  29070. vertexData.positions = positions;
  29071. vertexData.normals = normals;
  29072. vertexData.uvs = uvs;
  29073. return vertexData;
  29074. };
  29075. /**
  29076. * Creates the VertexData of the TiledGround.
  29077. */
  29078. VertexData.CreateTiledGround = function (options) {
  29079. var xmin = options.xmin || -1.0;
  29080. var zmin = options.zmin || -1.0;
  29081. var xmax = options.xmax || 1.0;
  29082. var zmax = options.zmax || 1.0;
  29083. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29084. var precision = options.precision || { w: 1, h: 1 };
  29085. var indices = new Array();
  29086. var positions = new Array();
  29087. var normals = new Array();
  29088. var uvs = new Array();
  29089. var row, col, tileRow, tileCol;
  29090. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29091. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29092. precision.w = (precision.w < 1) ? 1 : precision.w;
  29093. precision.h = (precision.h < 1) ? 1 : precision.h;
  29094. var tileSize = {
  29095. 'w': (xmax - xmin) / subdivisions.w,
  29096. 'h': (zmax - zmin) / subdivisions.h
  29097. };
  29098. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29099. // Indices
  29100. var base = positions.length / 3;
  29101. var rowLength = precision.w + 1;
  29102. for (row = 0; row < precision.h; row++) {
  29103. for (col = 0; col < precision.w; col++) {
  29104. var square = [
  29105. base + col + row * rowLength,
  29106. base + (col + 1) + row * rowLength,
  29107. base + (col + 1) + (row + 1) * rowLength,
  29108. base + col + (row + 1) * rowLength
  29109. ];
  29110. indices.push(square[1]);
  29111. indices.push(square[2]);
  29112. indices.push(square[3]);
  29113. indices.push(square[0]);
  29114. indices.push(square[1]);
  29115. indices.push(square[3]);
  29116. }
  29117. }
  29118. // Position, normals and uvs
  29119. var position = BABYLON.Vector3.Zero();
  29120. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29121. for (row = 0; row <= precision.h; row++) {
  29122. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29123. for (col = 0; col <= precision.w; col++) {
  29124. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29125. position.y = 0;
  29126. positions.push(position.x, position.y, position.z);
  29127. normals.push(normal.x, normal.y, normal.z);
  29128. uvs.push(col / precision.w, row / precision.h);
  29129. }
  29130. }
  29131. }
  29132. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29133. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29134. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  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 Ground designed from a heightmap.
  29147. */
  29148. VertexData.CreateGroundFromHeightMap = function (options) {
  29149. var indices = [];
  29150. var positions = [];
  29151. var normals = [];
  29152. var uvs = [];
  29153. var row, col;
  29154. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29155. // Vertices
  29156. for (row = 0; row <= options.subdivisions; row++) {
  29157. for (col = 0; col <= options.subdivisions; col++) {
  29158. 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));
  29159. // Compute height
  29160. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29161. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29162. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29163. var r = options.buffer[pos] / 255.0;
  29164. var g = options.buffer[pos + 1] / 255.0;
  29165. var b = options.buffer[pos + 2] / 255.0;
  29166. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29167. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29168. // Add vertex
  29169. positions.push(position.x, position.y, position.z);
  29170. normals.push(0, 0, 0);
  29171. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29172. }
  29173. }
  29174. // Indices
  29175. for (row = 0; row < options.subdivisions; row++) {
  29176. for (col = 0; col < options.subdivisions; col++) {
  29177. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29178. indices.push(col + 1 + row * (options.subdivisions + 1));
  29179. indices.push(col + row * (options.subdivisions + 1));
  29180. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29181. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29182. indices.push(col + row * (options.subdivisions + 1));
  29183. }
  29184. }
  29185. // Normals
  29186. VertexData.ComputeNormals(positions, indices, normals);
  29187. // Result
  29188. var vertexData = new VertexData();
  29189. vertexData.indices = indices;
  29190. vertexData.positions = positions;
  29191. vertexData.normals = normals;
  29192. vertexData.uvs = uvs;
  29193. return vertexData;
  29194. };
  29195. /**
  29196. * Creates the VertexData of the Plane.
  29197. */
  29198. VertexData.CreatePlane = function (options) {
  29199. var indices = [];
  29200. var positions = [];
  29201. var normals = [];
  29202. var uvs = [];
  29203. var width = options.width || options.size || 1;
  29204. var height = options.height || options.size || 1;
  29205. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29206. // Vertices
  29207. var halfWidth = width / 2.0;
  29208. var halfHeight = height / 2.0;
  29209. positions.push(-halfWidth, -halfHeight, 0);
  29210. normals.push(0, 0, -1.0);
  29211. uvs.push(0.0, 0.0);
  29212. positions.push(halfWidth, -halfHeight, 0);
  29213. normals.push(0, 0, -1.0);
  29214. uvs.push(1.0, 0.0);
  29215. positions.push(halfWidth, halfHeight, 0);
  29216. normals.push(0, 0, -1.0);
  29217. uvs.push(1.0, 1.0);
  29218. positions.push(-halfWidth, halfHeight, 0);
  29219. normals.push(0, 0, -1.0);
  29220. uvs.push(0.0, 1.0);
  29221. // Indices
  29222. indices.push(0);
  29223. indices.push(1);
  29224. indices.push(2);
  29225. indices.push(0);
  29226. indices.push(2);
  29227. indices.push(3);
  29228. // Sides
  29229. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29230. // Result
  29231. var vertexData = new VertexData();
  29232. vertexData.indices = indices;
  29233. vertexData.positions = positions;
  29234. vertexData.normals = normals;
  29235. vertexData.uvs = uvs;
  29236. return vertexData;
  29237. };
  29238. /**
  29239. * Creates the VertexData of the Disc or regular Polygon.
  29240. */
  29241. VertexData.CreateDisc = function (options) {
  29242. var positions = new Array();
  29243. var indices = new Array();
  29244. var normals = new Array();
  29245. var uvs = new Array();
  29246. var radius = options.radius || 0.5;
  29247. var tessellation = options.tessellation || 64;
  29248. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29249. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29250. // positions and uvs
  29251. positions.push(0, 0, 0); // disc center first
  29252. uvs.push(0.5, 0.5);
  29253. var theta = Math.PI * 2 * arc;
  29254. var step = theta / tessellation;
  29255. for (var a = 0; a < theta; a += step) {
  29256. var x = Math.cos(a);
  29257. var y = Math.sin(a);
  29258. var u = (x + 1) / 2;
  29259. var v = (1 - y) / 2;
  29260. positions.push(radius * x, radius * y, 0);
  29261. uvs.push(u, v);
  29262. }
  29263. if (arc === 1) {
  29264. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29265. uvs.push(uvs[2], uvs[3]);
  29266. }
  29267. //indices
  29268. var vertexNb = positions.length / 3;
  29269. for (var i = 1; i < vertexNb - 1; i++) {
  29270. indices.push(i + 1, 0, i);
  29271. }
  29272. // result
  29273. VertexData.ComputeNormals(positions, indices, normals);
  29274. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29275. var vertexData = new VertexData();
  29276. vertexData.indices = indices;
  29277. vertexData.positions = positions;
  29278. vertexData.normals = normals;
  29279. vertexData.uvs = uvs;
  29280. return vertexData;
  29281. };
  29282. /**
  29283. * Re-creates the VertexData of the Polygon for sideOrientation.
  29284. */
  29285. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29286. var faceUV = fUV || new Array(3);
  29287. var faceColors = fColors;
  29288. var colors = [];
  29289. // default face colors and UV if undefined
  29290. for (var f = 0; f < 3; f++) {
  29291. if (faceUV[f] === undefined) {
  29292. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29293. }
  29294. if (faceColors && faceColors[f] === undefined) {
  29295. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29296. }
  29297. }
  29298. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29299. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29300. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29301. var indices = polygon.getIndices();
  29302. // set face colours and textures
  29303. var idx = 0;
  29304. var face = 0;
  29305. for (var index = 0; index < normals.length; index += 3) {
  29306. //Edge Face no. 1
  29307. if (Math.abs(normals[index + 1]) < 0.001) {
  29308. face = 1;
  29309. }
  29310. //Top Face no. 0
  29311. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29312. face = 0;
  29313. }
  29314. //Bottom Face no. 2
  29315. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29316. face = 2;
  29317. }
  29318. idx = index / 3;
  29319. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29320. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29321. if (faceColors) {
  29322. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29323. }
  29324. }
  29325. // sides
  29326. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29327. // Result
  29328. var vertexData = new VertexData();
  29329. vertexData.indices = indices;
  29330. vertexData.positions = positions;
  29331. vertexData.normals = normals;
  29332. vertexData.uvs = uvs;
  29333. if (faceColors) {
  29334. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29335. vertexData.colors = totalColors;
  29336. }
  29337. return vertexData;
  29338. };
  29339. /**
  29340. * Creates the VertexData of the IcoSphere.
  29341. */
  29342. VertexData.CreateIcoSphere = function (options) {
  29343. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29344. var radius = options.radius || 1;
  29345. var flat = (options.flat === undefined) ? true : options.flat;
  29346. var subdivisions = options.subdivisions || 4;
  29347. var radiusX = options.radiusX || radius;
  29348. var radiusY = options.radiusY || radius;
  29349. var radiusZ = options.radiusZ || radius;
  29350. var t = (1 + Math.sqrt(5)) / 2;
  29351. // 12 vertex x,y,z
  29352. var ico_vertices = [
  29353. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29354. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29355. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29356. ];
  29357. // index of 3 vertex makes a face of icopshere
  29358. var ico_indices = [
  29359. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29360. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29361. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29362. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29363. ];
  29364. // vertex for uv have aliased position, not for UV
  29365. var vertices_unalias_id = [
  29366. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29367. // vertex alias
  29368. 0,
  29369. 2,
  29370. 3,
  29371. 3,
  29372. 3,
  29373. 4,
  29374. 7,
  29375. 8,
  29376. 9,
  29377. 9,
  29378. 10,
  29379. 11 // 23: B + 12
  29380. ];
  29381. // uv as integer step (not pixels !)
  29382. var ico_vertexuv = [
  29383. 5, 1, 3, 1, 6, 4, 0, 0,
  29384. 5, 3, 4, 2, 2, 2, 4, 0,
  29385. 2, 0, 1, 1, 6, 0, 6, 2,
  29386. // vertex alias (for same vertex on different faces)
  29387. 0, 4,
  29388. 3, 3,
  29389. 4, 4,
  29390. 3, 1,
  29391. 4, 2,
  29392. 4, 4,
  29393. 0, 2,
  29394. 1, 1,
  29395. 2, 2,
  29396. 3, 3,
  29397. 1, 3,
  29398. 2, 4 // 23: B + 12
  29399. ];
  29400. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29401. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29402. // First island of uv mapping
  29403. // v = 4h 3+ 2
  29404. // v = 3h 9+ 4
  29405. // v = 2h 9+ 5 B
  29406. // v = 1h 9 1 0
  29407. // v = 0h 3 8 7 A
  29408. // u = 0 1 2 3 4 5 6 *a
  29409. // Second island of uv mapping
  29410. // v = 4h 0+ B+ 4+
  29411. // v = 3h A+ 2+
  29412. // v = 2h 7+ 6 3+
  29413. // v = 1h 8+ 3+
  29414. // v = 0h
  29415. // u = 0 1 2 3 4 5 6 *a
  29416. // Face layout on texture UV mapping
  29417. // ============
  29418. // \ 4 /\ 16 / ======
  29419. // \ / \ / /\ 11 /
  29420. // \/ 7 \/ / \ /
  29421. // ======= / 10 \/
  29422. // /\ 17 /\ =======
  29423. // / \ / \ \ 15 /\
  29424. // / 8 \/ 12 \ \ / \
  29425. // ============ \/ 6 \
  29426. // \ 18 /\ ============
  29427. // \ / \ \ 5 /\ 0 /
  29428. // \/ 13 \ \ / \ /
  29429. // ======= \/ 1 \/
  29430. // =============
  29431. // /\ 19 /\ 2 /\
  29432. // / \ / \ / \
  29433. // / 14 \/ 9 \/ 3 \
  29434. // ===================
  29435. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29436. var ustep = 138 / 1024;
  29437. var vstep = 239 / 1024;
  29438. var uoffset = 60 / 1024;
  29439. var voffset = 26 / 1024;
  29440. // Second island should have margin, not to touch the first island
  29441. // avoid any borderline artefact in pixel rounding
  29442. var island_u_offset = -40 / 1024;
  29443. var island_v_offset = +20 / 1024;
  29444. // face is either island 0 or 1 :
  29445. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29446. var island = [
  29447. 0, 0, 0, 0, 1,
  29448. 0, 0, 1, 1, 0,
  29449. 0, 0, 1, 1, 0,
  29450. 0, 1, 1, 1, 0 // 15 - 19
  29451. ];
  29452. var indices = new Array();
  29453. var positions = new Array();
  29454. var normals = new Array();
  29455. var uvs = new Array();
  29456. var current_indice = 0;
  29457. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29458. var face_vertex_pos = new Array(3);
  29459. var face_vertex_uv = new Array(3);
  29460. var v012;
  29461. for (v012 = 0; v012 < 3; v012++) {
  29462. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29463. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29464. }
  29465. // create all with normals
  29466. for (var face = 0; face < 20; face++) {
  29467. // 3 vertex per face
  29468. for (v012 = 0; v012 < 3; v012++) {
  29469. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29470. var v_id = ico_indices[3 * face + v012];
  29471. // vertex have 3D position (x,y,z)
  29472. 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]);
  29473. // Normalize to get normal, then scale to radius
  29474. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29475. // uv Coordinates from vertex ID
  29476. 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);
  29477. }
  29478. // Subdivide the face (interpolate pos, norm, uv)
  29479. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29480. // - norm is linear interpolation of vertex corner normal
  29481. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29482. // - uv is linear interpolation
  29483. //
  29484. // Topology is as below for sub-divide by 2
  29485. // vertex shown as v0,v1,v2
  29486. // interp index is i1 to progress in range [v0,v1[
  29487. // interp index is i2 to progress in range [v0,v2[
  29488. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29489. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29490. //
  29491. //
  29492. // i2 v2
  29493. // ^ ^
  29494. // / / \
  29495. // / / \
  29496. // / / \
  29497. // / / (0,1) \
  29498. // / #---------\
  29499. // / / \ (0,0)'/ \
  29500. // / / \ / \
  29501. // / / \ / \
  29502. // / / (0,0) \ / (1,0) \
  29503. // / #---------#---------\
  29504. // v0 v1
  29505. //
  29506. // --------------------> i1
  29507. //
  29508. // interp of (i1,i2):
  29509. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29510. // along i1 : lerp(x0,x1, i1/(S-i2))
  29511. //
  29512. // centroid of triangle is needed to get help normal computation
  29513. // (c1,c2) are used for centroid location
  29514. var interp_vertex = function (i1, i2, c1, c2) {
  29515. // vertex is interpolated from
  29516. // - face_vertex_pos[0..2]
  29517. // - face_vertex_uv[0..2]
  29518. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29519. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29520. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29521. pos_interp.normalize();
  29522. var vertex_normal;
  29523. if (flat) {
  29524. // in flat mode, recalculate normal as face centroid normal
  29525. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29526. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29527. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29528. }
  29529. else {
  29530. // in smooth mode, recalculate normal from each single vertex position
  29531. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29532. }
  29533. // Vertex normal need correction due to X,Y,Z radius scaling
  29534. vertex_normal.x /= radiusX;
  29535. vertex_normal.y /= radiusY;
  29536. vertex_normal.z /= radiusZ;
  29537. vertex_normal.normalize();
  29538. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29539. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29540. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29541. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29542. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29543. uvs.push(uv_interp.x, uv_interp.y);
  29544. // push each vertex has member of a face
  29545. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29546. indices.push(current_indice);
  29547. current_indice++;
  29548. };
  29549. for (var i2 = 0; i2 < subdivisions; i2++) {
  29550. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29551. // face : (i1,i2) for /\ :
  29552. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29553. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29554. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29555. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29556. if (i1 + i2 + 1 < subdivisions) {
  29557. // face : (i1,i2)' for \/ :
  29558. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29559. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29560. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29561. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29562. }
  29563. }
  29564. }
  29565. }
  29566. // Sides
  29567. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29568. // Result
  29569. var vertexData = new VertexData();
  29570. vertexData.indices = indices;
  29571. vertexData.positions = positions;
  29572. vertexData.normals = normals;
  29573. vertexData.uvs = uvs;
  29574. return vertexData;
  29575. };
  29576. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29577. /**
  29578. * Creates the VertexData of the Polyhedron.
  29579. */
  29580. VertexData.CreatePolyhedron = function (options) {
  29581. // provided polyhedron types :
  29582. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29583. // 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)
  29584. var polyhedra = [];
  29585. 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]] };
  29586. 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]] };
  29587. polyhedra[2] = {
  29588. 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]],
  29589. 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]]
  29590. };
  29591. polyhedra[3] = {
  29592. 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]],
  29593. 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]]
  29594. };
  29595. polyhedra[4] = {
  29596. 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]],
  29597. 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]]
  29598. };
  29599. 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]] };
  29600. 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]] };
  29601. 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]] };
  29602. 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]] };
  29603. 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]] };
  29604. 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]] };
  29605. 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]] };
  29606. 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]] };
  29607. 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]] };
  29608. polyhedra[14] = {
  29609. 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]],
  29610. 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]]
  29611. };
  29612. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29613. var size = options.size;
  29614. var sizeX = options.sizeX || size || 1;
  29615. var sizeY = options.sizeY || size || 1;
  29616. var sizeZ = options.sizeZ || size || 1;
  29617. var data = options.custom || polyhedra[type];
  29618. var nbfaces = data.face.length;
  29619. var faceUV = options.faceUV || new Array(nbfaces);
  29620. var faceColors = options.faceColors;
  29621. var flat = (options.flat === undefined) ? true : options.flat;
  29622. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29623. var positions = new Array();
  29624. var indices = new Array();
  29625. var normals = new Array();
  29626. var uvs = new Array();
  29627. var colors = new Array();
  29628. var index = 0;
  29629. var faceIdx = 0; // face cursor in the array "indexes"
  29630. var indexes = new Array();
  29631. var i = 0;
  29632. var f = 0;
  29633. var u, v, ang, x, y, tmp;
  29634. // default face colors and UV if undefined
  29635. if (flat) {
  29636. for (f = 0; f < nbfaces; f++) {
  29637. if (faceColors && faceColors[f] === undefined) {
  29638. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29639. }
  29640. if (faceUV && faceUV[f] === undefined) {
  29641. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29642. }
  29643. }
  29644. }
  29645. if (!flat) {
  29646. for (i = 0; i < data.vertex.length; i++) {
  29647. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29648. uvs.push(0, 0);
  29649. }
  29650. for (f = 0; f < nbfaces; f++) {
  29651. for (i = 0; i < data.face[f].length - 2; i++) {
  29652. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29653. }
  29654. }
  29655. }
  29656. else {
  29657. for (f = 0; f < nbfaces; f++) {
  29658. var fl = data.face[f].length; // number of vertices of the current face
  29659. ang = 2 * Math.PI / fl;
  29660. x = 0.5 * Math.tan(ang / 2);
  29661. y = 0.5;
  29662. // positions, uvs, colors
  29663. for (i = 0; i < fl; i++) {
  29664. // positions
  29665. 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);
  29666. indexes.push(index);
  29667. index++;
  29668. // uvs
  29669. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29670. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29671. uvs.push(u, v);
  29672. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29673. y = x * Math.sin(ang) + y * Math.cos(ang);
  29674. x = tmp;
  29675. // colors
  29676. if (faceColors) {
  29677. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29678. }
  29679. }
  29680. // indices from indexes
  29681. for (i = 0; i < fl - 2; i++) {
  29682. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29683. }
  29684. faceIdx += fl;
  29685. }
  29686. }
  29687. VertexData.ComputeNormals(positions, indices, normals);
  29688. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29689. var vertexData = new VertexData();
  29690. vertexData.positions = positions;
  29691. vertexData.indices = indices;
  29692. vertexData.normals = normals;
  29693. vertexData.uvs = uvs;
  29694. if (faceColors && flat) {
  29695. vertexData.colors = colors;
  29696. }
  29697. return vertexData;
  29698. };
  29699. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29700. /**
  29701. * Creates the VertexData of the Torus Knot.
  29702. */
  29703. VertexData.CreateTorusKnot = function (options) {
  29704. var indices = new Array();
  29705. var positions = new Array();
  29706. var normals = new Array();
  29707. var uvs = new Array();
  29708. var radius = options.radius || 2;
  29709. var tube = options.tube || 0.5;
  29710. var radialSegments = options.radialSegments || 32;
  29711. var tubularSegments = options.tubularSegments || 32;
  29712. var p = options.p || 2;
  29713. var q = options.q || 3;
  29714. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29715. // Helper
  29716. var getPos = function (angle) {
  29717. var cu = Math.cos(angle);
  29718. var su = Math.sin(angle);
  29719. var quOverP = q / p * angle;
  29720. var cs = Math.cos(quOverP);
  29721. var tx = radius * (2 + cs) * 0.5 * cu;
  29722. var ty = radius * (2 + cs) * su * 0.5;
  29723. var tz = radius * Math.sin(quOverP) * 0.5;
  29724. return new BABYLON.Vector3(tx, ty, tz);
  29725. };
  29726. // Vertices
  29727. var i;
  29728. var j;
  29729. for (i = 0; i <= radialSegments; i++) {
  29730. var modI = i % radialSegments;
  29731. var u = modI / radialSegments * 2 * p * Math.PI;
  29732. var p1 = getPos(u);
  29733. var p2 = getPos(u + 0.01);
  29734. var tang = p2.subtract(p1);
  29735. var n = p2.add(p1);
  29736. var bitan = BABYLON.Vector3.Cross(tang, n);
  29737. n = BABYLON.Vector3.Cross(bitan, tang);
  29738. bitan.normalize();
  29739. n.normalize();
  29740. for (j = 0; j < tubularSegments; j++) {
  29741. var modJ = j % tubularSegments;
  29742. var v = modJ / tubularSegments * 2 * Math.PI;
  29743. var cx = -tube * Math.cos(v);
  29744. var cy = tube * Math.sin(v);
  29745. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29746. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29747. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29748. uvs.push(i / radialSegments);
  29749. uvs.push(j / tubularSegments);
  29750. }
  29751. }
  29752. for (i = 0; i < radialSegments; i++) {
  29753. for (j = 0; j < tubularSegments; j++) {
  29754. var jNext = (j + 1) % tubularSegments;
  29755. var a = i * tubularSegments + j;
  29756. var b = (i + 1) * tubularSegments + j;
  29757. var c = (i + 1) * tubularSegments + jNext;
  29758. var d = i * tubularSegments + jNext;
  29759. indices.push(d);
  29760. indices.push(b);
  29761. indices.push(a);
  29762. indices.push(d);
  29763. indices.push(c);
  29764. indices.push(b);
  29765. }
  29766. }
  29767. // Normals
  29768. VertexData.ComputeNormals(positions, indices, normals);
  29769. // Sides
  29770. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29771. // Result
  29772. var vertexData = new VertexData();
  29773. vertexData.indices = indices;
  29774. vertexData.positions = positions;
  29775. vertexData.normals = normals;
  29776. vertexData.uvs = uvs;
  29777. return vertexData;
  29778. };
  29779. // Tools
  29780. /**
  29781. * @param {any} - positions (number[] or Float32Array)
  29782. * @param {any} - indices (number[] or Uint16Array)
  29783. * @param {any} - normals (number[] or Float32Array)
  29784. * options (optional) :
  29785. * facetPositions : optional array of facet positions (vector3)
  29786. * facetNormals : optional array of facet normals (vector3)
  29787. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  29788. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  29789. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  29790. * bbSize : optional bounding box size data, required for facetPartitioning computation
  29791. * bInfo : optional bounding info, required for facetPartitioning computation
  29792. */
  29793. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  29794. // temporary scalar variables
  29795. var index = 0; // facet index
  29796. var p1p2x = 0.0; // p1p2 vector x coordinate
  29797. var p1p2y = 0.0; // p1p2 vector y coordinate
  29798. var p1p2z = 0.0; // p1p2 vector z coordinate
  29799. var p3p2x = 0.0; // p3p2 vector x coordinate
  29800. var p3p2y = 0.0; // p3p2 vector y coordinate
  29801. var p3p2z = 0.0; // p3p2 vector z coordinate
  29802. var faceNormalx = 0.0; // facet normal x coordinate
  29803. var faceNormaly = 0.0; // facet normal y coordinate
  29804. var faceNormalz = 0.0; // facet normal z coordinate
  29805. var length = 0.0; // facet normal length before normalization
  29806. var v1x = 0; // vector1 x index in the positions array
  29807. var v1y = 0; // vector1 y index in the positions array
  29808. var v1z = 0; // vector1 z index in the positions array
  29809. var v2x = 0; // vector2 x index in the positions array
  29810. var v2y = 0; // vector2 y index in the positions array
  29811. var v2z = 0; // vector2 z index in the positions array
  29812. var v3x = 0; // vector3 x index in the positions array
  29813. var v3y = 0; // vector3 y index in the positions array
  29814. var v3z = 0; // vector3 z index in the positions array
  29815. var computeFacetNormals = false;
  29816. var computeFacetPositions = false;
  29817. var computeFacetPartitioning = false;
  29818. var faceNormalSign = 1;
  29819. var ratio = 0;
  29820. if (options) {
  29821. computeFacetNormals = (options.facetNormals) ? true : false;
  29822. computeFacetPositions = (options.facetPositions) ? true : false;
  29823. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  29824. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  29825. ratio = options.ratio || 0;
  29826. }
  29827. // facetPartitioning reinit if needed
  29828. var xSubRatio = 0;
  29829. var ySubRatio = 0;
  29830. var zSubRatio = 0;
  29831. var subSq = 0;
  29832. if (computeFacetPartitioning && options && options.bbSize) {
  29833. var ox = 0; // X partitioning index for facet position
  29834. var oy = 0; // Y partinioning index for facet position
  29835. var oz = 0; // Z partinioning index for facet position
  29836. var b1x = 0; // X partitioning index for facet v1 vertex
  29837. var b1y = 0; // Y partitioning index for facet v1 vertex
  29838. var b1z = 0; // z partitioning index for facet v1 vertex
  29839. var b2x = 0; // X partitioning index for facet v2 vertex
  29840. var b2y = 0; // Y partitioning index for facet v2 vertex
  29841. var b2z = 0; // Z partitioning index for facet v2 vertex
  29842. var b3x = 0; // X partitioning index for facet v3 vertex
  29843. var b3y = 0; // Y partitioning index for facet v3 vertex
  29844. var b3z = 0; // Z partitioning index for facet v3 vertex
  29845. var block_idx_o = 0; // facet barycenter block index
  29846. var block_idx_v1 = 0; // v1 vertex block index
  29847. var block_idx_v2 = 0; // v2 vertex block index
  29848. var block_idx_v3 = 0; // v3 vertex block index
  29849. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  29850. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  29851. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  29852. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  29853. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  29854. subSq = options.subDiv.max * options.subDiv.max;
  29855. options.facetPartitioning.length = 0;
  29856. }
  29857. // reset the normals
  29858. for (index = 0; index < positions.length; index++) {
  29859. normals[index] = 0.0;
  29860. }
  29861. // Loop : 1 indice triplet = 1 facet
  29862. var nbFaces = indices.length / 3;
  29863. for (index = 0; index < nbFaces; index++) {
  29864. // get the indexes of the coordinates of each vertex of the facet
  29865. v1x = indices[index * 3] * 3;
  29866. v1y = v1x + 1;
  29867. v1z = v1x + 2;
  29868. v2x = indices[index * 3 + 1] * 3;
  29869. v2y = v2x + 1;
  29870. v2z = v2x + 2;
  29871. v3x = indices[index * 3 + 2] * 3;
  29872. v3y = v3x + 1;
  29873. v3z = v3x + 2;
  29874. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  29875. p1p2y = positions[v1y] - positions[v2y];
  29876. p1p2z = positions[v1z] - positions[v2z];
  29877. p3p2x = positions[v3x] - positions[v2x];
  29878. p3p2y = positions[v3y] - positions[v2y];
  29879. p3p2z = positions[v3z] - positions[v2z];
  29880. // compute the face normal with the cross product
  29881. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  29882. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  29883. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  29884. // normalize this normal and store it in the array facetData
  29885. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29886. length = (length === 0) ? 1.0 : length;
  29887. faceNormalx /= length;
  29888. faceNormaly /= length;
  29889. faceNormalz /= length;
  29890. if (computeFacetNormals && options) {
  29891. options.facetNormals[index].x = faceNormalx;
  29892. options.facetNormals[index].y = faceNormaly;
  29893. options.facetNormals[index].z = faceNormalz;
  29894. }
  29895. if (computeFacetPositions && options) {
  29896. // compute and the facet barycenter coordinates in the array facetPositions
  29897. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  29898. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  29899. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  29900. }
  29901. if (computeFacetPartitioning && options) {
  29902. // store the facet indexes in arrays in the main facetPartitioning array :
  29903. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  29904. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  29905. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  29906. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  29907. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29908. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29909. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29910. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29911. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29912. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29913. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29914. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29915. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29916. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  29917. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  29918. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  29919. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  29920. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  29921. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  29922. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  29923. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  29924. // push each facet index in each block containing the vertex
  29925. options.facetPartitioning[block_idx_v1].push(index);
  29926. if (block_idx_v2 != block_idx_v1) {
  29927. options.facetPartitioning[block_idx_v2].push(index);
  29928. }
  29929. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  29930. options.facetPartitioning[block_idx_v3].push(index);
  29931. }
  29932. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  29933. options.facetPartitioning[block_idx_o].push(index);
  29934. }
  29935. }
  29936. // compute the normals anyway
  29937. normals[v1x] += faceNormalx; // accumulate all the normals per face
  29938. normals[v1y] += faceNormaly;
  29939. normals[v1z] += faceNormalz;
  29940. normals[v2x] += faceNormalx;
  29941. normals[v2y] += faceNormaly;
  29942. normals[v2z] += faceNormalz;
  29943. normals[v3x] += faceNormalx;
  29944. normals[v3y] += faceNormaly;
  29945. normals[v3z] += faceNormalz;
  29946. }
  29947. // last normalization of each normal
  29948. for (index = 0; index < normals.length / 3; index++) {
  29949. faceNormalx = normals[index * 3];
  29950. faceNormaly = normals[index * 3 + 1];
  29951. faceNormalz = normals[index * 3 + 2];
  29952. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29953. length = (length === 0) ? 1.0 : length;
  29954. faceNormalx /= length;
  29955. faceNormaly /= length;
  29956. faceNormalz /= length;
  29957. normals[index * 3] = faceNormalx;
  29958. normals[index * 3 + 1] = faceNormaly;
  29959. normals[index * 3 + 2] = faceNormalz;
  29960. }
  29961. };
  29962. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  29963. var li = indices.length;
  29964. var ln = normals.length;
  29965. var i;
  29966. var n;
  29967. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29968. switch (sideOrientation) {
  29969. case BABYLON.Mesh.FRONTSIDE:
  29970. // nothing changed
  29971. break;
  29972. case BABYLON.Mesh.BACKSIDE:
  29973. var tmp;
  29974. // indices
  29975. for (i = 0; i < li; i += 3) {
  29976. tmp = indices[i];
  29977. indices[i] = indices[i + 2];
  29978. indices[i + 2] = tmp;
  29979. }
  29980. // normals
  29981. for (n = 0; n < ln; n++) {
  29982. normals[n] = -normals[n];
  29983. }
  29984. break;
  29985. case BABYLON.Mesh.DOUBLESIDE:
  29986. // positions
  29987. var lp = positions.length;
  29988. var l = lp / 3;
  29989. for (var p = 0; p < lp; p++) {
  29990. positions[lp + p] = positions[p];
  29991. }
  29992. // indices
  29993. for (i = 0; i < li; i += 3) {
  29994. indices[i + li] = indices[i + 2] + l;
  29995. indices[i + 1 + li] = indices[i + 1] + l;
  29996. indices[i + 2 + li] = indices[i] + l;
  29997. }
  29998. // normals
  29999. for (n = 0; n < ln; n++) {
  30000. normals[ln + n] = -normals[n];
  30001. }
  30002. // uvs
  30003. var lu = uvs.length;
  30004. var u = 0;
  30005. for (u = 0; u < lu; u++) {
  30006. uvs[u + lu] = uvs[u];
  30007. }
  30008. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30009. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30010. u = 0;
  30011. for (i = 0; i < lu / 2; i++) {
  30012. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30013. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30014. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30015. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30016. u += 2;
  30017. }
  30018. break;
  30019. }
  30020. };
  30021. /**
  30022. * Creates a new VertexData from the imported parameters.
  30023. */
  30024. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30025. var vertexData = new VertexData();
  30026. // positions
  30027. var positions = parsedVertexData.positions;
  30028. if (positions) {
  30029. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30030. }
  30031. // normals
  30032. var normals = parsedVertexData.normals;
  30033. if (normals) {
  30034. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30035. }
  30036. // tangents
  30037. var tangents = parsedVertexData.tangents;
  30038. if (tangents) {
  30039. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30040. }
  30041. // uvs
  30042. var uvs = parsedVertexData.uvs;
  30043. if (uvs) {
  30044. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30045. }
  30046. // uv2s
  30047. var uv2s = parsedVertexData.uv2s;
  30048. if (uv2s) {
  30049. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30050. }
  30051. // uv3s
  30052. var uv3s = parsedVertexData.uv3s;
  30053. if (uv3s) {
  30054. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30055. }
  30056. // uv4s
  30057. var uv4s = parsedVertexData.uv4s;
  30058. if (uv4s) {
  30059. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30060. }
  30061. // uv5s
  30062. var uv5s = parsedVertexData.uv5s;
  30063. if (uv5s) {
  30064. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30065. }
  30066. // uv6s
  30067. var uv6s = parsedVertexData.uv6s;
  30068. if (uv6s) {
  30069. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30070. }
  30071. // colors
  30072. var colors = parsedVertexData.colors;
  30073. if (colors) {
  30074. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30075. }
  30076. // matricesIndices
  30077. var matricesIndices = parsedVertexData.matricesIndices;
  30078. if (matricesIndices) {
  30079. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30080. }
  30081. // matricesWeights
  30082. var matricesWeights = parsedVertexData.matricesWeights;
  30083. if (matricesWeights) {
  30084. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30085. }
  30086. // indices
  30087. var indices = parsedVertexData.indices;
  30088. if (indices) {
  30089. vertexData.indices = indices;
  30090. }
  30091. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30092. };
  30093. return VertexData;
  30094. }());
  30095. BABYLON.VertexData = VertexData;
  30096. })(BABYLON || (BABYLON = {}));
  30097. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30098. var BABYLON;
  30099. (function (BABYLON) {
  30100. var Geometry = /** @class */ (function () {
  30101. function Geometry(id, scene, vertexData, updatable, mesh) {
  30102. if (updatable === void 0) { updatable = false; }
  30103. if (mesh === void 0) { mesh = null; }
  30104. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30105. this._totalVertices = 0;
  30106. this._isDisposed = false;
  30107. this._indexBufferIsUpdatable = false;
  30108. this.id = id;
  30109. this._engine = scene.getEngine();
  30110. this._meshes = [];
  30111. this._scene = scene;
  30112. //Init vertex buffer cache
  30113. this._vertexBuffers = {};
  30114. this._indices = [];
  30115. this._updatable = updatable;
  30116. // vertexData
  30117. if (vertexData) {
  30118. this.setAllVerticesData(vertexData, updatable);
  30119. }
  30120. else {
  30121. this._totalVertices = 0;
  30122. this._indices = [];
  30123. }
  30124. if (this._engine.getCaps().vertexArrayObject) {
  30125. this._vertexArrayObjects = {};
  30126. }
  30127. // applyToMesh
  30128. if (mesh) {
  30129. if (mesh.getClassName() === "LinesMesh") {
  30130. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30131. this.updateExtend();
  30132. }
  30133. this.applyToMesh(mesh);
  30134. mesh.computeWorldMatrix(true);
  30135. }
  30136. }
  30137. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30138. /**
  30139. * 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
  30140. * @returns The Bias Vector
  30141. */
  30142. get: function () {
  30143. return this._boundingBias;
  30144. },
  30145. set: function (value) {
  30146. if (this._boundingBias && this._boundingBias.equals(value)) {
  30147. return;
  30148. }
  30149. this._boundingBias = value.clone();
  30150. this.updateBoundingInfo(true, null);
  30151. },
  30152. enumerable: true,
  30153. configurable: true
  30154. });
  30155. Geometry.CreateGeometryForMesh = function (mesh) {
  30156. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30157. geometry.applyToMesh(mesh);
  30158. return geometry;
  30159. };
  30160. Object.defineProperty(Geometry.prototype, "extend", {
  30161. get: function () {
  30162. return this._extend;
  30163. },
  30164. enumerable: true,
  30165. configurable: true
  30166. });
  30167. Geometry.prototype.getScene = function () {
  30168. return this._scene;
  30169. };
  30170. Geometry.prototype.getEngine = function () {
  30171. return this._engine;
  30172. };
  30173. Geometry.prototype.isReady = function () {
  30174. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30175. };
  30176. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30177. get: function () {
  30178. for (var index = 0; index < this._meshes.length; index++) {
  30179. if (!this._meshes[index].doNotSerialize) {
  30180. return false;
  30181. }
  30182. }
  30183. return true;
  30184. },
  30185. enumerable: true,
  30186. configurable: true
  30187. });
  30188. Geometry.prototype._rebuild = function () {
  30189. if (this._vertexArrayObjects) {
  30190. this._vertexArrayObjects = {};
  30191. }
  30192. // Index buffer
  30193. if (this._meshes.length !== 0 && this._indices) {
  30194. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30195. }
  30196. // Vertex buffers
  30197. for (var key in this._vertexBuffers) {
  30198. var vertexBuffer = this._vertexBuffers[key];
  30199. vertexBuffer._rebuild();
  30200. }
  30201. };
  30202. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30203. vertexData.applyToGeometry(this, updatable);
  30204. this.notifyUpdate();
  30205. };
  30206. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30207. if (updatable === void 0) { updatable = false; }
  30208. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30209. this.setVerticesBuffer(buffer);
  30210. };
  30211. Geometry.prototype.removeVerticesData = function (kind) {
  30212. if (this._vertexBuffers[kind]) {
  30213. this._vertexBuffers[kind].dispose();
  30214. delete this._vertexBuffers[kind];
  30215. }
  30216. };
  30217. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30218. var kind = buffer.getKind();
  30219. if (this._vertexBuffers[kind]) {
  30220. this._vertexBuffers[kind].dispose();
  30221. }
  30222. this._vertexBuffers[kind] = buffer;
  30223. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30224. var data = buffer.getData();
  30225. var stride = buffer.getStrideSize();
  30226. this._totalVertices = data.length / stride;
  30227. this.updateExtend(data, stride);
  30228. this._resetPointsArrayCache();
  30229. var meshes = this._meshes;
  30230. var numOfMeshes = meshes.length;
  30231. for (var index = 0; index < numOfMeshes; index++) {
  30232. var mesh = meshes[index];
  30233. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30234. mesh._createGlobalSubMesh(false);
  30235. mesh.computeWorldMatrix(true);
  30236. }
  30237. }
  30238. this.notifyUpdate(kind);
  30239. if (this._vertexArrayObjects) {
  30240. this._disposeVertexArrayObjects();
  30241. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30242. }
  30243. };
  30244. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30245. var vertexBuffer = this.getVertexBuffer(kind);
  30246. if (!vertexBuffer) {
  30247. return;
  30248. }
  30249. vertexBuffer.updateDirectly(data, offset);
  30250. this.notifyUpdate(kind);
  30251. };
  30252. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30253. if (updateExtends === void 0) { updateExtends = false; }
  30254. var vertexBuffer = this.getVertexBuffer(kind);
  30255. if (!vertexBuffer) {
  30256. return;
  30257. }
  30258. vertexBuffer.update(data);
  30259. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30260. var stride = vertexBuffer.getStrideSize();
  30261. this._totalVertices = data.length / stride;
  30262. this.updateBoundingInfo(updateExtends, data);
  30263. }
  30264. this.notifyUpdate(kind);
  30265. };
  30266. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30267. if (updateExtends) {
  30268. this.updateExtend(data);
  30269. }
  30270. var meshes = this._meshes;
  30271. var numOfMeshes = meshes.length;
  30272. this._resetPointsArrayCache();
  30273. for (var index = 0; index < numOfMeshes; index++) {
  30274. var mesh = meshes[index];
  30275. if (updateExtends) {
  30276. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30277. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30278. var subMesh = mesh.subMeshes[subIndex];
  30279. subMesh.refreshBoundingInfo();
  30280. }
  30281. }
  30282. }
  30283. };
  30284. Geometry.prototype._bind = function (effect, indexToBind) {
  30285. if (!effect) {
  30286. return;
  30287. }
  30288. if (indexToBind === undefined) {
  30289. indexToBind = this._indexBuffer;
  30290. }
  30291. var vbs = this.getVertexBuffers();
  30292. if (!vbs) {
  30293. return;
  30294. }
  30295. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30296. this._engine.bindBuffers(vbs, indexToBind, effect);
  30297. return;
  30298. }
  30299. // Using VAO
  30300. if (!this._vertexArrayObjects[effect.key]) {
  30301. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30302. }
  30303. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30304. };
  30305. Geometry.prototype.getTotalVertices = function () {
  30306. if (!this.isReady()) {
  30307. return 0;
  30308. }
  30309. return this._totalVertices;
  30310. };
  30311. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30312. var vertexBuffer = this.getVertexBuffer(kind);
  30313. if (!vertexBuffer) {
  30314. return null;
  30315. }
  30316. var orig = vertexBuffer.getData();
  30317. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30318. return orig;
  30319. }
  30320. else {
  30321. var len = orig.length;
  30322. var copy = [];
  30323. for (var i = 0; i < len; i++) {
  30324. copy.push(orig[i]);
  30325. }
  30326. return copy;
  30327. }
  30328. };
  30329. /**
  30330. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30331. * Possible `kind` values :
  30332. * - BABYLON.VertexBuffer.PositionKind
  30333. * - BABYLON.VertexBuffer.UVKind
  30334. * - BABYLON.VertexBuffer.UV2Kind
  30335. * - BABYLON.VertexBuffer.UV3Kind
  30336. * - BABYLON.VertexBuffer.UV4Kind
  30337. * - BABYLON.VertexBuffer.UV5Kind
  30338. * - BABYLON.VertexBuffer.UV6Kind
  30339. * - BABYLON.VertexBuffer.ColorKind
  30340. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30341. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30342. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30343. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30344. */
  30345. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  30346. var vb = this._vertexBuffers[kind];
  30347. if (!vb) {
  30348. return false;
  30349. }
  30350. return vb.isUpdatable();
  30351. };
  30352. Geometry.prototype.getVertexBuffer = function (kind) {
  30353. if (!this.isReady()) {
  30354. return null;
  30355. }
  30356. return this._vertexBuffers[kind];
  30357. };
  30358. Geometry.prototype.getVertexBuffers = function () {
  30359. if (!this.isReady()) {
  30360. return null;
  30361. }
  30362. return this._vertexBuffers;
  30363. };
  30364. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30365. if (!this._vertexBuffers) {
  30366. if (this._delayInfo) {
  30367. return this._delayInfo.indexOf(kind) !== -1;
  30368. }
  30369. return false;
  30370. }
  30371. return this._vertexBuffers[kind] !== undefined;
  30372. };
  30373. Geometry.prototype.getVerticesDataKinds = function () {
  30374. var result = [];
  30375. var kind;
  30376. if (!this._vertexBuffers && this._delayInfo) {
  30377. for (kind in this._delayInfo) {
  30378. result.push(kind);
  30379. }
  30380. }
  30381. else {
  30382. for (kind in this._vertexBuffers) {
  30383. result.push(kind);
  30384. }
  30385. }
  30386. return result;
  30387. };
  30388. Geometry.prototype.updateIndices = function (indices, offset) {
  30389. if (!this._indexBuffer) {
  30390. return;
  30391. }
  30392. if (!this._indexBufferIsUpdatable) {
  30393. this.setIndices(indices, null, true);
  30394. }
  30395. else {
  30396. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  30397. }
  30398. };
  30399. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  30400. if (totalVertices === void 0) { totalVertices = null; }
  30401. if (updatable === void 0) { updatable = false; }
  30402. if (this._indexBuffer) {
  30403. this._engine._releaseBuffer(this._indexBuffer);
  30404. }
  30405. this._disposeVertexArrayObjects();
  30406. this._indices = indices;
  30407. this._indexBufferIsUpdatable = updatable;
  30408. if (this._meshes.length !== 0 && this._indices) {
  30409. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  30410. }
  30411. if (totalVertices != undefined) {
  30412. this._totalVertices = totalVertices;
  30413. }
  30414. var meshes = this._meshes;
  30415. var numOfMeshes = meshes.length;
  30416. for (var index = 0; index < numOfMeshes; index++) {
  30417. meshes[index]._createGlobalSubMesh(true);
  30418. }
  30419. this.notifyUpdate();
  30420. };
  30421. Geometry.prototype.getTotalIndices = function () {
  30422. if (!this.isReady()) {
  30423. return 0;
  30424. }
  30425. return this._indices.length;
  30426. };
  30427. Geometry.prototype.getIndices = function (copyWhenShared) {
  30428. if (!this.isReady()) {
  30429. return null;
  30430. }
  30431. var orig = this._indices;
  30432. if (!copyWhenShared || this._meshes.length === 1) {
  30433. return orig;
  30434. }
  30435. else {
  30436. var len = orig.length;
  30437. var copy = [];
  30438. for (var i = 0; i < len; i++) {
  30439. copy.push(orig[i]);
  30440. }
  30441. return copy;
  30442. }
  30443. };
  30444. Geometry.prototype.getIndexBuffer = function () {
  30445. if (!this.isReady()) {
  30446. return null;
  30447. }
  30448. return this._indexBuffer;
  30449. };
  30450. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  30451. if (effect === void 0) { effect = null; }
  30452. if (!effect || !this._vertexArrayObjects) {
  30453. return;
  30454. }
  30455. if (this._vertexArrayObjects[effect.key]) {
  30456. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  30457. delete this._vertexArrayObjects[effect.key];
  30458. }
  30459. };
  30460. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30461. var meshes = this._meshes;
  30462. var index = meshes.indexOf(mesh);
  30463. if (index === -1) {
  30464. return;
  30465. }
  30466. meshes.splice(index, 1);
  30467. mesh._geometry = null;
  30468. if (meshes.length === 0 && shouldDispose) {
  30469. this.dispose();
  30470. }
  30471. };
  30472. Geometry.prototype.applyToMesh = function (mesh) {
  30473. if (mesh._geometry === this) {
  30474. return;
  30475. }
  30476. var previousGeometry = mesh._geometry;
  30477. if (previousGeometry) {
  30478. previousGeometry.releaseForMesh(mesh);
  30479. }
  30480. var meshes = this._meshes;
  30481. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30482. mesh._geometry = this;
  30483. this._scene.pushGeometry(this);
  30484. meshes.push(mesh);
  30485. if (this.isReady()) {
  30486. this._applyToMesh(mesh);
  30487. }
  30488. else {
  30489. mesh._boundingInfo = this._boundingInfo;
  30490. }
  30491. };
  30492. Geometry.prototype.updateExtend = function (data, stride) {
  30493. if (data === void 0) { data = null; }
  30494. if (!data) {
  30495. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30496. }
  30497. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  30498. };
  30499. Geometry.prototype._applyToMesh = function (mesh) {
  30500. var numOfMeshes = this._meshes.length;
  30501. // vertexBuffers
  30502. for (var kind in this._vertexBuffers) {
  30503. if (numOfMeshes === 1) {
  30504. this._vertexBuffers[kind].create();
  30505. }
  30506. var buffer = this._vertexBuffers[kind].getBuffer();
  30507. if (buffer)
  30508. buffer.references = numOfMeshes;
  30509. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30510. if (!this._extend) {
  30511. this.updateExtend(this._vertexBuffers[kind].getData());
  30512. }
  30513. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30514. mesh._createGlobalSubMesh(false);
  30515. //bounding info was just created again, world matrix should be applied again.
  30516. mesh._updateBoundingInfo();
  30517. }
  30518. }
  30519. // indexBuffer
  30520. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30521. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30522. }
  30523. if (this._indexBuffer) {
  30524. this._indexBuffer.references = numOfMeshes;
  30525. }
  30526. };
  30527. Geometry.prototype.notifyUpdate = function (kind) {
  30528. if (this.onGeometryUpdated) {
  30529. this.onGeometryUpdated(this, kind);
  30530. }
  30531. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30532. var mesh = _a[_i];
  30533. mesh._markSubMeshesAsAttributesDirty();
  30534. }
  30535. };
  30536. Geometry.prototype.load = function (scene, onLoaded) {
  30537. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30538. return;
  30539. }
  30540. if (this.isReady()) {
  30541. if (onLoaded) {
  30542. onLoaded();
  30543. }
  30544. return;
  30545. }
  30546. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30547. this._queueLoad(scene, onLoaded);
  30548. };
  30549. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30550. var _this = this;
  30551. if (!this.delayLoadingFile) {
  30552. return;
  30553. }
  30554. scene._addPendingData(this);
  30555. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30556. if (!_this._delayLoadingFunction) {
  30557. return;
  30558. }
  30559. _this._delayLoadingFunction(JSON.parse(data), _this);
  30560. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30561. _this._delayInfo = [];
  30562. scene._removePendingData(_this);
  30563. var meshes = _this._meshes;
  30564. var numOfMeshes = meshes.length;
  30565. for (var index = 0; index < numOfMeshes; index++) {
  30566. _this._applyToMesh(meshes[index]);
  30567. }
  30568. if (onLoaded) {
  30569. onLoaded();
  30570. }
  30571. }, function () { }, scene.database);
  30572. };
  30573. /**
  30574. * Invert the geometry to move from a right handed system to a left handed one.
  30575. */
  30576. Geometry.prototype.toLeftHanded = function () {
  30577. // Flip faces
  30578. var tIndices = this.getIndices(false);
  30579. if (tIndices != null && tIndices.length > 0) {
  30580. for (var i = 0; i < tIndices.length; i += 3) {
  30581. var tTemp = tIndices[i + 0];
  30582. tIndices[i + 0] = tIndices[i + 2];
  30583. tIndices[i + 2] = tTemp;
  30584. }
  30585. this.setIndices(tIndices);
  30586. }
  30587. // Negate position.z
  30588. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30589. if (tPositions != null && tPositions.length > 0) {
  30590. for (var i = 0; i < tPositions.length; i += 3) {
  30591. tPositions[i + 2] = -tPositions[i + 2];
  30592. }
  30593. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30594. }
  30595. // Negate normal.z
  30596. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30597. if (tNormals != null && tNormals.length > 0) {
  30598. for (var i = 0; i < tNormals.length; i += 3) {
  30599. tNormals[i + 2] = -tNormals[i + 2];
  30600. }
  30601. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30602. }
  30603. };
  30604. // Cache
  30605. Geometry.prototype._resetPointsArrayCache = function () {
  30606. this._positions = null;
  30607. };
  30608. Geometry.prototype._generatePointsArray = function () {
  30609. if (this._positions)
  30610. return true;
  30611. this._positions = [];
  30612. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30613. if (!data) {
  30614. return false;
  30615. }
  30616. for (var index = 0; index < data.length; index += 3) {
  30617. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30618. }
  30619. return true;
  30620. };
  30621. Geometry.prototype.isDisposed = function () {
  30622. return this._isDisposed;
  30623. };
  30624. Geometry.prototype._disposeVertexArrayObjects = function () {
  30625. if (this._vertexArrayObjects) {
  30626. for (var kind in this._vertexArrayObjects) {
  30627. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30628. }
  30629. this._vertexArrayObjects = {};
  30630. }
  30631. };
  30632. Geometry.prototype.dispose = function () {
  30633. var meshes = this._meshes;
  30634. var numOfMeshes = meshes.length;
  30635. var index;
  30636. for (index = 0; index < numOfMeshes; index++) {
  30637. this.releaseForMesh(meshes[index]);
  30638. }
  30639. this._meshes = [];
  30640. this._disposeVertexArrayObjects();
  30641. for (var kind in this._vertexBuffers) {
  30642. this._vertexBuffers[kind].dispose();
  30643. }
  30644. this._vertexBuffers = {};
  30645. this._totalVertices = 0;
  30646. if (this._indexBuffer) {
  30647. this._engine._releaseBuffer(this._indexBuffer);
  30648. }
  30649. this._indexBuffer = null;
  30650. this._indices = [];
  30651. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30652. this.delayLoadingFile = null;
  30653. this._delayLoadingFunction = null;
  30654. this._delayInfo = [];
  30655. this._boundingInfo = null;
  30656. this._scene.removeGeometry(this);
  30657. this._isDisposed = true;
  30658. };
  30659. Geometry.prototype.copy = function (id) {
  30660. var vertexData = new BABYLON.VertexData();
  30661. vertexData.indices = [];
  30662. var indices = this.getIndices();
  30663. if (indices) {
  30664. for (var index = 0; index < indices.length; index++) {
  30665. vertexData.indices.push(indices[index]);
  30666. }
  30667. }
  30668. var updatable = false;
  30669. var stopChecking = false;
  30670. var kind;
  30671. for (kind in this._vertexBuffers) {
  30672. // using slice() to make a copy of the array and not just reference it
  30673. var data = this.getVerticesData(kind);
  30674. if (data instanceof Float32Array) {
  30675. vertexData.set(new Float32Array(data), kind);
  30676. }
  30677. else {
  30678. vertexData.set(data.slice(0), kind);
  30679. }
  30680. if (!stopChecking) {
  30681. var vb = this.getVertexBuffer(kind);
  30682. if (vb) {
  30683. updatable = vb.isUpdatable();
  30684. stopChecking = !updatable;
  30685. }
  30686. }
  30687. }
  30688. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  30689. geometry.delayLoadState = this.delayLoadState;
  30690. geometry.delayLoadingFile = this.delayLoadingFile;
  30691. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30692. for (kind in this._delayInfo) {
  30693. geometry._delayInfo = geometry._delayInfo || [];
  30694. geometry._delayInfo.push(kind);
  30695. }
  30696. // Bounding info
  30697. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30698. return geometry;
  30699. };
  30700. Geometry.prototype.serialize = function () {
  30701. var serializationObject = {};
  30702. serializationObject.id = this.id;
  30703. serializationObject.updatable = this._updatable;
  30704. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30705. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30706. }
  30707. return serializationObject;
  30708. };
  30709. Geometry.prototype.toNumberArray = function (origin) {
  30710. if (Array.isArray(origin)) {
  30711. return origin;
  30712. }
  30713. else {
  30714. return Array.prototype.slice.call(origin);
  30715. }
  30716. };
  30717. Geometry.prototype.serializeVerticeData = function () {
  30718. var serializationObject = this.serialize();
  30719. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30720. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  30721. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30722. serializationObject.positions._updatable = true;
  30723. }
  30724. }
  30725. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30726. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  30727. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30728. serializationObject.normals._updatable = true;
  30729. }
  30730. }
  30731. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30732. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  30733. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  30734. serializationObject.uvs._updatable = true;
  30735. }
  30736. }
  30737. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30738. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  30739. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  30740. serializationObject.uv2s._updatable = true;
  30741. }
  30742. }
  30743. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30744. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  30745. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  30746. serializationObject.uv3s._updatable = true;
  30747. }
  30748. }
  30749. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30750. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  30751. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  30752. serializationObject.uv4s._updatable = true;
  30753. }
  30754. }
  30755. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30756. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  30757. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  30758. serializationObject.uv5s._updatable = true;
  30759. }
  30760. }
  30761. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30762. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  30763. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  30764. serializationObject.uv6s._updatable = true;
  30765. }
  30766. }
  30767. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30768. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  30769. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  30770. serializationObject.colors._updatable = true;
  30771. }
  30772. }
  30773. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30774. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  30775. serializationObject.matricesIndices._isExpanded = true;
  30776. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30777. serializationObject.matricesIndices._updatable = true;
  30778. }
  30779. }
  30780. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30781. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  30782. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30783. serializationObject.matricesWeights._updatable = true;
  30784. }
  30785. }
  30786. serializationObject.indices = this.toNumberArray(this.getIndices());
  30787. return serializationObject;
  30788. };
  30789. // Statics
  30790. Geometry.ExtractFromMesh = function (mesh, id) {
  30791. var geometry = mesh._geometry;
  30792. if (!geometry) {
  30793. return null;
  30794. }
  30795. return geometry.copy(id);
  30796. };
  30797. /**
  30798. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  30799. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  30800. * Be aware Math.random() could cause collisions, but:
  30801. * "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"
  30802. */
  30803. Geometry.RandomId = function () {
  30804. return BABYLON.Tools.RandomId();
  30805. };
  30806. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  30807. var scene = mesh.getScene();
  30808. // Geometry
  30809. var geometryId = parsedGeometry.geometryId;
  30810. if (geometryId) {
  30811. var geometry = scene.getGeometryByID(geometryId);
  30812. if (geometry) {
  30813. geometry.applyToMesh(mesh);
  30814. }
  30815. }
  30816. else if (parsedGeometry instanceof ArrayBuffer) {
  30817. var binaryInfo = mesh._binaryInfo;
  30818. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  30819. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  30820. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  30821. }
  30822. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  30823. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  30824. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  30825. }
  30826. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  30827. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  30828. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  30829. }
  30830. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  30831. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  30832. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  30833. }
  30834. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  30835. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  30836. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  30837. }
  30838. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  30839. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  30840. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  30841. }
  30842. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  30843. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  30844. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  30845. }
  30846. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  30847. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  30848. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  30849. }
  30850. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  30851. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  30852. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  30853. }
  30854. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  30855. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  30856. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  30857. }
  30858. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  30859. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  30860. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  30861. }
  30862. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  30863. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  30864. mesh.setIndices(indicesData, null);
  30865. }
  30866. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  30867. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  30868. mesh.subMeshes = [];
  30869. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  30870. var materialIndex = subMeshesData[(i * 5) + 0];
  30871. var verticesStart = subMeshesData[(i * 5) + 1];
  30872. var verticesCount = subMeshesData[(i * 5) + 2];
  30873. var indexStart = subMeshesData[(i * 5) + 3];
  30874. var indexCount = subMeshesData[(i * 5) + 4];
  30875. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  30876. }
  30877. }
  30878. }
  30879. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  30880. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  30881. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  30882. if (parsedGeometry.uvs) {
  30883. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  30884. }
  30885. if (parsedGeometry.uvs2) {
  30886. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  30887. }
  30888. if (parsedGeometry.uvs3) {
  30889. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  30890. }
  30891. if (parsedGeometry.uvs4) {
  30892. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  30893. }
  30894. if (parsedGeometry.uvs5) {
  30895. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  30896. }
  30897. if (parsedGeometry.uvs6) {
  30898. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  30899. }
  30900. if (parsedGeometry.colors) {
  30901. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  30902. }
  30903. if (parsedGeometry.matricesIndices) {
  30904. if (!parsedGeometry.matricesIndices._isExpanded) {
  30905. var floatIndices = [];
  30906. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  30907. var matricesIndex = parsedGeometry.matricesIndices[i];
  30908. floatIndices.push(matricesIndex & 0x000000FF);
  30909. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30910. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30911. floatIndices.push(matricesIndex >> 24);
  30912. }
  30913. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  30914. }
  30915. else {
  30916. delete parsedGeometry.matricesIndices._isExpanded;
  30917. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  30918. }
  30919. }
  30920. if (parsedGeometry.matricesIndicesExtra) {
  30921. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  30922. var floatIndices = [];
  30923. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  30924. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  30925. floatIndices.push(matricesIndex & 0x000000FF);
  30926. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30927. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30928. floatIndices.push(matricesIndex >> 24);
  30929. }
  30930. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  30931. }
  30932. else {
  30933. delete parsedGeometry.matricesIndices._isExpanded;
  30934. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  30935. }
  30936. }
  30937. if (parsedGeometry.matricesWeights) {
  30938. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  30939. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  30940. }
  30941. if (parsedGeometry.matricesWeightsExtra) {
  30942. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  30943. }
  30944. mesh.setIndices(parsedGeometry.indices, null);
  30945. }
  30946. // SubMeshes
  30947. if (parsedGeometry.subMeshes) {
  30948. mesh.subMeshes = [];
  30949. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  30950. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  30951. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  30952. }
  30953. }
  30954. // Flat shading
  30955. if (mesh._shouldGenerateFlatShading) {
  30956. mesh.convertToFlatShadedMesh();
  30957. delete mesh._shouldGenerateFlatShading;
  30958. }
  30959. // Update
  30960. mesh.computeWorldMatrix(true);
  30961. // Octree
  30962. if (scene['_selectionOctree']) {
  30963. scene['_selectionOctree'].addMesh(mesh);
  30964. }
  30965. };
  30966. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  30967. var epsilon = 1e-3;
  30968. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  30969. return;
  30970. }
  30971. var noInfluenceBoneIndex = 0.0;
  30972. if (parsedGeometry.skeletonId > -1) {
  30973. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  30974. if (!skeleton) {
  30975. return;
  30976. }
  30977. noInfluenceBoneIndex = skeleton.bones.length;
  30978. }
  30979. else {
  30980. return;
  30981. }
  30982. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30983. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  30984. var matricesWeights = parsedGeometry.matricesWeights;
  30985. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  30986. var influencers = parsedGeometry.numBoneInfluencer;
  30987. var size = matricesWeights.length;
  30988. for (var i = 0; i < size; i += 4) {
  30989. var weight = 0.0;
  30990. var firstZeroWeight = -1;
  30991. for (var j = 0; j < 4; j++) {
  30992. var w = matricesWeights[i + j];
  30993. weight += w;
  30994. if (w < epsilon && firstZeroWeight < 0) {
  30995. firstZeroWeight = j;
  30996. }
  30997. }
  30998. if (matricesWeightsExtra) {
  30999. for (var j = 0; j < 4; j++) {
  31000. var w = matricesWeightsExtra[i + j];
  31001. weight += w;
  31002. if (w < epsilon && firstZeroWeight < 0) {
  31003. firstZeroWeight = j + 4;
  31004. }
  31005. }
  31006. }
  31007. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31008. firstZeroWeight = influencers - 1;
  31009. }
  31010. if (weight > epsilon) {
  31011. var mweight = 1.0 / weight;
  31012. for (var j = 0; j < 4; j++) {
  31013. matricesWeights[i + j] *= mweight;
  31014. }
  31015. if (matricesWeightsExtra) {
  31016. for (var j = 0; j < 4; j++) {
  31017. matricesWeightsExtra[i + j] *= mweight;
  31018. }
  31019. }
  31020. }
  31021. else {
  31022. if (firstZeroWeight >= 4) {
  31023. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31024. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31025. }
  31026. else {
  31027. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31028. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31029. }
  31030. }
  31031. }
  31032. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31033. if (parsedGeometry.matricesWeightsExtra) {
  31034. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31035. }
  31036. };
  31037. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31038. if (scene.getGeometryByID(parsedVertexData.id)) {
  31039. return null; // null since geometry could be something else than a box...
  31040. }
  31041. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31042. if (BABYLON.Tags) {
  31043. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31044. }
  31045. if (parsedVertexData.delayLoadingFile) {
  31046. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31047. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31048. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31049. geometry._delayInfo = [];
  31050. if (parsedVertexData.hasUVs) {
  31051. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31052. }
  31053. if (parsedVertexData.hasUVs2) {
  31054. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31055. }
  31056. if (parsedVertexData.hasUVs3) {
  31057. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31058. }
  31059. if (parsedVertexData.hasUVs4) {
  31060. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31061. }
  31062. if (parsedVertexData.hasUVs5) {
  31063. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31064. }
  31065. if (parsedVertexData.hasUVs6) {
  31066. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31067. }
  31068. if (parsedVertexData.hasColors) {
  31069. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31070. }
  31071. if (parsedVertexData.hasMatricesIndices) {
  31072. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31073. }
  31074. if (parsedVertexData.hasMatricesWeights) {
  31075. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31076. }
  31077. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31078. }
  31079. else {
  31080. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31081. }
  31082. scene.pushGeometry(geometry, true);
  31083. return geometry;
  31084. };
  31085. return Geometry;
  31086. }());
  31087. BABYLON.Geometry = Geometry;
  31088. /////// Primitives //////////////////////////////////////////////
  31089. (function (Geometry) {
  31090. var Primitives;
  31091. (function (Primitives) {
  31092. /// Abstract class
  31093. var _Primitive = /** @class */ (function (_super) {
  31094. __extends(_Primitive, _super);
  31095. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31096. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31097. if (mesh === void 0) { mesh = null; }
  31098. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31099. _this._canBeRegenerated = _canBeRegenerated;
  31100. _this._beingRegenerated = true;
  31101. _this.regenerate();
  31102. _this._beingRegenerated = false;
  31103. return _this;
  31104. }
  31105. _Primitive.prototype.canBeRegenerated = function () {
  31106. return this._canBeRegenerated;
  31107. };
  31108. _Primitive.prototype.regenerate = function () {
  31109. if (!this._canBeRegenerated) {
  31110. return;
  31111. }
  31112. this._beingRegenerated = true;
  31113. this.setAllVerticesData(this._regenerateVertexData(), false);
  31114. this._beingRegenerated = false;
  31115. };
  31116. _Primitive.prototype.asNewGeometry = function (id) {
  31117. return _super.prototype.copy.call(this, id);
  31118. };
  31119. // overrides
  31120. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31121. if (!this._beingRegenerated) {
  31122. return;
  31123. }
  31124. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31125. };
  31126. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31127. if (!this._beingRegenerated) {
  31128. return;
  31129. }
  31130. _super.prototype.setVerticesData.call(this, kind, data, false);
  31131. };
  31132. // to override
  31133. // protected
  31134. _Primitive.prototype._regenerateVertexData = function () {
  31135. throw new Error("Abstract method");
  31136. };
  31137. _Primitive.prototype.copy = function (id) {
  31138. throw new Error("Must be overriden in sub-classes.");
  31139. };
  31140. _Primitive.prototype.serialize = function () {
  31141. var serializationObject = _super.prototype.serialize.call(this);
  31142. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31143. return serializationObject;
  31144. };
  31145. return _Primitive;
  31146. }(Geometry));
  31147. Primitives._Primitive = _Primitive;
  31148. var Ribbon = /** @class */ (function (_super) {
  31149. __extends(Ribbon, _super);
  31150. // Members
  31151. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31152. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31153. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31154. _this.pathArray = pathArray;
  31155. _this.closeArray = closeArray;
  31156. _this.closePath = closePath;
  31157. _this.offset = offset;
  31158. _this.side = side;
  31159. return _this;
  31160. }
  31161. Ribbon.prototype._regenerateVertexData = function () {
  31162. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31163. };
  31164. Ribbon.prototype.copy = function (id) {
  31165. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31166. };
  31167. return Ribbon;
  31168. }(_Primitive));
  31169. Primitives.Ribbon = Ribbon;
  31170. var Box = /** @class */ (function (_super) {
  31171. __extends(Box, _super);
  31172. // Members
  31173. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31174. if (mesh === void 0) { mesh = null; }
  31175. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31176. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31177. _this.size = size;
  31178. _this.side = side;
  31179. return _this;
  31180. }
  31181. Box.prototype._regenerateVertexData = function () {
  31182. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31183. };
  31184. Box.prototype.copy = function (id) {
  31185. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31186. };
  31187. Box.prototype.serialize = function () {
  31188. var serializationObject = _super.prototype.serialize.call(this);
  31189. serializationObject.size = this.size;
  31190. return serializationObject;
  31191. };
  31192. Box.Parse = function (parsedBox, scene) {
  31193. if (scene.getGeometryByID(parsedBox.id)) {
  31194. return null; // null since geometry could be something else than a box...
  31195. }
  31196. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31197. if (BABYLON.Tags) {
  31198. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31199. }
  31200. scene.pushGeometry(box, true);
  31201. return box;
  31202. };
  31203. return Box;
  31204. }(_Primitive));
  31205. Primitives.Box = Box;
  31206. var Sphere = /** @class */ (function (_super) {
  31207. __extends(Sphere, _super);
  31208. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31209. if (mesh === void 0) { mesh = null; }
  31210. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31211. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31212. _this.segments = segments;
  31213. _this.diameter = diameter;
  31214. _this.side = side;
  31215. return _this;
  31216. }
  31217. Sphere.prototype._regenerateVertexData = function () {
  31218. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31219. };
  31220. Sphere.prototype.copy = function (id) {
  31221. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31222. };
  31223. Sphere.prototype.serialize = function () {
  31224. var serializationObject = _super.prototype.serialize.call(this);
  31225. serializationObject.segments = this.segments;
  31226. serializationObject.diameter = this.diameter;
  31227. return serializationObject;
  31228. };
  31229. Sphere.Parse = function (parsedSphere, scene) {
  31230. if (scene.getGeometryByID(parsedSphere.id)) {
  31231. return null; // null since geometry could be something else than a sphere...
  31232. }
  31233. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31234. if (BABYLON.Tags) {
  31235. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31236. }
  31237. scene.pushGeometry(sphere, true);
  31238. return sphere;
  31239. };
  31240. return Sphere;
  31241. }(_Primitive));
  31242. Primitives.Sphere = Sphere;
  31243. var Disc = /** @class */ (function (_super) {
  31244. __extends(Disc, _super);
  31245. // Members
  31246. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31247. if (mesh === void 0) { mesh = null; }
  31248. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31249. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31250. _this.radius = radius;
  31251. _this.tessellation = tessellation;
  31252. _this.side = side;
  31253. return _this;
  31254. }
  31255. Disc.prototype._regenerateVertexData = function () {
  31256. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31257. };
  31258. Disc.prototype.copy = function (id) {
  31259. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31260. };
  31261. return Disc;
  31262. }(_Primitive));
  31263. Primitives.Disc = Disc;
  31264. var Cylinder = /** @class */ (function (_super) {
  31265. __extends(Cylinder, _super);
  31266. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31267. if (subdivisions === void 0) { subdivisions = 1; }
  31268. if (mesh === void 0) { mesh = null; }
  31269. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31270. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31271. _this.height = height;
  31272. _this.diameterTop = diameterTop;
  31273. _this.diameterBottom = diameterBottom;
  31274. _this.tessellation = tessellation;
  31275. _this.subdivisions = subdivisions;
  31276. _this.side = side;
  31277. return _this;
  31278. }
  31279. Cylinder.prototype._regenerateVertexData = function () {
  31280. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31281. };
  31282. Cylinder.prototype.copy = function (id) {
  31283. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31284. };
  31285. Cylinder.prototype.serialize = function () {
  31286. var serializationObject = _super.prototype.serialize.call(this);
  31287. serializationObject.height = this.height;
  31288. serializationObject.diameterTop = this.diameterTop;
  31289. serializationObject.diameterBottom = this.diameterBottom;
  31290. serializationObject.tessellation = this.tessellation;
  31291. return serializationObject;
  31292. };
  31293. Cylinder.Parse = function (parsedCylinder, scene) {
  31294. if (scene.getGeometryByID(parsedCylinder.id)) {
  31295. return null; // null since geometry could be something else than a cylinder...
  31296. }
  31297. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31298. if (BABYLON.Tags) {
  31299. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31300. }
  31301. scene.pushGeometry(cylinder, true);
  31302. return cylinder;
  31303. };
  31304. return Cylinder;
  31305. }(_Primitive));
  31306. Primitives.Cylinder = Cylinder;
  31307. var Torus = /** @class */ (function (_super) {
  31308. __extends(Torus, _super);
  31309. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31310. if (mesh === void 0) { mesh = null; }
  31311. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31312. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31313. _this.diameter = diameter;
  31314. _this.thickness = thickness;
  31315. _this.tessellation = tessellation;
  31316. _this.side = side;
  31317. return _this;
  31318. }
  31319. Torus.prototype._regenerateVertexData = function () {
  31320. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31321. };
  31322. Torus.prototype.copy = function (id) {
  31323. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31324. };
  31325. Torus.prototype.serialize = function () {
  31326. var serializationObject = _super.prototype.serialize.call(this);
  31327. serializationObject.diameter = this.diameter;
  31328. serializationObject.thickness = this.thickness;
  31329. serializationObject.tessellation = this.tessellation;
  31330. return serializationObject;
  31331. };
  31332. Torus.Parse = function (parsedTorus, scene) {
  31333. if (scene.getGeometryByID(parsedTorus.id)) {
  31334. return null; // null since geometry could be something else than a torus...
  31335. }
  31336. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31337. if (BABYLON.Tags) {
  31338. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31339. }
  31340. scene.pushGeometry(torus, true);
  31341. return torus;
  31342. };
  31343. return Torus;
  31344. }(_Primitive));
  31345. Primitives.Torus = Torus;
  31346. var Ground = /** @class */ (function (_super) {
  31347. __extends(Ground, _super);
  31348. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31349. if (mesh === void 0) { mesh = null; }
  31350. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31351. _this.width = width;
  31352. _this.height = height;
  31353. _this.subdivisions = subdivisions;
  31354. return _this;
  31355. }
  31356. Ground.prototype._regenerateVertexData = function () {
  31357. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31358. };
  31359. Ground.prototype.copy = function (id) {
  31360. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31361. };
  31362. Ground.prototype.serialize = function () {
  31363. var serializationObject = _super.prototype.serialize.call(this);
  31364. serializationObject.width = this.width;
  31365. serializationObject.height = this.height;
  31366. serializationObject.subdivisions = this.subdivisions;
  31367. return serializationObject;
  31368. };
  31369. Ground.Parse = function (parsedGround, scene) {
  31370. if (scene.getGeometryByID(parsedGround.id)) {
  31371. return null; // null since geometry could be something else than a ground...
  31372. }
  31373. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31374. if (BABYLON.Tags) {
  31375. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31376. }
  31377. scene.pushGeometry(ground, true);
  31378. return ground;
  31379. };
  31380. return Ground;
  31381. }(_Primitive));
  31382. Primitives.Ground = Ground;
  31383. var TiledGround = /** @class */ (function (_super) {
  31384. __extends(TiledGround, _super);
  31385. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31386. if (mesh === void 0) { mesh = null; }
  31387. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31388. _this.xmin = xmin;
  31389. _this.zmin = zmin;
  31390. _this.xmax = xmax;
  31391. _this.zmax = zmax;
  31392. _this.subdivisions = subdivisions;
  31393. _this.precision = precision;
  31394. return _this;
  31395. }
  31396. TiledGround.prototype._regenerateVertexData = function () {
  31397. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31398. };
  31399. TiledGround.prototype.copy = function (id) {
  31400. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31401. };
  31402. return TiledGround;
  31403. }(_Primitive));
  31404. Primitives.TiledGround = TiledGround;
  31405. var Plane = /** @class */ (function (_super) {
  31406. __extends(Plane, _super);
  31407. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31408. if (mesh === void 0) { mesh = null; }
  31409. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31410. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31411. _this.size = size;
  31412. _this.side = side;
  31413. return _this;
  31414. }
  31415. Plane.prototype._regenerateVertexData = function () {
  31416. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31417. };
  31418. Plane.prototype.copy = function (id) {
  31419. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31420. };
  31421. Plane.prototype.serialize = function () {
  31422. var serializationObject = _super.prototype.serialize.call(this);
  31423. serializationObject.size = this.size;
  31424. return serializationObject;
  31425. };
  31426. Plane.Parse = function (parsedPlane, scene) {
  31427. if (scene.getGeometryByID(parsedPlane.id)) {
  31428. return null; // null since geometry could be something else than a ground...
  31429. }
  31430. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31431. if (BABYLON.Tags) {
  31432. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31433. }
  31434. scene.pushGeometry(plane, true);
  31435. return plane;
  31436. };
  31437. return Plane;
  31438. }(_Primitive));
  31439. Primitives.Plane = Plane;
  31440. var TorusKnot = /** @class */ (function (_super) {
  31441. __extends(TorusKnot, _super);
  31442. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31443. if (mesh === void 0) { mesh = null; }
  31444. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31445. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31446. _this.radius = radius;
  31447. _this.tube = tube;
  31448. _this.radialSegments = radialSegments;
  31449. _this.tubularSegments = tubularSegments;
  31450. _this.p = p;
  31451. _this.q = q;
  31452. _this.side = side;
  31453. return _this;
  31454. }
  31455. TorusKnot.prototype._regenerateVertexData = function () {
  31456. 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 });
  31457. };
  31458. TorusKnot.prototype.copy = function (id) {
  31459. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31460. };
  31461. TorusKnot.prototype.serialize = function () {
  31462. var serializationObject = _super.prototype.serialize.call(this);
  31463. serializationObject.radius = this.radius;
  31464. serializationObject.tube = this.tube;
  31465. serializationObject.radialSegments = this.radialSegments;
  31466. serializationObject.tubularSegments = this.tubularSegments;
  31467. serializationObject.p = this.p;
  31468. serializationObject.q = this.q;
  31469. return serializationObject;
  31470. };
  31471. ;
  31472. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31473. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31474. return null; // null since geometry could be something else than a ground...
  31475. }
  31476. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31477. if (BABYLON.Tags) {
  31478. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31479. }
  31480. scene.pushGeometry(torusKnot, true);
  31481. return torusKnot;
  31482. };
  31483. return TorusKnot;
  31484. }(_Primitive));
  31485. Primitives.TorusKnot = TorusKnot;
  31486. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31487. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31488. })(BABYLON || (BABYLON = {}));
  31489. //# sourceMappingURL=babylon.geometry.js.map
  31490. var BABYLON;
  31491. (function (BABYLON) {
  31492. var PostProcessManager = /** @class */ (function () {
  31493. function PostProcessManager(scene) {
  31494. this._vertexBuffers = {};
  31495. this._scene = scene;
  31496. }
  31497. PostProcessManager.prototype._prepareBuffers = function () {
  31498. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31499. return;
  31500. }
  31501. // VBO
  31502. var vertices = [];
  31503. vertices.push(1, 1);
  31504. vertices.push(-1, 1);
  31505. vertices.push(-1, -1);
  31506. vertices.push(1, -1);
  31507. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31508. this._buildIndexBuffer();
  31509. };
  31510. PostProcessManager.prototype._buildIndexBuffer = function () {
  31511. // Indices
  31512. var indices = [];
  31513. indices.push(0);
  31514. indices.push(1);
  31515. indices.push(2);
  31516. indices.push(0);
  31517. indices.push(2);
  31518. indices.push(3);
  31519. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31520. };
  31521. PostProcessManager.prototype._rebuild = function () {
  31522. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31523. if (!vb) {
  31524. return;
  31525. }
  31526. vb._rebuild();
  31527. this._buildIndexBuffer();
  31528. };
  31529. // Methods
  31530. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31531. if (sourceTexture === void 0) { sourceTexture = null; }
  31532. if (postProcesses === void 0) { postProcesses = null; }
  31533. var camera = this._scene.activeCamera;
  31534. if (!camera) {
  31535. return false;
  31536. }
  31537. var postProcesses = postProcesses || camera._postProcesses;
  31538. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31539. return false;
  31540. }
  31541. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31542. return true;
  31543. };
  31544. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31545. if (targetTexture === void 0) { targetTexture = null; }
  31546. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31547. if (!this._scene.activeCamera) {
  31548. return;
  31549. }
  31550. var engine = this._scene.getEngine();
  31551. for (var index = 0; index < postProcesses.length; index++) {
  31552. if (index < postProcesses.length - 1) {
  31553. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31554. }
  31555. else {
  31556. if (targetTexture) {
  31557. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31558. }
  31559. else {
  31560. engine.restoreDefaultFramebuffer();
  31561. }
  31562. }
  31563. var pp = postProcesses[index];
  31564. var effect = pp.apply();
  31565. if (effect) {
  31566. pp.onBeforeRenderObservable.notifyObservers(effect);
  31567. // VBOs
  31568. this._prepareBuffers();
  31569. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31570. // Draw order
  31571. engine.draw(true, 0, 6);
  31572. pp.onAfterRenderObservable.notifyObservers(effect);
  31573. }
  31574. }
  31575. // Restore depth buffer
  31576. engine.setDepthBuffer(true);
  31577. engine.setDepthWrite(true);
  31578. };
  31579. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31580. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31581. var camera = this._scene.activeCamera;
  31582. if (!camera) {
  31583. return;
  31584. }
  31585. postProcesses = postProcesses || camera._postProcesses;
  31586. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31587. return;
  31588. }
  31589. var engine = this._scene.getEngine();
  31590. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31591. if (index < len - 1) {
  31592. postProcesses[index + 1].activate(camera, targetTexture);
  31593. }
  31594. else {
  31595. if (targetTexture) {
  31596. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31597. }
  31598. else {
  31599. engine.restoreDefaultFramebuffer();
  31600. }
  31601. }
  31602. if (doNotPresent) {
  31603. break;
  31604. }
  31605. var pp = postProcesses[index];
  31606. var effect = pp.apply();
  31607. if (effect) {
  31608. pp.onBeforeRenderObservable.notifyObservers(effect);
  31609. // VBOs
  31610. this._prepareBuffers();
  31611. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31612. // Draw order
  31613. engine.draw(true, 0, 6);
  31614. pp.onAfterRenderObservable.notifyObservers(effect);
  31615. }
  31616. }
  31617. // Restore states
  31618. engine.setDepthBuffer(true);
  31619. engine.setDepthWrite(true);
  31620. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31621. };
  31622. PostProcessManager.prototype.dispose = function () {
  31623. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31624. if (buffer) {
  31625. buffer.dispose();
  31626. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31627. }
  31628. if (this._indexBuffer) {
  31629. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31630. this._indexBuffer = null;
  31631. }
  31632. };
  31633. return PostProcessManager;
  31634. }());
  31635. BABYLON.PostProcessManager = PostProcessManager;
  31636. })(BABYLON || (BABYLON = {}));
  31637. //# sourceMappingURL=babylon.postProcessManager.js.map
  31638. var BABYLON;
  31639. (function (BABYLON) {
  31640. /**
  31641. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31642. */
  31643. var PerformanceMonitor = /** @class */ (function () {
  31644. /**
  31645. * constructor
  31646. * @param frameSampleSize The number of samples required to saturate the sliding window
  31647. */
  31648. function PerformanceMonitor(frameSampleSize) {
  31649. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31650. this._enabled = true;
  31651. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31652. }
  31653. /**
  31654. * Samples current frame
  31655. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31656. */
  31657. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31658. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31659. if (!this._enabled)
  31660. return;
  31661. if (this._lastFrameTimeMs != null) {
  31662. var dt = timeMs - this._lastFrameTimeMs;
  31663. this._rollingFrameTime.add(dt);
  31664. }
  31665. this._lastFrameTimeMs = timeMs;
  31666. };
  31667. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31668. /**
  31669. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31670. * @return Average frame time in milliseconds
  31671. */
  31672. get: function () {
  31673. return this._rollingFrameTime.average;
  31674. },
  31675. enumerable: true,
  31676. configurable: true
  31677. });
  31678. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  31679. /**
  31680. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31681. * @return Frame time variance in milliseconds squared
  31682. */
  31683. get: function () {
  31684. return this._rollingFrameTime.variance;
  31685. },
  31686. enumerable: true,
  31687. configurable: true
  31688. });
  31689. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  31690. /**
  31691. * Returns the frame time of the most recent frame
  31692. * @return Frame time in milliseconds
  31693. */
  31694. get: function () {
  31695. return this._rollingFrameTime.history(0);
  31696. },
  31697. enumerable: true,
  31698. configurable: true
  31699. });
  31700. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  31701. /**
  31702. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  31703. * @return Framerate in frames per second
  31704. */
  31705. get: function () {
  31706. return 1000.0 / this._rollingFrameTime.average;
  31707. },
  31708. enumerable: true,
  31709. configurable: true
  31710. });
  31711. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  31712. /**
  31713. * Returns the average framerate in frames per second using the most recent frame time
  31714. * @return Framerate in frames per second
  31715. */
  31716. get: function () {
  31717. var history = this._rollingFrameTime.history(0);
  31718. if (history === 0) {
  31719. return 0;
  31720. }
  31721. return 1000.0 / history;
  31722. },
  31723. enumerable: true,
  31724. configurable: true
  31725. });
  31726. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  31727. /**
  31728. * Returns true if enough samples have been taken to completely fill the sliding window
  31729. * @return true if saturated
  31730. */
  31731. get: function () {
  31732. return this._rollingFrameTime.isSaturated();
  31733. },
  31734. enumerable: true,
  31735. configurable: true
  31736. });
  31737. /**
  31738. * Enables contributions to the sliding window sample set
  31739. */
  31740. PerformanceMonitor.prototype.enable = function () {
  31741. this._enabled = true;
  31742. };
  31743. /**
  31744. * Disables contributions to the sliding window sample set
  31745. * Samples will not be interpolated over the disabled period
  31746. */
  31747. PerformanceMonitor.prototype.disable = function () {
  31748. this._enabled = false;
  31749. //clear last sample to avoid interpolating over the disabled period when next enabled
  31750. this._lastFrameTimeMs = null;
  31751. this._lastChangeTimeMs = null;
  31752. };
  31753. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  31754. /**
  31755. * Returns true if sampling is enabled
  31756. * @return true if enabled
  31757. */
  31758. get: function () {
  31759. return this._enabled;
  31760. },
  31761. enumerable: true,
  31762. configurable: true
  31763. });
  31764. /**
  31765. * Resets performance monitor
  31766. */
  31767. PerformanceMonitor.prototype.reset = function () {
  31768. //clear last sample to avoid interpolating over the disabled period when next enabled
  31769. this._lastFrameTimeMs = null;
  31770. this._lastChangeTimeMs = null;
  31771. //wipe record
  31772. this._rollingFrameTime.reset();
  31773. };
  31774. return PerformanceMonitor;
  31775. }());
  31776. BABYLON.PerformanceMonitor = PerformanceMonitor;
  31777. /**
  31778. * RollingAverage
  31779. *
  31780. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  31781. */
  31782. var RollingAverage = /** @class */ (function () {
  31783. /**
  31784. * constructor
  31785. * @param length The number of samples required to saturate the sliding window
  31786. */
  31787. function RollingAverage(length) {
  31788. this._samples = new Array(length);
  31789. this.reset();
  31790. }
  31791. /**
  31792. * Adds a sample to the sample set
  31793. * @param v The sample value
  31794. */
  31795. RollingAverage.prototype.add = function (v) {
  31796. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  31797. var delta;
  31798. //we need to check if we've already wrapped round
  31799. if (this.isSaturated()) {
  31800. //remove bottom of stack from mean
  31801. var bottomValue = this._samples[this._pos];
  31802. delta = bottomValue - this.average;
  31803. this.average -= delta / (this._sampleCount - 1);
  31804. this._m2 -= delta * (bottomValue - this.average);
  31805. }
  31806. else {
  31807. this._sampleCount++;
  31808. }
  31809. //add new value to mean
  31810. delta = v - this.average;
  31811. this.average += delta / (this._sampleCount);
  31812. this._m2 += delta * (v - this.average);
  31813. //set the new variance
  31814. this.variance = this._m2 / (this._sampleCount - 1);
  31815. this._samples[this._pos] = v;
  31816. this._pos++;
  31817. this._pos %= this._samples.length; //positive wrap around
  31818. };
  31819. /**
  31820. * Returns previously added values or null if outside of history or outside the sliding window domain
  31821. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  31822. * @return Value previously recorded with add() or null if outside of range
  31823. */
  31824. RollingAverage.prototype.history = function (i) {
  31825. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  31826. return 0;
  31827. }
  31828. var i0 = this._wrapPosition(this._pos - 1.0);
  31829. return this._samples[this._wrapPosition(i0 - i)];
  31830. };
  31831. /**
  31832. * Returns true if enough samples have been taken to completely fill the sliding window
  31833. * @return true if sample-set saturated
  31834. */
  31835. RollingAverage.prototype.isSaturated = function () {
  31836. return this._sampleCount >= this._samples.length;
  31837. };
  31838. /**
  31839. * Resets the rolling average (equivalent to 0 samples taken so far)
  31840. */
  31841. RollingAverage.prototype.reset = function () {
  31842. this.average = 0;
  31843. this.variance = 0;
  31844. this._sampleCount = 0;
  31845. this._pos = 0;
  31846. this._m2 = 0;
  31847. };
  31848. /**
  31849. * Wraps a value around the sample range boundaries
  31850. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  31851. * @return Wrapped position in sample range
  31852. */
  31853. RollingAverage.prototype._wrapPosition = function (i) {
  31854. var max = this._samples.length;
  31855. return ((i % max) + max) % max;
  31856. };
  31857. return RollingAverage;
  31858. }());
  31859. BABYLON.RollingAverage = RollingAverage;
  31860. })(BABYLON || (BABYLON = {}));
  31861. //# sourceMappingURL=babylon.performanceMonitor.js.map
  31862. var BABYLON;
  31863. (function (BABYLON) {
  31864. /**
  31865. * This groups together the common properties used for image processing either in direct forward pass
  31866. * or through post processing effect depending on the use of the image processing pipeline in your scene
  31867. * or not.
  31868. */
  31869. var ImageProcessingConfiguration = /** @class */ (function () {
  31870. function ImageProcessingConfiguration() {
  31871. /**
  31872. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  31873. */
  31874. this.colorCurves = new BABYLON.ColorCurves();
  31875. this._colorCurvesEnabled = false;
  31876. this._colorGradingEnabled = false;
  31877. this._colorGradingWithGreenDepth = true;
  31878. this._colorGradingBGR = true;
  31879. this._exposure = 1.0;
  31880. this._toneMappingEnabled = false;
  31881. this._contrast = 1.0;
  31882. /**
  31883. * Vignette stretch size.
  31884. */
  31885. this.vignetteStretch = 0;
  31886. /**
  31887. * Vignette centre X Offset.
  31888. */
  31889. this.vignetteCentreX = 0;
  31890. /**
  31891. * Vignette centre Y Offset.
  31892. */
  31893. this.vignetteCentreY = 0;
  31894. /**
  31895. * Vignette weight or intensity of the vignette effect.
  31896. */
  31897. this.vignetteWeight = 1.5;
  31898. /**
  31899. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  31900. * if vignetteEnabled is set to true.
  31901. */
  31902. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  31903. /**
  31904. * Camera field of view used by the Vignette effect.
  31905. */
  31906. this.vignetteCameraFov = 0.5;
  31907. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  31908. this._vignetteEnabled = false;
  31909. this._applyByPostProcess = false;
  31910. /**
  31911. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  31912. * @type {BABYLON.Observable}
  31913. */
  31914. this.onUpdateParameters = new BABYLON.Observable();
  31915. }
  31916. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  31917. /**
  31918. * Gets wether the color curves effect is enabled.
  31919. */
  31920. get: function () {
  31921. return this._colorCurvesEnabled;
  31922. },
  31923. /**
  31924. * Sets wether the color curves effect is enabled.
  31925. */
  31926. set: function (value) {
  31927. if (this._colorCurvesEnabled === value) {
  31928. return;
  31929. }
  31930. this._colorCurvesEnabled = value;
  31931. this._updateParameters();
  31932. },
  31933. enumerable: true,
  31934. configurable: true
  31935. });
  31936. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  31937. /**
  31938. * Gets wether the color grading effect is enabled.
  31939. */
  31940. get: function () {
  31941. return this._colorGradingEnabled;
  31942. },
  31943. /**
  31944. * Sets wether the color grading effect is enabled.
  31945. */
  31946. set: function (value) {
  31947. if (this._colorGradingEnabled === value) {
  31948. return;
  31949. }
  31950. this._colorGradingEnabled = value;
  31951. this._updateParameters();
  31952. },
  31953. enumerable: true,
  31954. configurable: true
  31955. });
  31956. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  31957. /**
  31958. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  31959. */
  31960. get: function () {
  31961. return this._colorGradingWithGreenDepth;
  31962. },
  31963. /**
  31964. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  31965. */
  31966. set: function (value) {
  31967. if (this._colorGradingWithGreenDepth === value) {
  31968. return;
  31969. }
  31970. this._colorGradingWithGreenDepth = value;
  31971. this._updateParameters();
  31972. },
  31973. enumerable: true,
  31974. configurable: true
  31975. });
  31976. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  31977. /**
  31978. * Gets wether the color grading texture contains BGR values.
  31979. */
  31980. get: function () {
  31981. return this._colorGradingBGR;
  31982. },
  31983. /**
  31984. * Sets wether the color grading texture contains BGR values.
  31985. */
  31986. set: function (value) {
  31987. if (this._colorGradingBGR === value) {
  31988. return;
  31989. }
  31990. this._colorGradingBGR = value;
  31991. this._updateParameters();
  31992. },
  31993. enumerable: true,
  31994. configurable: true
  31995. });
  31996. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  31997. /**
  31998. * Gets the Exposure used in the effect.
  31999. */
  32000. get: function () {
  32001. return this._exposure;
  32002. },
  32003. /**
  32004. * Sets the Exposure used in the effect.
  32005. */
  32006. set: function (value) {
  32007. if (this._exposure === value) {
  32008. return;
  32009. }
  32010. this._exposure = value;
  32011. this._updateParameters();
  32012. },
  32013. enumerable: true,
  32014. configurable: true
  32015. });
  32016. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32017. /**
  32018. * Gets wether the tone mapping effect is enabled.
  32019. */
  32020. get: function () {
  32021. return this._toneMappingEnabled;
  32022. },
  32023. /**
  32024. * Sets wether the tone mapping effect is enabled.
  32025. */
  32026. set: function (value) {
  32027. if (this._toneMappingEnabled === value) {
  32028. return;
  32029. }
  32030. this._toneMappingEnabled = value;
  32031. this._updateParameters();
  32032. },
  32033. enumerable: true,
  32034. configurable: true
  32035. });
  32036. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32037. /**
  32038. * Gets the contrast used in the effect.
  32039. */
  32040. get: function () {
  32041. return this._contrast;
  32042. },
  32043. /**
  32044. * Sets the contrast used in the effect.
  32045. */
  32046. set: function (value) {
  32047. if (this._contrast === value) {
  32048. return;
  32049. }
  32050. this._contrast = value;
  32051. this._updateParameters();
  32052. },
  32053. enumerable: true,
  32054. configurable: true
  32055. });
  32056. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32057. /**
  32058. * Gets the vignette blend mode allowing different kind of effect.
  32059. */
  32060. get: function () {
  32061. return this._vignetteBlendMode;
  32062. },
  32063. /**
  32064. * Sets the vignette blend mode allowing different kind of effect.
  32065. */
  32066. set: function (value) {
  32067. if (this._vignetteBlendMode === value) {
  32068. return;
  32069. }
  32070. this._vignetteBlendMode = value;
  32071. this._updateParameters();
  32072. },
  32073. enumerable: true,
  32074. configurable: true
  32075. });
  32076. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32077. /**
  32078. * Gets wether the vignette effect is enabled.
  32079. */
  32080. get: function () {
  32081. return this._vignetteEnabled;
  32082. },
  32083. /**
  32084. * Sets wether the vignette effect is enabled.
  32085. */
  32086. set: function (value) {
  32087. if (this._vignetteEnabled === value) {
  32088. return;
  32089. }
  32090. this._vignetteEnabled = value;
  32091. this._updateParameters();
  32092. },
  32093. enumerable: true,
  32094. configurable: true
  32095. });
  32096. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32097. /**
  32098. * Gets wether the image processing is applied through a post process or not.
  32099. */
  32100. get: function () {
  32101. return this._applyByPostProcess;
  32102. },
  32103. /**
  32104. * Sets wether the image processing is applied through a post process or not.
  32105. */
  32106. set: function (value) {
  32107. if (this._applyByPostProcess === value) {
  32108. return;
  32109. }
  32110. this._applyByPostProcess = value;
  32111. this._updateParameters();
  32112. },
  32113. enumerable: true,
  32114. configurable: true
  32115. });
  32116. /**
  32117. * Method called each time the image processing information changes requires to recompile the effect.
  32118. */
  32119. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32120. this.onUpdateParameters.notifyObservers(this);
  32121. };
  32122. ImageProcessingConfiguration.prototype.getClassName = function () {
  32123. return "ImageProcessingConfiguration";
  32124. };
  32125. /**
  32126. * Prepare the list of uniforms associated with the Image Processing effects.
  32127. * @param uniformsList The list of uniforms used in the effect
  32128. * @param defines the list of defines currently in use
  32129. */
  32130. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32131. if (defines.EXPOSURE) {
  32132. uniforms.push("exposureLinear");
  32133. }
  32134. if (defines.CONTRAST) {
  32135. uniforms.push("contrast");
  32136. }
  32137. if (defines.COLORGRADING) {
  32138. uniforms.push("colorTransformSettings");
  32139. }
  32140. if (defines.VIGNETTE) {
  32141. uniforms.push("vInverseScreenSize");
  32142. uniforms.push("vignetteSettings1");
  32143. uniforms.push("vignetteSettings2");
  32144. }
  32145. if (defines.COLORCURVES) {
  32146. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32147. }
  32148. };
  32149. /**
  32150. * Prepare the list of samplers associated with the Image Processing effects.
  32151. * @param uniformsList The list of uniforms used in the effect
  32152. * @param defines the list of defines currently in use
  32153. */
  32154. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32155. if (defines.COLORGRADING) {
  32156. samplersList.push("txColorTransform");
  32157. }
  32158. };
  32159. /**
  32160. * Prepare the list of defines associated to the shader.
  32161. * @param defines the list of defines to complete
  32162. */
  32163. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32164. if (forPostProcess === void 0) { forPostProcess = false; }
  32165. if (forPostProcess !== this.applyByPostProcess) {
  32166. defines.VIGNETTE = false;
  32167. defines.TONEMAPPING = false;
  32168. defines.CONTRAST = false;
  32169. defines.EXPOSURE = false;
  32170. defines.COLORCURVES = false;
  32171. defines.COLORGRADING = false;
  32172. defines.COLORGRADING3D = false;
  32173. defines.IMAGEPROCESSING = false;
  32174. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32175. return;
  32176. }
  32177. defines.VIGNETTE = this.vignetteEnabled;
  32178. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32179. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32180. defines.TONEMAPPING = this.toneMappingEnabled;
  32181. defines.CONTRAST = (this.contrast !== 1.0);
  32182. defines.EXPOSURE = (this.exposure !== 1.0);
  32183. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32184. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32185. if (defines.COLORGRADING) {
  32186. var texture = this.colorGradingTexture;
  32187. defines.COLORGRADING3D = (texture.getScene().getEngine().webGLVersion > 1) ? true : false;
  32188. }
  32189. else {
  32190. defines.COLORGRADING3D = false;
  32191. }
  32192. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32193. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32194. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32195. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32196. };
  32197. /**
  32198. * Returns true if all the image processing information are ready.
  32199. */
  32200. ImageProcessingConfiguration.prototype.isReady = function () {
  32201. // Color Grading texure can not be none blocking.
  32202. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32203. };
  32204. /**
  32205. * Binds the image processing to the shader.
  32206. * @param effect The effect to bind to
  32207. */
  32208. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32209. if (aspectRatio === void 0) { aspectRatio = 1; }
  32210. // Color Curves
  32211. if (this._colorCurvesEnabled && this.colorCurves) {
  32212. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32213. }
  32214. // Vignette
  32215. if (this._vignetteEnabled) {
  32216. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32217. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32218. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32219. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32220. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32221. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32222. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32223. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32224. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32225. var vignettePower = -2.0 * this.vignetteWeight;
  32226. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32227. }
  32228. // Exposure
  32229. effect.setFloat("exposureLinear", this.exposure);
  32230. // Contrast
  32231. effect.setFloat("contrast", this.contrast);
  32232. // Color transform settings
  32233. if (this.colorGradingTexture) {
  32234. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32235. var textureSize = this.colorGradingTexture.getSize().height;
  32236. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32237. 0.5 / textureSize, // textureOffset
  32238. textureSize, // textureSize
  32239. this.colorGradingTexture.level // weight
  32240. );
  32241. }
  32242. };
  32243. /**
  32244. * Clones the current image processing instance.
  32245. * @return The cloned image processing
  32246. */
  32247. ImageProcessingConfiguration.prototype.clone = function () {
  32248. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32249. };
  32250. /**
  32251. * Serializes the current image processing instance to a json representation.
  32252. * @return a JSON representation
  32253. */
  32254. ImageProcessingConfiguration.prototype.serialize = function () {
  32255. return BABYLON.SerializationHelper.Serialize(this);
  32256. };
  32257. /**
  32258. * Parses the image processing from a json representation.
  32259. * @param source the JSON source to parse
  32260. * @return The parsed image processing
  32261. */
  32262. ImageProcessingConfiguration.Parse = function (source) {
  32263. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32264. };
  32265. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32266. /**
  32267. * Used to apply the vignette as a mix with the pixel color.
  32268. */
  32269. get: function () {
  32270. return this._VIGNETTEMODE_MULTIPLY;
  32271. },
  32272. enumerable: true,
  32273. configurable: true
  32274. });
  32275. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32276. /**
  32277. * Used to apply the vignette as a replacement of the pixel color.
  32278. */
  32279. get: function () {
  32280. return this._VIGNETTEMODE_OPAQUE;
  32281. },
  32282. enumerable: true,
  32283. configurable: true
  32284. });
  32285. // Static constants associated to the image processing.
  32286. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32287. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32288. __decorate([
  32289. BABYLON.serializeAsColorCurves()
  32290. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32291. __decorate([
  32292. BABYLON.serialize()
  32293. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32294. __decorate([
  32295. BABYLON.serializeAsTexture()
  32296. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32297. __decorate([
  32298. BABYLON.serialize()
  32299. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32300. __decorate([
  32301. BABYLON.serialize()
  32302. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32303. __decorate([
  32304. BABYLON.serialize()
  32305. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32306. __decorate([
  32307. BABYLON.serialize()
  32308. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32309. __decorate([
  32310. BABYLON.serialize()
  32311. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32312. __decorate([
  32313. BABYLON.serialize()
  32314. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32315. __decorate([
  32316. BABYLON.serialize()
  32317. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32318. __decorate([
  32319. BABYLON.serialize()
  32320. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32321. __decorate([
  32322. BABYLON.serialize()
  32323. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32324. __decorate([
  32325. BABYLON.serialize()
  32326. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32327. __decorate([
  32328. BABYLON.serializeAsColor4()
  32329. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32330. __decorate([
  32331. BABYLON.serialize()
  32332. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32333. __decorate([
  32334. BABYLON.serialize()
  32335. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32336. __decorate([
  32337. BABYLON.serialize()
  32338. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32339. __decorate([
  32340. BABYLON.serialize()
  32341. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32342. return ImageProcessingConfiguration;
  32343. }());
  32344. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  32345. })(BABYLON || (BABYLON = {}));
  32346. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  32347. var BABYLON;
  32348. (function (BABYLON) {
  32349. /**
  32350. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  32351. * It can help converting any input color in a desired output one. This can then be used to create effects
  32352. * from sepia, black and white to sixties or futuristic rendering...
  32353. *
  32354. * The only supported format is currently 3dl.
  32355. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  32356. */
  32357. var ColorGradingTexture = /** @class */ (function (_super) {
  32358. __extends(ColorGradingTexture, _super);
  32359. /**
  32360. * Instantiates a ColorGradingTexture from the following parameters.
  32361. *
  32362. * @param url The location of the color gradind data (currently only supporting 3dl)
  32363. * @param scene The scene the texture will be used in
  32364. */
  32365. function ColorGradingTexture(url, scene) {
  32366. var _this = _super.call(this, scene) || this;
  32367. if (!url) {
  32368. return _this;
  32369. }
  32370. _this._engine = scene.getEngine();
  32371. _this._textureMatrix = BABYLON.Matrix.Identity();
  32372. _this.name = url;
  32373. _this.url = url;
  32374. _this.hasAlpha = false;
  32375. _this.isCube = false;
  32376. _this.is3D = _this._engine.webGLVersion > 1;
  32377. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32378. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32379. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32380. _this.anisotropicFilteringLevel = 1;
  32381. _this._texture = _this._getFromCache(url, true);
  32382. if (!_this._texture) {
  32383. if (!scene.useDelayedTextureLoading) {
  32384. _this.loadTexture();
  32385. }
  32386. else {
  32387. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32388. }
  32389. }
  32390. return _this;
  32391. }
  32392. /**
  32393. * Returns the texture matrix used in most of the material.
  32394. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  32395. */
  32396. ColorGradingTexture.prototype.getTextureMatrix = function () {
  32397. return this._textureMatrix;
  32398. };
  32399. /**
  32400. * Occurs when the file being loaded is a .3dl LUT file.
  32401. */
  32402. ColorGradingTexture.prototype.load3dlTexture = function () {
  32403. var engine = this._engine;
  32404. var texture;
  32405. if (engine.webGLVersion === 1) {
  32406. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32407. }
  32408. else {
  32409. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32410. }
  32411. this._texture = texture;
  32412. var callback = function (text) {
  32413. var data = null;
  32414. var tempData = null;
  32415. var line;
  32416. var lines = text.split('\n');
  32417. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  32418. var maxColor = 0;
  32419. for (var i = 0; i < lines.length; i++) {
  32420. line = lines[i];
  32421. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  32422. continue;
  32423. if (line.indexOf('#') === 0)
  32424. continue;
  32425. var words = line.split(" ");
  32426. if (size === 0) {
  32427. // Number of space + one
  32428. size = words.length;
  32429. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  32430. tempData = new Float32Array(size * size * size * 4);
  32431. continue;
  32432. }
  32433. if (size != 0) {
  32434. var r = Math.max(parseInt(words[0]), 0);
  32435. var g = Math.max(parseInt(words[1]), 0);
  32436. var b = Math.max(parseInt(words[2]), 0);
  32437. maxColor = Math.max(r, maxColor);
  32438. maxColor = Math.max(g, maxColor);
  32439. maxColor = Math.max(b, maxColor);
  32440. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  32441. if (tempData) {
  32442. tempData[pixelStorageIndex + 0] = r;
  32443. tempData[pixelStorageIndex + 1] = g;
  32444. tempData[pixelStorageIndex + 2] = b;
  32445. }
  32446. pixelIndexSlice++;
  32447. if (pixelIndexSlice % size == 0) {
  32448. pixelIndexH++;
  32449. pixelIndexSlice = 0;
  32450. if (pixelIndexH % size == 0) {
  32451. pixelIndexW++;
  32452. pixelIndexH = 0;
  32453. }
  32454. }
  32455. }
  32456. }
  32457. if (tempData && data) {
  32458. for (var i = 0; i < tempData.length; i++) {
  32459. if (i > 0 && (i + 1) % 4 === 0) {
  32460. data[i] = 255;
  32461. }
  32462. else {
  32463. var value = tempData[i];
  32464. data[i] = (value / maxColor * 255);
  32465. }
  32466. }
  32467. }
  32468. if (texture.is3D) {
  32469. texture.updateSize(size, size, size);
  32470. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32471. }
  32472. else {
  32473. texture.updateSize(size * size, size);
  32474. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32475. }
  32476. };
  32477. BABYLON.Tools.LoadFile(this.url, callback);
  32478. return this._texture;
  32479. };
  32480. /**
  32481. * Starts the loading process of the texture.
  32482. */
  32483. ColorGradingTexture.prototype.loadTexture = function () {
  32484. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  32485. this.load3dlTexture();
  32486. }
  32487. };
  32488. /**
  32489. * Clones the color gradind texture.
  32490. */
  32491. ColorGradingTexture.prototype.clone = function () {
  32492. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  32493. // Base texture
  32494. newTexture.level = this.level;
  32495. return newTexture;
  32496. };
  32497. /**
  32498. * Called during delayed load for textures.
  32499. */
  32500. ColorGradingTexture.prototype.delayLoad = function () {
  32501. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32502. return;
  32503. }
  32504. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32505. this._texture = this._getFromCache(this.url, true);
  32506. if (!this._texture) {
  32507. this.loadTexture();
  32508. }
  32509. };
  32510. /**
  32511. * Parses a color grading texture serialized by Babylon.
  32512. * @param parsedTexture The texture information being parsedTexture
  32513. * @param scene The scene to load the texture in
  32514. * @param rootUrl The root url of the data assets to load
  32515. * @return A color gradind texture
  32516. */
  32517. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32518. var texture = null;
  32519. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  32520. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  32521. texture.name = parsedTexture.name;
  32522. texture.level = parsedTexture.level;
  32523. }
  32524. return texture;
  32525. };
  32526. /**
  32527. * Serializes the LUT texture to json format.
  32528. */
  32529. ColorGradingTexture.prototype.serialize = function () {
  32530. if (!this.name) {
  32531. return null;
  32532. }
  32533. var serializationObject = {};
  32534. serializationObject.name = this.name;
  32535. serializationObject.level = this.level;
  32536. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32537. return serializationObject;
  32538. };
  32539. /**
  32540. * Empty line regex stored for GC.
  32541. */
  32542. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32543. return ColorGradingTexture;
  32544. }(BABYLON.BaseTexture));
  32545. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32546. })(BABYLON || (BABYLON = {}));
  32547. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32548. var BABYLON;
  32549. (function (BABYLON) {
  32550. /**
  32551. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32552. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32553. * 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;
  32554. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32555. */
  32556. var ColorCurves = /** @class */ (function () {
  32557. function ColorCurves() {
  32558. this._dirty = true;
  32559. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32560. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32561. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32562. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32563. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32564. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32565. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32566. this._globalHue = 30;
  32567. this._globalDensity = 0;
  32568. this._globalSaturation = 0;
  32569. this._globalExposure = 0;
  32570. this._highlightsHue = 30;
  32571. this._highlightsDensity = 0;
  32572. this._highlightsSaturation = 0;
  32573. this._highlightsExposure = 0;
  32574. this._midtonesHue = 30;
  32575. this._midtonesDensity = 0;
  32576. this._midtonesSaturation = 0;
  32577. this._midtonesExposure = 0;
  32578. this._shadowsHue = 30;
  32579. this._shadowsDensity = 0;
  32580. this._shadowsSaturation = 0;
  32581. this._shadowsExposure = 0;
  32582. }
  32583. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32584. /**
  32585. * Gets the global Hue value.
  32586. * 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).
  32587. */
  32588. get: function () {
  32589. return this._globalHue;
  32590. },
  32591. /**
  32592. * Sets the global Hue value.
  32593. * 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).
  32594. */
  32595. set: function (value) {
  32596. this._globalHue = value;
  32597. this._dirty = true;
  32598. },
  32599. enumerable: true,
  32600. configurable: true
  32601. });
  32602. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32603. /**
  32604. * Gets the global Density value.
  32605. * 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.
  32606. * Values less than zero provide a filter of opposite hue.
  32607. */
  32608. get: function () {
  32609. return this._globalDensity;
  32610. },
  32611. /**
  32612. * Sets the global Density value.
  32613. * 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.
  32614. * Values less than zero provide a filter of opposite hue.
  32615. */
  32616. set: function (value) {
  32617. this._globalDensity = value;
  32618. this._dirty = true;
  32619. },
  32620. enumerable: true,
  32621. configurable: true
  32622. });
  32623. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32624. /**
  32625. * Gets the global Saturation value.
  32626. * 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.
  32627. */
  32628. get: function () {
  32629. return this._globalSaturation;
  32630. },
  32631. /**
  32632. * Sets the global Saturation value.
  32633. * 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.
  32634. */
  32635. set: function (value) {
  32636. this._globalSaturation = value;
  32637. this._dirty = true;
  32638. },
  32639. enumerable: true,
  32640. configurable: true
  32641. });
  32642. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32643. /**
  32644. * Gets the highlights Hue value.
  32645. * 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).
  32646. */
  32647. get: function () {
  32648. return this._highlightsHue;
  32649. },
  32650. /**
  32651. * Sets the highlights Hue value.
  32652. * 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).
  32653. */
  32654. set: function (value) {
  32655. this._highlightsHue = value;
  32656. this._dirty = true;
  32657. },
  32658. enumerable: true,
  32659. configurable: true
  32660. });
  32661. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32662. /**
  32663. * Gets the highlights Density value.
  32664. * 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.
  32665. * Values less than zero provide a filter of opposite hue.
  32666. */
  32667. get: function () {
  32668. return this._highlightsDensity;
  32669. },
  32670. /**
  32671. * Sets the highlights Density value.
  32672. * 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.
  32673. * Values less than zero provide a filter of opposite hue.
  32674. */
  32675. set: function (value) {
  32676. this._highlightsDensity = value;
  32677. this._dirty = true;
  32678. },
  32679. enumerable: true,
  32680. configurable: true
  32681. });
  32682. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  32683. /**
  32684. * Gets the highlights Saturation value.
  32685. * 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.
  32686. */
  32687. get: function () {
  32688. return this._highlightsSaturation;
  32689. },
  32690. /**
  32691. * Sets the highlights Saturation value.
  32692. * 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.
  32693. */
  32694. set: function (value) {
  32695. this._highlightsSaturation = value;
  32696. this._dirty = true;
  32697. },
  32698. enumerable: true,
  32699. configurable: true
  32700. });
  32701. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  32702. /**
  32703. * Gets the highlights Exposure value.
  32704. * 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.
  32705. */
  32706. get: function () {
  32707. return this._highlightsExposure;
  32708. },
  32709. /**
  32710. * Sets the highlights Exposure value.
  32711. * 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.
  32712. */
  32713. set: function (value) {
  32714. this._highlightsExposure = value;
  32715. this._dirty = true;
  32716. },
  32717. enumerable: true,
  32718. configurable: true
  32719. });
  32720. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  32721. /**
  32722. * Gets the midtones Hue value.
  32723. * 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).
  32724. */
  32725. get: function () {
  32726. return this._midtonesHue;
  32727. },
  32728. /**
  32729. * Sets the midtones Hue value.
  32730. * 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).
  32731. */
  32732. set: function (value) {
  32733. this._midtonesHue = value;
  32734. this._dirty = true;
  32735. },
  32736. enumerable: true,
  32737. configurable: true
  32738. });
  32739. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  32740. /**
  32741. * Gets the midtones Density value.
  32742. * 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.
  32743. * Values less than zero provide a filter of opposite hue.
  32744. */
  32745. get: function () {
  32746. return this._midtonesDensity;
  32747. },
  32748. /**
  32749. * Sets the midtones Density value.
  32750. * 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.
  32751. * Values less than zero provide a filter of opposite hue.
  32752. */
  32753. set: function (value) {
  32754. this._midtonesDensity = value;
  32755. this._dirty = true;
  32756. },
  32757. enumerable: true,
  32758. configurable: true
  32759. });
  32760. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  32761. /**
  32762. * Gets the midtones Saturation value.
  32763. * 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.
  32764. */
  32765. get: function () {
  32766. return this._midtonesSaturation;
  32767. },
  32768. /**
  32769. * Sets the midtones Saturation value.
  32770. * 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.
  32771. */
  32772. set: function (value) {
  32773. this._midtonesSaturation = value;
  32774. this._dirty = true;
  32775. },
  32776. enumerable: true,
  32777. configurable: true
  32778. });
  32779. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  32780. /**
  32781. * Gets the midtones Exposure value.
  32782. * 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.
  32783. */
  32784. get: function () {
  32785. return this._midtonesExposure;
  32786. },
  32787. /**
  32788. * Sets the midtones Exposure value.
  32789. * 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.
  32790. */
  32791. set: function (value) {
  32792. this._midtonesExposure = value;
  32793. this._dirty = true;
  32794. },
  32795. enumerable: true,
  32796. configurable: true
  32797. });
  32798. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  32799. /**
  32800. * Gets the shadows Hue value.
  32801. * 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).
  32802. */
  32803. get: function () {
  32804. return this._shadowsHue;
  32805. },
  32806. /**
  32807. * Sets the shadows Hue value.
  32808. * 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).
  32809. */
  32810. set: function (value) {
  32811. this._shadowsHue = value;
  32812. this._dirty = true;
  32813. },
  32814. enumerable: true,
  32815. configurable: true
  32816. });
  32817. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  32818. /**
  32819. * Gets the shadows Density value.
  32820. * 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.
  32821. * Values less than zero provide a filter of opposite hue.
  32822. */
  32823. get: function () {
  32824. return this._shadowsDensity;
  32825. },
  32826. /**
  32827. * Sets the shadows Density value.
  32828. * 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.
  32829. * Values less than zero provide a filter of opposite hue.
  32830. */
  32831. set: function (value) {
  32832. this._shadowsDensity = value;
  32833. this._dirty = true;
  32834. },
  32835. enumerable: true,
  32836. configurable: true
  32837. });
  32838. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  32839. /**
  32840. * Gets the shadows Saturation value.
  32841. * 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.
  32842. */
  32843. get: function () {
  32844. return this._shadowsSaturation;
  32845. },
  32846. /**
  32847. * Sets the shadows Saturation value.
  32848. * 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.
  32849. */
  32850. set: function (value) {
  32851. this._shadowsSaturation = value;
  32852. this._dirty = true;
  32853. },
  32854. enumerable: true,
  32855. configurable: true
  32856. });
  32857. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  32858. /**
  32859. * Gets the shadows Exposure value.
  32860. * 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.
  32861. */
  32862. get: function () {
  32863. return this._shadowsExposure;
  32864. },
  32865. /**
  32866. * Sets the shadows Exposure value.
  32867. * 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.
  32868. */
  32869. set: function (value) {
  32870. this._shadowsExposure = value;
  32871. this._dirty = true;
  32872. },
  32873. enumerable: true,
  32874. configurable: true
  32875. });
  32876. ColorCurves.prototype.getClassName = function () {
  32877. return "ColorCurves";
  32878. };
  32879. /**
  32880. * Binds the color curves to the shader.
  32881. * @param colorCurves The color curve to bind
  32882. * @param effect The effect to bind to
  32883. */
  32884. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  32885. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  32886. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  32887. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  32888. if (colorCurves._dirty) {
  32889. colorCurves._dirty = false;
  32890. // Fill in global info.
  32891. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  32892. // Compute highlights info.
  32893. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  32894. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  32895. // Compute midtones info.
  32896. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  32897. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  32898. // Compute shadows info.
  32899. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  32900. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  32901. // Compute deltas (neutral is midtones).
  32902. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  32903. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  32904. }
  32905. if (effect) {
  32906. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  32907. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  32908. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  32909. }
  32910. };
  32911. /**
  32912. * Prepare the list of uniforms associated with the ColorCurves effects.
  32913. * @param uniformsList The list of uniforms used in the effect
  32914. */
  32915. ColorCurves.PrepareUniforms = function (uniformsList) {
  32916. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  32917. };
  32918. /**
  32919. * Returns color grading data based on a hue, density, saturation and exposure value.
  32920. * @param filterHue The hue of the color filter.
  32921. * @param filterDensity The density of the color filter.
  32922. * @param saturation The saturation.
  32923. * @param exposure The exposure.
  32924. * @param result The result data container.
  32925. */
  32926. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  32927. if (hue == null) {
  32928. return;
  32929. }
  32930. hue = ColorCurves.clamp(hue, 0, 360);
  32931. density = ColorCurves.clamp(density, -100, 100);
  32932. saturation = ColorCurves.clamp(saturation, -100, 100);
  32933. exposure = ColorCurves.clamp(exposure, -100, 100);
  32934. // Remap the slider/config filter density with non-linear mapping and also scale by half
  32935. // so that the maximum filter density is only 50% control. This provides fine control
  32936. // for small values and reasonable range.
  32937. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  32938. density *= 0.5;
  32939. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  32940. if (density < 0) {
  32941. density *= -1;
  32942. hue = (hue + 180) % 360;
  32943. }
  32944. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  32945. result.scaleToRef(2, result);
  32946. result.a = 1 + 0.01 * saturation;
  32947. };
  32948. /**
  32949. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  32950. * @param value The input slider value in range [-100,100].
  32951. * @returns Adjusted value.
  32952. */
  32953. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  32954. value /= 100;
  32955. var x = Math.abs(value);
  32956. x = Math.pow(x, 2);
  32957. if (value < 0) {
  32958. x *= -1;
  32959. }
  32960. x *= 100;
  32961. return x;
  32962. };
  32963. /**
  32964. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  32965. * @param hue The hue (H) input.
  32966. * @param saturation The saturation (S) input.
  32967. * @param brightness The brightness (B) input.
  32968. * @result An RGBA color represented as Vector4.
  32969. */
  32970. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  32971. var h = ColorCurves.clamp(hue, 0, 360);
  32972. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  32973. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  32974. if (s === 0) {
  32975. result.r = v;
  32976. result.g = v;
  32977. result.b = v;
  32978. }
  32979. else {
  32980. // sector 0 to 5
  32981. h /= 60;
  32982. var i = Math.floor(h);
  32983. // fractional part of h
  32984. var f = h - i;
  32985. var p = v * (1 - s);
  32986. var q = v * (1 - s * f);
  32987. var t = v * (1 - s * (1 - f));
  32988. switch (i) {
  32989. case 0:
  32990. result.r = v;
  32991. result.g = t;
  32992. result.b = p;
  32993. break;
  32994. case 1:
  32995. result.r = q;
  32996. result.g = v;
  32997. result.b = p;
  32998. break;
  32999. case 2:
  33000. result.r = p;
  33001. result.g = v;
  33002. result.b = t;
  33003. break;
  33004. case 3:
  33005. result.r = p;
  33006. result.g = q;
  33007. result.b = v;
  33008. break;
  33009. case 4:
  33010. result.r = t;
  33011. result.g = p;
  33012. result.b = v;
  33013. break;
  33014. default:// case 5:
  33015. result.r = v;
  33016. result.g = p;
  33017. result.b = q;
  33018. break;
  33019. }
  33020. }
  33021. result.a = 1;
  33022. };
  33023. /**
  33024. * Returns a value clamped between min and max
  33025. * @param value The value to clamp
  33026. * @param min The minimum of value
  33027. * @param max The maximum of value
  33028. * @returns The clamped value.
  33029. */
  33030. ColorCurves.clamp = function (value, min, max) {
  33031. return Math.min(Math.max(value, min), max);
  33032. };
  33033. /**
  33034. * Clones the current color curve instance.
  33035. * @return The cloned curves
  33036. */
  33037. ColorCurves.prototype.clone = function () {
  33038. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33039. };
  33040. /**
  33041. * Serializes the current color curve instance to a json representation.
  33042. * @return a JSON representation
  33043. */
  33044. ColorCurves.prototype.serialize = function () {
  33045. return BABYLON.SerializationHelper.Serialize(this);
  33046. };
  33047. /**
  33048. * Parses the color curve from a json representation.
  33049. * @param source the JSON source to parse
  33050. * @return The parsed curves
  33051. */
  33052. ColorCurves.Parse = function (source) {
  33053. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33054. };
  33055. __decorate([
  33056. BABYLON.serialize()
  33057. ], ColorCurves.prototype, "_globalHue", void 0);
  33058. __decorate([
  33059. BABYLON.serialize()
  33060. ], ColorCurves.prototype, "_globalDensity", void 0);
  33061. __decorate([
  33062. BABYLON.serialize()
  33063. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33064. __decorate([
  33065. BABYLON.serialize()
  33066. ], ColorCurves.prototype, "_globalExposure", void 0);
  33067. __decorate([
  33068. BABYLON.serialize()
  33069. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33070. __decorate([
  33071. BABYLON.serialize()
  33072. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33073. __decorate([
  33074. BABYLON.serialize()
  33075. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33076. __decorate([
  33077. BABYLON.serialize()
  33078. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33079. __decorate([
  33080. BABYLON.serialize()
  33081. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33082. __decorate([
  33083. BABYLON.serialize()
  33084. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33085. __decorate([
  33086. BABYLON.serialize()
  33087. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33088. __decorate([
  33089. BABYLON.serialize()
  33090. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33091. return ColorCurves;
  33092. }());
  33093. BABYLON.ColorCurves = ColorCurves;
  33094. })(BABYLON || (BABYLON = {}));
  33095. //# sourceMappingURL=babylon.colorCurves.js.map
  33096. var BABYLON;
  33097. (function (BABYLON) {
  33098. var StandardMaterialDefines = /** @class */ (function (_super) {
  33099. __extends(StandardMaterialDefines, _super);
  33100. function StandardMaterialDefines() {
  33101. var _this = _super.call(this) || this;
  33102. _this.MAINUV1 = false;
  33103. _this.MAINUV2 = false;
  33104. _this.DIFFUSE = false;
  33105. _this.DIFFUSEDIRECTUV = 0;
  33106. _this.AMBIENT = false;
  33107. _this.AMBIENTDIRECTUV = 0;
  33108. _this.OPACITY = false;
  33109. _this.OPACITYDIRECTUV = 0;
  33110. _this.OPACITYRGB = false;
  33111. _this.REFLECTION = false;
  33112. _this.EMISSIVE = false;
  33113. _this.EMISSIVEDIRECTUV = 0;
  33114. _this.SPECULAR = false;
  33115. _this.SPECULARDIRECTUV = 0;
  33116. _this.BUMP = false;
  33117. _this.BUMPDIRECTUV = 0;
  33118. _this.PARALLAX = false;
  33119. _this.PARALLAXOCCLUSION = false;
  33120. _this.SPECULAROVERALPHA = false;
  33121. _this.CLIPPLANE = false;
  33122. _this.ALPHATEST = false;
  33123. _this.DEPTHPREPASS = false;
  33124. _this.ALPHAFROMDIFFUSE = false;
  33125. _this.POINTSIZE = false;
  33126. _this.FOG = false;
  33127. _this.SPECULARTERM = false;
  33128. _this.DIFFUSEFRESNEL = false;
  33129. _this.OPACITYFRESNEL = false;
  33130. _this.REFLECTIONFRESNEL = false;
  33131. _this.REFRACTIONFRESNEL = false;
  33132. _this.EMISSIVEFRESNEL = false;
  33133. _this.FRESNEL = false;
  33134. _this.NORMAL = false;
  33135. _this.UV1 = false;
  33136. _this.UV2 = false;
  33137. _this.VERTEXCOLOR = false;
  33138. _this.VERTEXALPHA = false;
  33139. _this.NUM_BONE_INFLUENCERS = 0;
  33140. _this.BonesPerMesh = 0;
  33141. _this.INSTANCES = false;
  33142. _this.GLOSSINESS = false;
  33143. _this.ROUGHNESS = false;
  33144. _this.EMISSIVEASILLUMINATION = false;
  33145. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33146. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33147. _this.LIGHTMAP = false;
  33148. _this.LIGHTMAPDIRECTUV = 0;
  33149. _this.USELIGHTMAPASSHADOWMAP = false;
  33150. _this.REFLECTIONMAP_3D = false;
  33151. _this.REFLECTIONMAP_SPHERICAL = false;
  33152. _this.REFLECTIONMAP_PLANAR = false;
  33153. _this.REFLECTIONMAP_CUBIC = false;
  33154. _this.REFLECTIONMAP_PROJECTION = false;
  33155. _this.REFLECTIONMAP_SKYBOX = false;
  33156. _this.REFLECTIONMAP_EXPLICIT = false;
  33157. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33158. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33159. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33160. _this.INVERTCUBICMAP = false;
  33161. _this.LOGARITHMICDEPTH = false;
  33162. _this.REFRACTION = false;
  33163. _this.REFRACTIONMAP_3D = false;
  33164. _this.REFLECTIONOVERALPHA = false;
  33165. _this.TWOSIDEDLIGHTING = false;
  33166. _this.SHADOWFLOAT = false;
  33167. _this.MORPHTARGETS = false;
  33168. _this.MORPHTARGETS_NORMAL = false;
  33169. _this.MORPHTARGETS_TANGENT = false;
  33170. _this.NUM_MORPH_INFLUENCERS = 0;
  33171. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33172. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33173. _this.IMAGEPROCESSING = false;
  33174. _this.VIGNETTE = false;
  33175. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33176. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33177. _this.TONEMAPPING = false;
  33178. _this.CONTRAST = false;
  33179. _this.COLORCURVES = false;
  33180. _this.COLORGRADING = false;
  33181. _this.COLORGRADING3D = false;
  33182. _this.SAMPLER3DGREENDEPTH = false;
  33183. _this.SAMPLER3DBGRMAP = false;
  33184. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33185. _this.EXPOSURE = false;
  33186. _this.rebuild();
  33187. return _this;
  33188. }
  33189. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33190. var modes = [
  33191. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33192. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33193. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33194. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33195. ];
  33196. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33197. var mode = modes_1[_i];
  33198. this[mode] = (mode === modeToEnable);
  33199. }
  33200. };
  33201. return StandardMaterialDefines;
  33202. }(BABYLON.MaterialDefines));
  33203. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33204. var StandardMaterial = /** @class */ (function (_super) {
  33205. __extends(StandardMaterial, _super);
  33206. function StandardMaterial(name, scene) {
  33207. var _this = _super.call(this, name, scene) || this;
  33208. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33209. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33210. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33211. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33212. _this.specularPower = 64;
  33213. _this._useAlphaFromDiffuseTexture = false;
  33214. _this._useEmissiveAsIllumination = false;
  33215. _this._linkEmissiveWithDiffuse = false;
  33216. _this._useSpecularOverAlpha = false;
  33217. _this._useReflectionOverAlpha = false;
  33218. _this._disableLighting = false;
  33219. _this._useParallax = false;
  33220. _this._useParallaxOcclusion = false;
  33221. _this.parallaxScaleBias = 0.05;
  33222. _this._roughness = 0;
  33223. _this.indexOfRefraction = 0.98;
  33224. _this.invertRefractionY = true;
  33225. _this._useLightmapAsShadowmap = false;
  33226. _this._useReflectionFresnelFromSpecular = false;
  33227. _this._useGlossinessFromSpecularMapAlpha = false;
  33228. _this._maxSimultaneousLights = 4;
  33229. /**
  33230. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33231. */
  33232. _this._invertNormalMapX = false;
  33233. /**
  33234. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33235. */
  33236. _this._invertNormalMapY = false;
  33237. /**
  33238. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33239. */
  33240. _this._twoSidedLighting = false;
  33241. _this._renderTargets = new BABYLON.SmartArray(16);
  33242. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33243. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33244. // Setup the default processing configuration to the scene.
  33245. _this._attachImageProcessingConfiguration(null);
  33246. _this.getRenderTargetTextures = function () {
  33247. _this._renderTargets.reset();
  33248. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33249. _this._renderTargets.push(_this._reflectionTexture);
  33250. }
  33251. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33252. _this._renderTargets.push(_this._refractionTexture);
  33253. }
  33254. return _this._renderTargets;
  33255. };
  33256. return _this;
  33257. }
  33258. ;
  33259. ;
  33260. ;
  33261. ;
  33262. ;
  33263. ;
  33264. ;
  33265. ;
  33266. ;
  33267. ;
  33268. ;
  33269. ;
  33270. ;
  33271. ;
  33272. ;
  33273. ;
  33274. ;
  33275. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33276. /**
  33277. * Gets the image processing configuration used either in this material.
  33278. */
  33279. get: function () {
  33280. return this._imageProcessingConfiguration;
  33281. },
  33282. /**
  33283. * Sets the Default image processing configuration used either in the this material.
  33284. *
  33285. * If sets to null, the scene one is in use.
  33286. */
  33287. set: function (value) {
  33288. this._attachImageProcessingConfiguration(value);
  33289. // Ensure the effect will be rebuilt.
  33290. this._markAllSubMeshesAsTexturesDirty();
  33291. },
  33292. enumerable: true,
  33293. configurable: true
  33294. });
  33295. /**
  33296. * Attaches a new image processing configuration to the Standard Material.
  33297. * @param configuration
  33298. */
  33299. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33300. var _this = this;
  33301. if (configuration === this._imageProcessingConfiguration) {
  33302. return;
  33303. }
  33304. // Detaches observer.
  33305. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33306. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33307. }
  33308. // Pick the scene configuration if needed.
  33309. if (!configuration) {
  33310. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33311. }
  33312. else {
  33313. this._imageProcessingConfiguration = configuration;
  33314. }
  33315. // Attaches observer.
  33316. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33317. _this._markAllSubMeshesAsImageProcessingDirty();
  33318. });
  33319. };
  33320. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33321. /**
  33322. * Gets wether the color curves effect is enabled.
  33323. */
  33324. get: function () {
  33325. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33326. },
  33327. /**
  33328. * Sets wether the color curves effect is enabled.
  33329. */
  33330. set: function (value) {
  33331. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33332. },
  33333. enumerable: true,
  33334. configurable: true
  33335. });
  33336. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33337. /**
  33338. * Gets wether the color grading effect is enabled.
  33339. */
  33340. get: function () {
  33341. return this.imageProcessingConfiguration.colorGradingEnabled;
  33342. },
  33343. /**
  33344. * Gets wether the color grading effect is enabled.
  33345. */
  33346. set: function (value) {
  33347. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33348. },
  33349. enumerable: true,
  33350. configurable: true
  33351. });
  33352. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  33353. /**
  33354. * Gets wether tonemapping is enabled or not.
  33355. */
  33356. get: function () {
  33357. return this._imageProcessingConfiguration.toneMappingEnabled;
  33358. },
  33359. /**
  33360. * Sets wether tonemapping is enabled or not
  33361. */
  33362. set: function (value) {
  33363. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33364. },
  33365. enumerable: true,
  33366. configurable: true
  33367. });
  33368. ;
  33369. ;
  33370. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  33371. /**
  33372. * The camera exposure used on this material.
  33373. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33374. * This corresponds to a photographic exposure.
  33375. */
  33376. get: function () {
  33377. return this._imageProcessingConfiguration.exposure;
  33378. },
  33379. /**
  33380. * The camera exposure used on this material.
  33381. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33382. * This corresponds to a photographic exposure.
  33383. */
  33384. set: function (value) {
  33385. this._imageProcessingConfiguration.exposure = value;
  33386. },
  33387. enumerable: true,
  33388. configurable: true
  33389. });
  33390. ;
  33391. ;
  33392. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  33393. /**
  33394. * Gets The camera contrast used on this material.
  33395. */
  33396. get: function () {
  33397. return this._imageProcessingConfiguration.contrast;
  33398. },
  33399. /**
  33400. * Sets The camera contrast used on this material.
  33401. */
  33402. set: function (value) {
  33403. this._imageProcessingConfiguration.contrast = value;
  33404. },
  33405. enumerable: true,
  33406. configurable: true
  33407. });
  33408. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  33409. /**
  33410. * Gets the Color Grading 2D Lookup Texture.
  33411. */
  33412. get: function () {
  33413. return this._imageProcessingConfiguration.colorGradingTexture;
  33414. },
  33415. /**
  33416. * Sets the Color Grading 2D Lookup Texture.
  33417. */
  33418. set: function (value) {
  33419. this._imageProcessingConfiguration.colorGradingTexture = value;
  33420. },
  33421. enumerable: true,
  33422. configurable: true
  33423. });
  33424. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  33425. /**
  33426. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33427. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33428. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  33429. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33430. */
  33431. get: function () {
  33432. return this._imageProcessingConfiguration.colorCurves;
  33433. },
  33434. /**
  33435. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33436. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33437. * 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;
  33438. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33439. */
  33440. set: function (value) {
  33441. this._imageProcessingConfiguration.colorCurves = value;
  33442. },
  33443. enumerable: true,
  33444. configurable: true
  33445. });
  33446. StandardMaterial.prototype.getClassName = function () {
  33447. return "StandardMaterial";
  33448. };
  33449. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  33450. get: function () {
  33451. return this._useLogarithmicDepth;
  33452. },
  33453. set: function (value) {
  33454. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33455. this._markAllSubMeshesAsMiscDirty();
  33456. },
  33457. enumerable: true,
  33458. configurable: true
  33459. });
  33460. StandardMaterial.prototype.needAlphaBlending = function () {
  33461. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  33462. };
  33463. StandardMaterial.prototype.needAlphaTesting = function () {
  33464. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  33465. };
  33466. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  33467. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  33468. };
  33469. StandardMaterial.prototype.getAlphaTestTexture = function () {
  33470. return this._diffuseTexture;
  33471. };
  33472. /**
  33473. * Child classes can use it to update shaders
  33474. */
  33475. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33476. if (useInstances === void 0) { useInstances = false; }
  33477. if (subMesh.effect && this.isFrozen) {
  33478. if (this._wasPreviouslyReady && subMesh.effect) {
  33479. return true;
  33480. }
  33481. }
  33482. if (!subMesh._materialDefines) {
  33483. subMesh._materialDefines = new StandardMaterialDefines();
  33484. }
  33485. var scene = this.getScene();
  33486. var defines = subMesh._materialDefines;
  33487. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33488. if (defines._renderId === scene.getRenderId()) {
  33489. return true;
  33490. }
  33491. }
  33492. var engine = scene.getEngine();
  33493. // Lights
  33494. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33495. // Textures
  33496. if (defines._areTexturesDirty) {
  33497. defines._needUVs = false;
  33498. defines.MAINUV1 = false;
  33499. defines.MAINUV2 = false;
  33500. if (scene.texturesEnabled) {
  33501. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33502. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  33503. return false;
  33504. }
  33505. else {
  33506. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  33507. }
  33508. }
  33509. else {
  33510. defines.DIFFUSE = false;
  33511. }
  33512. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33513. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33514. return false;
  33515. }
  33516. else {
  33517. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33518. }
  33519. }
  33520. else {
  33521. defines.AMBIENT = false;
  33522. }
  33523. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33524. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33525. return false;
  33526. }
  33527. else {
  33528. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33529. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33530. }
  33531. }
  33532. else {
  33533. defines.OPACITY = false;
  33534. }
  33535. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33536. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  33537. return false;
  33538. }
  33539. else {
  33540. defines._needNormals = true;
  33541. defines.REFLECTION = true;
  33542. defines.ROUGHNESS = (this._roughness > 0);
  33543. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  33544. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  33545. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  33546. switch (this._reflectionTexture.coordinatesMode) {
  33547. case BABYLON.Texture.CUBIC_MODE:
  33548. case BABYLON.Texture.INVCUBIC_MODE:
  33549. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33550. break;
  33551. case BABYLON.Texture.EXPLICIT_MODE:
  33552. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33553. break;
  33554. case BABYLON.Texture.PLANAR_MODE:
  33555. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33556. break;
  33557. case BABYLON.Texture.PROJECTION_MODE:
  33558. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33559. break;
  33560. case BABYLON.Texture.SKYBOX_MODE:
  33561. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33562. break;
  33563. case BABYLON.Texture.SPHERICAL_MODE:
  33564. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33565. break;
  33566. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33567. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33568. break;
  33569. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33570. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33571. break;
  33572. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33573. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33574. break;
  33575. }
  33576. }
  33577. }
  33578. else {
  33579. defines.REFLECTION = false;
  33580. }
  33581. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33582. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33583. return false;
  33584. }
  33585. else {
  33586. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33587. }
  33588. }
  33589. else {
  33590. defines.EMISSIVE = false;
  33591. }
  33592. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33593. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33594. return false;
  33595. }
  33596. else {
  33597. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33598. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33599. }
  33600. }
  33601. else {
  33602. defines.LIGHTMAP = false;
  33603. }
  33604. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33605. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33606. return false;
  33607. }
  33608. else {
  33609. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33610. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33611. }
  33612. }
  33613. else {
  33614. defines.SPECULAR = false;
  33615. }
  33616. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33617. // Bump texure can not be not blocking.
  33618. if (!this._bumpTexture.isReady()) {
  33619. return false;
  33620. }
  33621. else {
  33622. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33623. defines.PARALLAX = this._useParallax;
  33624. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33625. }
  33626. }
  33627. else {
  33628. defines.BUMP = false;
  33629. }
  33630. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33631. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33632. return false;
  33633. }
  33634. else {
  33635. defines._needUVs = true;
  33636. defines.REFRACTION = true;
  33637. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33638. }
  33639. }
  33640. else {
  33641. defines.REFRACTION = false;
  33642. }
  33643. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33644. }
  33645. else {
  33646. defines.DIFFUSE = false;
  33647. defines.AMBIENT = false;
  33648. defines.OPACITY = false;
  33649. defines.REFLECTION = false;
  33650. defines.EMISSIVE = false;
  33651. defines.LIGHTMAP = false;
  33652. defines.BUMP = false;
  33653. defines.REFRACTION = false;
  33654. }
  33655. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33656. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33657. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33658. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33659. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33660. }
  33661. if (defines._areImageProcessingDirty) {
  33662. if (!this._imageProcessingConfiguration.isReady()) {
  33663. return false;
  33664. }
  33665. this._imageProcessingConfiguration.prepareDefines(defines);
  33666. }
  33667. if (defines._areFresnelDirty) {
  33668. if (StandardMaterial.FresnelEnabled) {
  33669. // Fresnel
  33670. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33671. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  33672. this._reflectionFresnelParameters) {
  33673. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  33674. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  33675. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  33676. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  33677. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  33678. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  33679. defines._needNormals = true;
  33680. defines.FRESNEL = true;
  33681. }
  33682. }
  33683. else {
  33684. defines.FRESNEL = false;
  33685. }
  33686. }
  33687. // Misc.
  33688. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  33689. // Attribs
  33690. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  33691. // Values that need to be evaluated on every frame
  33692. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  33693. // Get correct effect
  33694. if (defines.isDirty) {
  33695. defines.markAsProcessed();
  33696. scene.resetCachedMaterial();
  33697. // Fallbacks
  33698. var fallbacks = new BABYLON.EffectFallbacks();
  33699. if (defines.REFLECTION) {
  33700. fallbacks.addFallback(0, "REFLECTION");
  33701. }
  33702. if (defines.SPECULAR) {
  33703. fallbacks.addFallback(0, "SPECULAR");
  33704. }
  33705. if (defines.BUMP) {
  33706. fallbacks.addFallback(0, "BUMP");
  33707. }
  33708. if (defines.PARALLAX) {
  33709. fallbacks.addFallback(1, "PARALLAX");
  33710. }
  33711. if (defines.PARALLAXOCCLUSION) {
  33712. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  33713. }
  33714. if (defines.SPECULAROVERALPHA) {
  33715. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  33716. }
  33717. if (defines.FOG) {
  33718. fallbacks.addFallback(1, "FOG");
  33719. }
  33720. if (defines.POINTSIZE) {
  33721. fallbacks.addFallback(0, "POINTSIZE");
  33722. }
  33723. if (defines.LOGARITHMICDEPTH) {
  33724. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  33725. }
  33726. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  33727. if (defines.SPECULARTERM) {
  33728. fallbacks.addFallback(0, "SPECULARTERM");
  33729. }
  33730. if (defines.DIFFUSEFRESNEL) {
  33731. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  33732. }
  33733. if (defines.OPACITYFRESNEL) {
  33734. fallbacks.addFallback(2, "OPACITYFRESNEL");
  33735. }
  33736. if (defines.REFLECTIONFRESNEL) {
  33737. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  33738. }
  33739. if (defines.EMISSIVEFRESNEL) {
  33740. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  33741. }
  33742. if (defines.FRESNEL) {
  33743. fallbacks.addFallback(4, "FRESNEL");
  33744. }
  33745. //Attributes
  33746. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33747. if (defines.NORMAL) {
  33748. attribs.push(BABYLON.VertexBuffer.NormalKind);
  33749. }
  33750. if (defines.UV1) {
  33751. attribs.push(BABYLON.VertexBuffer.UVKind);
  33752. }
  33753. if (defines.UV2) {
  33754. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33755. }
  33756. if (defines.VERTEXCOLOR) {
  33757. attribs.push(BABYLON.VertexBuffer.ColorKind);
  33758. }
  33759. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  33760. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  33761. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  33762. var shaderName = "default";
  33763. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  33764. "vFogInfos", "vFogColor", "pointSize",
  33765. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  33766. "mBones",
  33767. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  33768. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  33769. "logarithmicDepthConstant", "vTangentSpaceParams"
  33770. ];
  33771. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  33772. var uniformBuffers = ["Material", "Scene"];
  33773. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  33774. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  33775. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  33776. uniformsNames: uniforms,
  33777. uniformBuffersNames: uniformBuffers,
  33778. samplers: samplers,
  33779. defines: defines,
  33780. maxSimultaneousLights: this._maxSimultaneousLights
  33781. });
  33782. if (this.customShaderNameResolve) {
  33783. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  33784. }
  33785. var join = defines.toString();
  33786. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  33787. attributes: attribs,
  33788. uniformsNames: uniforms,
  33789. uniformBuffersNames: uniformBuffers,
  33790. samplers: samplers,
  33791. defines: join,
  33792. fallbacks: fallbacks,
  33793. onCompiled: this.onCompiled,
  33794. onError: this.onError,
  33795. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  33796. }, engine), defines);
  33797. this.buildUniformLayout();
  33798. }
  33799. if (!subMesh.effect || !subMesh.effect.isReady()) {
  33800. return false;
  33801. }
  33802. defines._renderId = scene.getRenderId();
  33803. this._wasPreviouslyReady = true;
  33804. return true;
  33805. };
  33806. StandardMaterial.prototype.buildUniformLayout = function () {
  33807. // Order is important !
  33808. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  33809. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  33810. this._uniformBuffer.addUniform("opacityParts", 4);
  33811. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  33812. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  33813. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  33814. this._uniformBuffer.addUniform("refractionRightColor", 4);
  33815. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  33816. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  33817. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  33818. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  33819. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  33820. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  33821. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  33822. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  33823. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  33824. this._uniformBuffer.addUniform("vBumpInfos", 3);
  33825. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  33826. this._uniformBuffer.addUniform("ambientMatrix", 16);
  33827. this._uniformBuffer.addUniform("opacityMatrix", 16);
  33828. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  33829. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  33830. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  33831. this._uniformBuffer.addUniform("specularMatrix", 16);
  33832. this._uniformBuffer.addUniform("bumpMatrix", 16);
  33833. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  33834. this._uniformBuffer.addUniform("refractionMatrix", 16);
  33835. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  33836. this._uniformBuffer.addUniform("vSpecularColor", 4);
  33837. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  33838. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  33839. this._uniformBuffer.addUniform("pointSize", 1);
  33840. this._uniformBuffer.create();
  33841. };
  33842. StandardMaterial.prototype.unbind = function () {
  33843. if (this._activeEffect) {
  33844. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  33845. this._activeEffect.setTexture("reflection2DSampler", null);
  33846. }
  33847. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  33848. this._activeEffect.setTexture("refraction2DSampler", null);
  33849. }
  33850. }
  33851. _super.prototype.unbind.call(this);
  33852. };
  33853. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  33854. var scene = this.getScene();
  33855. var defines = subMesh._materialDefines;
  33856. if (!defines) {
  33857. return;
  33858. }
  33859. var effect = subMesh.effect;
  33860. if (!effect) {
  33861. return;
  33862. }
  33863. this._activeEffect = effect;
  33864. // Matrices
  33865. this.bindOnlyWorldMatrix(world);
  33866. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  33867. // Bones
  33868. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  33869. if (mustRebind) {
  33870. this._uniformBuffer.bindToEffect(effect, "Material");
  33871. this.bindViewProjection(effect);
  33872. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  33873. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  33874. // Fresnel
  33875. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  33876. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  33877. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  33878. }
  33879. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  33880. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  33881. }
  33882. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  33883. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  33884. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  33885. }
  33886. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  33887. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  33888. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  33889. }
  33890. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  33891. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  33892. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  33893. }
  33894. }
  33895. // Textures
  33896. if (scene.texturesEnabled) {
  33897. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33898. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  33899. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  33900. }
  33901. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33902. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  33903. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  33904. }
  33905. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33906. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  33907. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  33908. }
  33909. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33910. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  33911. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  33912. }
  33913. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33914. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  33915. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  33916. }
  33917. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33918. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  33919. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  33920. }
  33921. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33922. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  33923. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  33924. }
  33925. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  33926. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  33927. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  33928. if (scene._mirroredCameraPosition) {
  33929. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  33930. }
  33931. else {
  33932. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  33933. }
  33934. }
  33935. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33936. var depth = 1.0;
  33937. if (!this._refractionTexture.isCube) {
  33938. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  33939. if (this._refractionTexture.depth) {
  33940. depth = this._refractionTexture.depth;
  33941. }
  33942. }
  33943. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  33944. }
  33945. }
  33946. // Point size
  33947. if (this.pointsCloud) {
  33948. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  33949. }
  33950. if (defines.SPECULARTERM) {
  33951. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  33952. }
  33953. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  33954. // Diffuse
  33955. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  33956. }
  33957. // Textures
  33958. if (scene.texturesEnabled) {
  33959. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33960. effect.setTexture("diffuseSampler", this._diffuseTexture);
  33961. }
  33962. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33963. effect.setTexture("ambientSampler", this._ambientTexture);
  33964. }
  33965. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33966. effect.setTexture("opacitySampler", this._opacityTexture);
  33967. }
  33968. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33969. if (this._reflectionTexture.isCube) {
  33970. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  33971. }
  33972. else {
  33973. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  33974. }
  33975. }
  33976. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33977. effect.setTexture("emissiveSampler", this._emissiveTexture);
  33978. }
  33979. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33980. effect.setTexture("lightmapSampler", this._lightmapTexture);
  33981. }
  33982. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33983. effect.setTexture("specularSampler", this._specularTexture);
  33984. }
  33985. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  33986. effect.setTexture("bumpSampler", this._bumpTexture);
  33987. }
  33988. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33989. var depth = 1.0;
  33990. if (this._refractionTexture.isCube) {
  33991. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  33992. }
  33993. else {
  33994. effect.setTexture("refraction2DSampler", this._refractionTexture);
  33995. }
  33996. }
  33997. }
  33998. // Clip plane
  33999. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34000. // Colors
  34001. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34002. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34003. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34004. }
  34005. if (mustRebind || !this.isFrozen) {
  34006. // Lights
  34007. if (scene.lightsEnabled && !this._disableLighting) {
  34008. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34009. }
  34010. // View
  34011. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34012. this.bindView(effect);
  34013. }
  34014. // Fog
  34015. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34016. // Morph targets
  34017. if (defines.NUM_MORPH_INFLUENCERS) {
  34018. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34019. }
  34020. // Log. depth
  34021. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34022. // image processing
  34023. this._imageProcessingConfiguration.bind(this._activeEffect);
  34024. }
  34025. this._uniformBuffer.update();
  34026. this._afterBind(mesh, this._activeEffect);
  34027. };
  34028. StandardMaterial.prototype.getAnimatables = function () {
  34029. var results = [];
  34030. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34031. results.push(this._diffuseTexture);
  34032. }
  34033. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34034. results.push(this._ambientTexture);
  34035. }
  34036. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34037. results.push(this._opacityTexture);
  34038. }
  34039. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34040. results.push(this._reflectionTexture);
  34041. }
  34042. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34043. results.push(this._emissiveTexture);
  34044. }
  34045. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34046. results.push(this._specularTexture);
  34047. }
  34048. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34049. results.push(this._bumpTexture);
  34050. }
  34051. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34052. results.push(this._lightmapTexture);
  34053. }
  34054. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34055. results.push(this._refractionTexture);
  34056. }
  34057. return results;
  34058. };
  34059. StandardMaterial.prototype.getActiveTextures = function () {
  34060. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34061. if (this._diffuseTexture) {
  34062. activeTextures.push(this._diffuseTexture);
  34063. }
  34064. if (this._ambientTexture) {
  34065. activeTextures.push(this._ambientTexture);
  34066. }
  34067. if (this._opacityTexture) {
  34068. activeTextures.push(this._opacityTexture);
  34069. }
  34070. if (this._reflectionTexture) {
  34071. activeTextures.push(this._reflectionTexture);
  34072. }
  34073. if (this._emissiveTexture) {
  34074. activeTextures.push(this._emissiveTexture);
  34075. }
  34076. if (this._specularTexture) {
  34077. activeTextures.push(this._specularTexture);
  34078. }
  34079. if (this._bumpTexture) {
  34080. activeTextures.push(this._bumpTexture);
  34081. }
  34082. if (this._lightmapTexture) {
  34083. activeTextures.push(this._lightmapTexture);
  34084. }
  34085. if (this._refractionTexture) {
  34086. activeTextures.push(this._refractionTexture);
  34087. }
  34088. return activeTextures;
  34089. };
  34090. StandardMaterial.prototype.hasTexture = function (texture) {
  34091. if (_super.prototype.hasTexture.call(this, texture)) {
  34092. return true;
  34093. }
  34094. if (this._diffuseTexture === texture) {
  34095. return true;
  34096. }
  34097. if (this._ambientTexture === texture) {
  34098. return true;
  34099. }
  34100. if (this._opacityTexture === texture) {
  34101. return true;
  34102. }
  34103. if (this._reflectionTexture === texture) {
  34104. return true;
  34105. }
  34106. if (this._emissiveTexture === texture) {
  34107. return true;
  34108. }
  34109. if (this._specularTexture === texture) {
  34110. return true;
  34111. }
  34112. if (this._bumpTexture === texture) {
  34113. return true;
  34114. }
  34115. if (this._lightmapTexture === texture) {
  34116. return true;
  34117. }
  34118. if (this._refractionTexture === texture) {
  34119. return true;
  34120. }
  34121. return false;
  34122. };
  34123. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34124. if (forceDisposeTextures) {
  34125. if (this._diffuseTexture) {
  34126. this._diffuseTexture.dispose();
  34127. }
  34128. if (this._ambientTexture) {
  34129. this._ambientTexture.dispose();
  34130. }
  34131. if (this._opacityTexture) {
  34132. this._opacityTexture.dispose();
  34133. }
  34134. if (this._reflectionTexture) {
  34135. this._reflectionTexture.dispose();
  34136. }
  34137. if (this._emissiveTexture) {
  34138. this._emissiveTexture.dispose();
  34139. }
  34140. if (this._specularTexture) {
  34141. this._specularTexture.dispose();
  34142. }
  34143. if (this._bumpTexture) {
  34144. this._bumpTexture.dispose();
  34145. }
  34146. if (this._lightmapTexture) {
  34147. this._lightmapTexture.dispose();
  34148. }
  34149. if (this._refractionTexture) {
  34150. this._refractionTexture.dispose();
  34151. }
  34152. }
  34153. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34154. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34155. }
  34156. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34157. };
  34158. StandardMaterial.prototype.clone = function (name) {
  34159. var _this = this;
  34160. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34161. result.name = name;
  34162. result.id = name;
  34163. return result;
  34164. };
  34165. StandardMaterial.prototype.serialize = function () {
  34166. return BABYLON.SerializationHelper.Serialize(this);
  34167. };
  34168. // Statics
  34169. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34170. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34171. };
  34172. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34173. get: function () {
  34174. return StandardMaterial._DiffuseTextureEnabled;
  34175. },
  34176. set: function (value) {
  34177. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34178. return;
  34179. }
  34180. StandardMaterial._DiffuseTextureEnabled = value;
  34181. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34182. },
  34183. enumerable: true,
  34184. configurable: true
  34185. });
  34186. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34187. get: function () {
  34188. return StandardMaterial._AmbientTextureEnabled;
  34189. },
  34190. set: function (value) {
  34191. if (StandardMaterial._AmbientTextureEnabled === value) {
  34192. return;
  34193. }
  34194. StandardMaterial._AmbientTextureEnabled = value;
  34195. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34196. },
  34197. enumerable: true,
  34198. configurable: true
  34199. });
  34200. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34201. get: function () {
  34202. return StandardMaterial._OpacityTextureEnabled;
  34203. },
  34204. set: function (value) {
  34205. if (StandardMaterial._OpacityTextureEnabled === value) {
  34206. return;
  34207. }
  34208. StandardMaterial._OpacityTextureEnabled = value;
  34209. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34210. },
  34211. enumerable: true,
  34212. configurable: true
  34213. });
  34214. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34215. get: function () {
  34216. return StandardMaterial._ReflectionTextureEnabled;
  34217. },
  34218. set: function (value) {
  34219. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34220. return;
  34221. }
  34222. StandardMaterial._ReflectionTextureEnabled = value;
  34223. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34224. },
  34225. enumerable: true,
  34226. configurable: true
  34227. });
  34228. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34229. get: function () {
  34230. return StandardMaterial._EmissiveTextureEnabled;
  34231. },
  34232. set: function (value) {
  34233. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34234. return;
  34235. }
  34236. StandardMaterial._EmissiveTextureEnabled = value;
  34237. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34238. },
  34239. enumerable: true,
  34240. configurable: true
  34241. });
  34242. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34243. get: function () {
  34244. return StandardMaterial._SpecularTextureEnabled;
  34245. },
  34246. set: function (value) {
  34247. if (StandardMaterial._SpecularTextureEnabled === value) {
  34248. return;
  34249. }
  34250. StandardMaterial._SpecularTextureEnabled = value;
  34251. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34252. },
  34253. enumerable: true,
  34254. configurable: true
  34255. });
  34256. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34257. get: function () {
  34258. return StandardMaterial._BumpTextureEnabled;
  34259. },
  34260. set: function (value) {
  34261. if (StandardMaterial._BumpTextureEnabled === value) {
  34262. return;
  34263. }
  34264. StandardMaterial._BumpTextureEnabled = value;
  34265. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34266. },
  34267. enumerable: true,
  34268. configurable: true
  34269. });
  34270. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34271. get: function () {
  34272. return StandardMaterial._LightmapTextureEnabled;
  34273. },
  34274. set: function (value) {
  34275. if (StandardMaterial._LightmapTextureEnabled === value) {
  34276. return;
  34277. }
  34278. StandardMaterial._LightmapTextureEnabled = value;
  34279. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34280. },
  34281. enumerable: true,
  34282. configurable: true
  34283. });
  34284. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34285. get: function () {
  34286. return StandardMaterial._RefractionTextureEnabled;
  34287. },
  34288. set: function (value) {
  34289. if (StandardMaterial._RefractionTextureEnabled === value) {
  34290. return;
  34291. }
  34292. StandardMaterial._RefractionTextureEnabled = value;
  34293. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34294. },
  34295. enumerable: true,
  34296. configurable: true
  34297. });
  34298. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34299. get: function () {
  34300. return StandardMaterial._ColorGradingTextureEnabled;
  34301. },
  34302. set: function (value) {
  34303. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34304. return;
  34305. }
  34306. StandardMaterial._ColorGradingTextureEnabled = value;
  34307. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34308. },
  34309. enumerable: true,
  34310. configurable: true
  34311. });
  34312. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34313. get: function () {
  34314. return StandardMaterial._FresnelEnabled;
  34315. },
  34316. set: function (value) {
  34317. if (StandardMaterial._FresnelEnabled === value) {
  34318. return;
  34319. }
  34320. StandardMaterial._FresnelEnabled = value;
  34321. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34322. },
  34323. enumerable: true,
  34324. configurable: true
  34325. });
  34326. // Flags used to enable or disable a type of texture for all Standard Materials
  34327. StandardMaterial._DiffuseTextureEnabled = true;
  34328. StandardMaterial._AmbientTextureEnabled = true;
  34329. StandardMaterial._OpacityTextureEnabled = true;
  34330. StandardMaterial._ReflectionTextureEnabled = true;
  34331. StandardMaterial._EmissiveTextureEnabled = true;
  34332. StandardMaterial._SpecularTextureEnabled = true;
  34333. StandardMaterial._BumpTextureEnabled = true;
  34334. StandardMaterial._LightmapTextureEnabled = true;
  34335. StandardMaterial._RefractionTextureEnabled = true;
  34336. StandardMaterial._ColorGradingTextureEnabled = true;
  34337. StandardMaterial._FresnelEnabled = true;
  34338. __decorate([
  34339. BABYLON.serializeAsTexture("diffuseTexture")
  34340. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34341. __decorate([
  34342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34343. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34344. __decorate([
  34345. BABYLON.serializeAsTexture("ambientTexture")
  34346. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  34347. __decorate([
  34348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34349. ], StandardMaterial.prototype, "ambientTexture", void 0);
  34350. __decorate([
  34351. BABYLON.serializeAsTexture("opacityTexture")
  34352. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  34353. __decorate([
  34354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34355. ], StandardMaterial.prototype, "opacityTexture", void 0);
  34356. __decorate([
  34357. BABYLON.serializeAsTexture("reflectionTexture")
  34358. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  34359. __decorate([
  34360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34361. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  34362. __decorate([
  34363. BABYLON.serializeAsTexture("emissiveTexture")
  34364. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  34365. __decorate([
  34366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34367. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  34368. __decorate([
  34369. BABYLON.serializeAsTexture("specularTexture")
  34370. ], StandardMaterial.prototype, "_specularTexture", void 0);
  34371. __decorate([
  34372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34373. ], StandardMaterial.prototype, "specularTexture", void 0);
  34374. __decorate([
  34375. BABYLON.serializeAsTexture("bumpTexture")
  34376. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  34377. __decorate([
  34378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34379. ], StandardMaterial.prototype, "bumpTexture", void 0);
  34380. __decorate([
  34381. BABYLON.serializeAsTexture("lightmapTexture")
  34382. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  34383. __decorate([
  34384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34385. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  34386. __decorate([
  34387. BABYLON.serializeAsTexture("refractionTexture")
  34388. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  34389. __decorate([
  34390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34391. ], StandardMaterial.prototype, "refractionTexture", void 0);
  34392. __decorate([
  34393. BABYLON.serializeAsColor3("ambient")
  34394. ], StandardMaterial.prototype, "ambientColor", void 0);
  34395. __decorate([
  34396. BABYLON.serializeAsColor3("diffuse")
  34397. ], StandardMaterial.prototype, "diffuseColor", void 0);
  34398. __decorate([
  34399. BABYLON.serializeAsColor3("specular")
  34400. ], StandardMaterial.prototype, "specularColor", void 0);
  34401. __decorate([
  34402. BABYLON.serializeAsColor3("emissive")
  34403. ], StandardMaterial.prototype, "emissiveColor", void 0);
  34404. __decorate([
  34405. BABYLON.serialize()
  34406. ], StandardMaterial.prototype, "specularPower", void 0);
  34407. __decorate([
  34408. BABYLON.serialize("useAlphaFromDiffuseTexture")
  34409. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  34410. __decorate([
  34411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34412. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  34413. __decorate([
  34414. BABYLON.serialize("useEmissiveAsIllumination")
  34415. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  34416. __decorate([
  34417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34418. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  34419. __decorate([
  34420. BABYLON.serialize("linkEmissiveWithDiffuse")
  34421. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  34422. __decorate([
  34423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34424. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  34425. __decorate([
  34426. BABYLON.serialize("useSpecularOverAlpha")
  34427. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  34428. __decorate([
  34429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34430. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  34431. __decorate([
  34432. BABYLON.serialize("useReflectionOverAlpha")
  34433. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  34434. __decorate([
  34435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34436. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  34437. __decorate([
  34438. BABYLON.serialize("disableLighting")
  34439. ], StandardMaterial.prototype, "_disableLighting", void 0);
  34440. __decorate([
  34441. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34442. ], StandardMaterial.prototype, "disableLighting", void 0);
  34443. __decorate([
  34444. BABYLON.serialize("useParallax")
  34445. ], StandardMaterial.prototype, "_useParallax", void 0);
  34446. __decorate([
  34447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34448. ], StandardMaterial.prototype, "useParallax", void 0);
  34449. __decorate([
  34450. BABYLON.serialize("useParallaxOcclusion")
  34451. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  34452. __decorate([
  34453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34454. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  34455. __decorate([
  34456. BABYLON.serialize()
  34457. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  34458. __decorate([
  34459. BABYLON.serialize("roughness")
  34460. ], StandardMaterial.prototype, "_roughness", void 0);
  34461. __decorate([
  34462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34463. ], StandardMaterial.prototype, "roughness", void 0);
  34464. __decorate([
  34465. BABYLON.serialize()
  34466. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  34467. __decorate([
  34468. BABYLON.serialize()
  34469. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  34470. __decorate([
  34471. BABYLON.serialize("useLightmapAsShadowmap")
  34472. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  34473. __decorate([
  34474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34475. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34476. __decorate([
  34477. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  34478. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  34479. __decorate([
  34480. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34481. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  34482. __decorate([
  34483. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  34484. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  34485. __decorate([
  34486. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34487. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  34488. __decorate([
  34489. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  34490. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  34491. __decorate([
  34492. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34493. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  34494. __decorate([
  34495. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  34496. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  34497. __decorate([
  34498. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34499. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  34500. __decorate([
  34501. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  34502. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  34503. __decorate([
  34504. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34505. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  34506. __decorate([
  34507. BABYLON.serialize("useReflectionFresnelFromSpecular")
  34508. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  34509. __decorate([
  34510. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34511. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  34512. __decorate([
  34513. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  34514. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  34515. __decorate([
  34516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34517. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  34518. __decorate([
  34519. BABYLON.serialize("maxSimultaneousLights")
  34520. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  34521. __decorate([
  34522. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34523. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  34524. __decorate([
  34525. BABYLON.serialize("invertNormalMapX")
  34526. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  34527. __decorate([
  34528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34529. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  34530. __decorate([
  34531. BABYLON.serialize("invertNormalMapY")
  34532. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  34533. __decorate([
  34534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34535. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  34536. __decorate([
  34537. BABYLON.serialize("twoSidedLighting")
  34538. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  34539. __decorate([
  34540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34541. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  34542. __decorate([
  34543. BABYLON.serialize()
  34544. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  34545. return StandardMaterial;
  34546. }(BABYLON.PushMaterial));
  34547. BABYLON.StandardMaterial = StandardMaterial;
  34548. })(BABYLON || (BABYLON = {}));
  34549. //# sourceMappingURL=babylon.standardMaterial.js.map
  34550. var BABYLON;
  34551. (function (BABYLON) {
  34552. var PBRMaterialDefines = /** @class */ (function (_super) {
  34553. __extends(PBRMaterialDefines, _super);
  34554. function PBRMaterialDefines() {
  34555. var _this = _super.call(this) || this;
  34556. _this.PBR = true;
  34557. _this.MAINUV1 = false;
  34558. _this.MAINUV2 = false;
  34559. _this.UV1 = false;
  34560. _this.UV2 = false;
  34561. _this.ALBEDO = false;
  34562. _this.ALBEDODIRECTUV = 0;
  34563. _this.VERTEXCOLOR = false;
  34564. _this.AMBIENT = false;
  34565. _this.AMBIENTDIRECTUV = 0;
  34566. _this.AMBIENTINGRAYSCALE = false;
  34567. _this.OPACITY = false;
  34568. _this.VERTEXALPHA = false;
  34569. _this.OPACITYDIRECTUV = 0;
  34570. _this.OPACITYRGB = false;
  34571. _this.ALPHATEST = false;
  34572. _this.DEPTHPREPASS = false;
  34573. _this.ALPHABLEND = false;
  34574. _this.ALPHAFROMALBEDO = false;
  34575. _this.ALPHATESTVALUE = 0.5;
  34576. _this.SPECULAROVERALPHA = false;
  34577. _this.RADIANCEOVERALPHA = false;
  34578. _this.ALPHAFRESNEL = false;
  34579. _this.PREMULTIPLYALPHA = false;
  34580. _this.EMISSIVE = false;
  34581. _this.EMISSIVEDIRECTUV = 0;
  34582. _this.REFLECTIVITY = false;
  34583. _this.REFLECTIVITYDIRECTUV = 0;
  34584. _this.SPECULARTERM = false;
  34585. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34586. _this.MICROSURFACEAUTOMATIC = false;
  34587. _this.LODBASEDMICROSFURACE = false;
  34588. _this.MICROSURFACEMAP = false;
  34589. _this.MICROSURFACEMAPDIRECTUV = 0;
  34590. _this.METALLICWORKFLOW = false;
  34591. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34592. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34593. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34594. _this.AOSTOREINMETALMAPRED = false;
  34595. _this.ENVIRONMENTBRDF = false;
  34596. _this.NORMAL = false;
  34597. _this.TANGENT = false;
  34598. _this.BUMP = false;
  34599. _this.BUMPDIRECTUV = 0;
  34600. _this.PARALLAX = false;
  34601. _this.PARALLAXOCCLUSION = false;
  34602. _this.NORMALXYSCALE = true;
  34603. _this.LIGHTMAP = false;
  34604. _this.LIGHTMAPDIRECTUV = 0;
  34605. _this.USELIGHTMAPASSHADOWMAP = false;
  34606. _this.REFLECTION = false;
  34607. _this.REFLECTIONMAP_3D = false;
  34608. _this.REFLECTIONMAP_SPHERICAL = false;
  34609. _this.REFLECTIONMAP_PLANAR = false;
  34610. _this.REFLECTIONMAP_CUBIC = false;
  34611. _this.REFLECTIONMAP_PROJECTION = false;
  34612. _this.REFLECTIONMAP_SKYBOX = false;
  34613. _this.REFLECTIONMAP_EXPLICIT = false;
  34614. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34615. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34616. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34617. _this.INVERTCUBICMAP = false;
  34618. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34619. _this.USESPHERICALINFRAGMENT = false;
  34620. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34621. _this.LODINREFLECTIONALPHA = false;
  34622. _this.GAMMAREFLECTION = false;
  34623. _this.REFRACTION = false;
  34624. _this.REFRACTIONMAP_3D = false;
  34625. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34626. _this.LODINREFRACTIONALPHA = false;
  34627. _this.GAMMAREFRACTION = false;
  34628. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34629. _this.INSTANCES = false;
  34630. _this.NUM_BONE_INFLUENCERS = 0;
  34631. _this.BonesPerMesh = 0;
  34632. _this.NONUNIFORMSCALING = false;
  34633. _this.MORPHTARGETS = false;
  34634. _this.MORPHTARGETS_NORMAL = false;
  34635. _this.MORPHTARGETS_TANGENT = false;
  34636. _this.NUM_MORPH_INFLUENCERS = 0;
  34637. _this.IMAGEPROCESSING = false;
  34638. _this.VIGNETTE = false;
  34639. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34640. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34641. _this.TONEMAPPING = false;
  34642. _this.CONTRAST = false;
  34643. _this.COLORCURVES = false;
  34644. _this.COLORGRADING = false;
  34645. _this.COLORGRADING3D = false;
  34646. _this.SAMPLER3DGREENDEPTH = false;
  34647. _this.SAMPLER3DBGRMAP = false;
  34648. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34649. _this.EXPOSURE = false;
  34650. _this.USEPHYSICALLIGHTFALLOFF = false;
  34651. _this.TWOSIDEDLIGHTING = false;
  34652. _this.SHADOWFLOAT = false;
  34653. _this.CLIPPLANE = false;
  34654. _this.POINTSIZE = false;
  34655. _this.FOG = false;
  34656. _this.LOGARITHMICDEPTH = false;
  34657. _this.FORCENORMALFORWARD = false;
  34658. _this.rebuild();
  34659. return _this;
  34660. }
  34661. PBRMaterialDefines.prototype.reset = function () {
  34662. _super.prototype.reset.call(this);
  34663. this.ALPHATESTVALUE = 0.5;
  34664. this.PBR = true;
  34665. };
  34666. return PBRMaterialDefines;
  34667. }(BABYLON.MaterialDefines));
  34668. /**
  34669. * The Physically based material base class of BJS.
  34670. *
  34671. * This offers the main features of a standard PBR material.
  34672. * For more information, please refer to the documentation :
  34673. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34674. */
  34675. var PBRBaseMaterial = /** @class */ (function (_super) {
  34676. __extends(PBRBaseMaterial, _super);
  34677. /**
  34678. * Instantiates a new PBRMaterial instance.
  34679. *
  34680. * @param name The material name
  34681. * @param scene The scene the material will be use in.
  34682. */
  34683. function PBRBaseMaterial(name, scene) {
  34684. var _this = _super.call(this, name, scene) || this;
  34685. /**
  34686. * Intensity of the direct lights e.g. the four lights available in your scene.
  34687. * This impacts both the direct diffuse and specular highlights.
  34688. */
  34689. _this._directIntensity = 1.0;
  34690. /**
  34691. * Intensity of the emissive part of the material.
  34692. * This helps controlling the emissive effect without modifying the emissive color.
  34693. */
  34694. _this._emissiveIntensity = 1.0;
  34695. /**
  34696. * Intensity of the environment e.g. how much the environment will light the object
  34697. * either through harmonics for rough material or through the refelction for shiny ones.
  34698. */
  34699. _this._environmentIntensity = 1.0;
  34700. /**
  34701. * This is a special control allowing the reduction of the specular highlights coming from the
  34702. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34703. */
  34704. _this._specularIntensity = 1.0;
  34705. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34706. /**
  34707. * Debug Control allowing disabling the bump map on this material.
  34708. */
  34709. _this._disableBumpMap = false;
  34710. /**
  34711. * AKA Occlusion Texture Intensity in other nomenclature.
  34712. */
  34713. _this._ambientTextureStrength = 1.0;
  34714. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34715. /**
  34716. * AKA Diffuse Color in other nomenclature.
  34717. */
  34718. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34719. /**
  34720. * AKA Specular Color in other nomenclature.
  34721. */
  34722. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34723. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  34724. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34725. /**
  34726. * AKA Glossiness in other nomenclature.
  34727. */
  34728. _this._microSurface = 0.9;
  34729. /**
  34730. * source material index of refraction (IOR)' / 'destination material IOR.
  34731. */
  34732. _this._indexOfRefraction = 0.66;
  34733. /**
  34734. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34735. */
  34736. _this._invertRefractionY = false;
  34737. /**
  34738. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34739. * Materials half opaque for instance using refraction could benefit from this control.
  34740. */
  34741. _this._linkRefractionWithTransparency = false;
  34742. _this._useLightmapAsShadowmap = false;
  34743. /**
  34744. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34745. */
  34746. _this._useAlphaFromAlbedoTexture = false;
  34747. /**
  34748. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34749. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34750. */
  34751. _this._useSpecularOverAlpha = true;
  34752. /**
  34753. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34754. */
  34755. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34756. /**
  34757. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34758. */
  34759. _this._useRoughnessFromMetallicTextureAlpha = true;
  34760. /**
  34761. * Specifies if the metallic texture contains the roughness information in its green channel.
  34762. */
  34763. _this._useRoughnessFromMetallicTextureGreen = false;
  34764. /**
  34765. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34766. */
  34767. _this._useMetallnessFromMetallicTextureBlue = false;
  34768. /**
  34769. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34770. */
  34771. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34772. /**
  34773. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34774. */
  34775. _this._useAmbientInGrayScale = false;
  34776. /**
  34777. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34778. * The material will try to infer what glossiness each pixel should be.
  34779. */
  34780. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34781. /**
  34782. * BJS is using an harcoded light falloff based on a manually sets up range.
  34783. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34784. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34785. */
  34786. _this._usePhysicalLightFalloff = true;
  34787. /**
  34788. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34789. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34790. */
  34791. _this._useRadianceOverAlpha = true;
  34792. /**
  34793. * Allows using the bump map in parallax mode.
  34794. */
  34795. _this._useParallax = false;
  34796. /**
  34797. * Allows using the bump map in parallax occlusion mode.
  34798. */
  34799. _this._useParallaxOcclusion = false;
  34800. /**
  34801. * Controls the scale bias of the parallax mode.
  34802. */
  34803. _this._parallaxScaleBias = 0.05;
  34804. /**
  34805. * If sets to true, disables all the lights affecting the material.
  34806. */
  34807. _this._disableLighting = false;
  34808. /**
  34809. * Number of Simultaneous lights allowed on the material.
  34810. */
  34811. _this._maxSimultaneousLights = 4;
  34812. /**
  34813. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  34814. */
  34815. _this._invertNormalMapX = false;
  34816. /**
  34817. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  34818. */
  34819. _this._invertNormalMapY = false;
  34820. /**
  34821. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34822. */
  34823. _this._twoSidedLighting = false;
  34824. /**
  34825. * Defines the alpha limits in alpha test mode.
  34826. */
  34827. _this._alphaCutOff = 0.4;
  34828. /**
  34829. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34830. */
  34831. _this._forceAlphaTest = false;
  34832. /**
  34833. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34834. * And/Or occlude the blended part.
  34835. */
  34836. _this._useAlphaFresnel = false;
  34837. /**
  34838. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  34839. * from cos thetav and roughness:
  34840. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  34841. */
  34842. _this._environmentBRDFTexture = null;
  34843. /**
  34844. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  34845. */
  34846. _this._forceIrradianceInFragment = false;
  34847. /**
  34848. * Force normal to face away from face.
  34849. * (Temporary internal fix to remove before 3.1)
  34850. */
  34851. _this._forceNormalForward = false;
  34852. _this._renderTargets = new BABYLON.SmartArray(16);
  34853. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34854. // Setup the default processing configuration to the scene.
  34855. _this._attachImageProcessingConfiguration(null);
  34856. _this.getRenderTargetTextures = function () {
  34857. _this._renderTargets.reset();
  34858. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34859. _this._renderTargets.push(_this._reflectionTexture);
  34860. }
  34861. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34862. _this._renderTargets.push(_this._refractionTexture);
  34863. }
  34864. return _this._renderTargets;
  34865. };
  34866. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  34867. return _this;
  34868. }
  34869. /**
  34870. * Attaches a new image processing configuration to the PBR Material.
  34871. * @param configuration
  34872. */
  34873. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34874. var _this = this;
  34875. if (configuration === this._imageProcessingConfiguration) {
  34876. return;
  34877. }
  34878. // Detaches observer.
  34879. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34880. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34881. }
  34882. // Pick the scene configuration if needed.
  34883. if (!configuration) {
  34884. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34885. }
  34886. else {
  34887. this._imageProcessingConfiguration = configuration;
  34888. }
  34889. // Attaches observer.
  34890. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34891. _this._markAllSubMeshesAsImageProcessingDirty();
  34892. });
  34893. };
  34894. PBRBaseMaterial.prototype.getClassName = function () {
  34895. return "PBRBaseMaterial";
  34896. };
  34897. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  34898. get: function () {
  34899. return this._useLogarithmicDepth;
  34900. },
  34901. set: function (value) {
  34902. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34903. },
  34904. enumerable: true,
  34905. configurable: true
  34906. });
  34907. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  34908. if (this._linkRefractionWithTransparency) {
  34909. return false;
  34910. }
  34911. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  34912. };
  34913. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  34914. if (this._forceAlphaTest) {
  34915. return true;
  34916. }
  34917. if (this._linkRefractionWithTransparency) {
  34918. return false;
  34919. }
  34920. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  34921. };
  34922. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34923. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  34924. };
  34925. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  34926. return this._albedoTexture;
  34927. };
  34928. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34929. var _this = this;
  34930. if (subMesh.effect && this.isFrozen) {
  34931. if (this._wasPreviouslyReady) {
  34932. return true;
  34933. }
  34934. }
  34935. if (!subMesh._materialDefines) {
  34936. subMesh._materialDefines = new PBRMaterialDefines();
  34937. }
  34938. var scene = this.getScene();
  34939. var defines = subMesh._materialDefines;
  34940. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34941. if (defines._renderId === scene.getRenderId()) {
  34942. return true;
  34943. }
  34944. }
  34945. var engine = scene.getEngine();
  34946. // Lights
  34947. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34948. defines._needNormals = true;
  34949. // Textures
  34950. if (defines._areTexturesDirty) {
  34951. defines._needUVs = false;
  34952. if (scene.texturesEnabled) {
  34953. if (scene.getEngine().getCaps().textureLOD) {
  34954. defines.LODBASEDMICROSFURACE = true;
  34955. }
  34956. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34957. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  34958. return false;
  34959. }
  34960. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  34961. }
  34962. else {
  34963. defines.ALBEDO = false;
  34964. }
  34965. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34966. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34967. return false;
  34968. }
  34969. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34970. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  34971. }
  34972. else {
  34973. defines.AMBIENT = false;
  34974. }
  34975. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34976. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34977. return false;
  34978. }
  34979. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34980. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34981. }
  34982. else {
  34983. defines.OPACITY = false;
  34984. }
  34985. var reflectionTexture = this._getReflectionTexture();
  34986. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34987. if (!reflectionTexture.isReadyOrNotBlocking()) {
  34988. return false;
  34989. }
  34990. defines.REFLECTION = true;
  34991. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  34992. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  34993. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  34994. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  34995. defines.INVERTCUBICMAP = true;
  34996. }
  34997. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  34998. switch (reflectionTexture.coordinatesMode) {
  34999. case BABYLON.Texture.CUBIC_MODE:
  35000. case BABYLON.Texture.INVCUBIC_MODE:
  35001. defines.REFLECTIONMAP_CUBIC = true;
  35002. break;
  35003. case BABYLON.Texture.EXPLICIT_MODE:
  35004. defines.REFLECTIONMAP_EXPLICIT = true;
  35005. break;
  35006. case BABYLON.Texture.PLANAR_MODE:
  35007. defines.REFLECTIONMAP_PLANAR = true;
  35008. break;
  35009. case BABYLON.Texture.PROJECTION_MODE:
  35010. defines.REFLECTIONMAP_PROJECTION = true;
  35011. break;
  35012. case BABYLON.Texture.SKYBOX_MODE:
  35013. defines.REFLECTIONMAP_SKYBOX = true;
  35014. break;
  35015. case BABYLON.Texture.SPHERICAL_MODE:
  35016. defines.REFLECTIONMAP_SPHERICAL = true;
  35017. break;
  35018. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35019. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35020. break;
  35021. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35022. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35023. break;
  35024. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35025. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35026. break;
  35027. }
  35028. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35029. if (reflectionTexture.sphericalPolynomial) {
  35030. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35031. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35032. defines.USESPHERICALINFRAGMENT = true;
  35033. }
  35034. }
  35035. }
  35036. }
  35037. else {
  35038. defines.REFLECTION = false;
  35039. defines.REFLECTIONMAP_3D = false;
  35040. defines.REFLECTIONMAP_SPHERICAL = false;
  35041. defines.REFLECTIONMAP_PLANAR = false;
  35042. defines.REFLECTIONMAP_CUBIC = false;
  35043. defines.REFLECTIONMAP_PROJECTION = false;
  35044. defines.REFLECTIONMAP_SKYBOX = false;
  35045. defines.REFLECTIONMAP_EXPLICIT = false;
  35046. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35047. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35048. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35049. defines.INVERTCUBICMAP = false;
  35050. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35051. defines.USESPHERICALINFRAGMENT = false;
  35052. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35053. defines.LODINREFLECTIONALPHA = false;
  35054. defines.GAMMAREFLECTION = false;
  35055. }
  35056. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35057. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35058. return false;
  35059. }
  35060. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35061. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35062. }
  35063. else {
  35064. defines.LIGHTMAP = false;
  35065. }
  35066. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35067. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35068. return false;
  35069. }
  35070. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35071. }
  35072. else {
  35073. defines.EMISSIVE = false;
  35074. }
  35075. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35076. if (this._metallicTexture) {
  35077. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35078. return false;
  35079. }
  35080. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35081. defines.METALLICWORKFLOW = true;
  35082. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35083. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35084. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35085. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35086. }
  35087. else if (this._reflectivityTexture) {
  35088. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35089. return false;
  35090. }
  35091. defines.METALLICWORKFLOW = false;
  35092. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35093. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35094. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35095. }
  35096. else {
  35097. defines.METALLICWORKFLOW = false;
  35098. defines.REFLECTIVITY = false;
  35099. }
  35100. if (this._microSurfaceTexture) {
  35101. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35102. return false;
  35103. }
  35104. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35105. }
  35106. else {
  35107. defines.MICROSURFACEMAP = false;
  35108. }
  35109. }
  35110. else {
  35111. defines.REFLECTIVITY = false;
  35112. defines.MICROSURFACEMAP = false;
  35113. }
  35114. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35115. // Bump texure can not be none blocking.
  35116. if (!this._bumpTexture.isReady()) {
  35117. return false;
  35118. }
  35119. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35120. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35121. defines.PARALLAX = true;
  35122. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35123. }
  35124. else {
  35125. defines.PARALLAX = false;
  35126. }
  35127. }
  35128. else {
  35129. defines.BUMP = false;
  35130. }
  35131. var refractionTexture = this._getRefractionTexture();
  35132. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35133. if (!refractionTexture.isReadyOrNotBlocking()) {
  35134. return false;
  35135. }
  35136. defines.REFRACTION = true;
  35137. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35138. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35139. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35140. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35141. if (this._linkRefractionWithTransparency) {
  35142. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35143. }
  35144. }
  35145. else {
  35146. defines.REFRACTION = false;
  35147. }
  35148. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35149. // This is blocking.
  35150. if (!this._environmentBRDFTexture.isReady()) {
  35151. return false;
  35152. }
  35153. defines.ENVIRONMENTBRDF = true;
  35154. }
  35155. else {
  35156. defines.ENVIRONMENTBRDF = false;
  35157. }
  35158. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35159. defines.ALPHAFROMALBEDO = true;
  35160. }
  35161. else {
  35162. defines.ALPHAFROMALBEDO = false;
  35163. }
  35164. }
  35165. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35166. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35167. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35168. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35169. defines.METALLICWORKFLOW = true;
  35170. }
  35171. else {
  35172. defines.METALLICWORKFLOW = false;
  35173. }
  35174. if (!this.backFaceCulling && this._twoSidedLighting) {
  35175. defines.TWOSIDEDLIGHTING = true;
  35176. }
  35177. else {
  35178. defines.TWOSIDEDLIGHTING = false;
  35179. }
  35180. defines.ALPHATESTVALUE = this._alphaCutOff;
  35181. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35182. defines.ALPHABLEND = this.needAlphaBlending();
  35183. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35184. }
  35185. if (defines._areImageProcessingDirty) {
  35186. if (!this._imageProcessingConfiguration.isReady()) {
  35187. return false;
  35188. }
  35189. this._imageProcessingConfiguration.prepareDefines(defines);
  35190. }
  35191. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35192. // Misc.
  35193. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35194. // Values that need to be evaluated on every frame
  35195. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35196. // Attribs
  35197. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35198. if (mesh) {
  35199. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35200. mesh.createNormals(true);
  35201. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35202. }
  35203. }
  35204. }
  35205. // Get correct effect
  35206. if (defines.isDirty) {
  35207. defines.markAsProcessed();
  35208. scene.resetCachedMaterial();
  35209. // Fallbacks
  35210. var fallbacks = new BABYLON.EffectFallbacks();
  35211. if (defines.ENVIRONMENTBRDF) {
  35212. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  35213. }
  35214. if (defines.REFLECTION) {
  35215. fallbacks.addFallback(0, "REFLECTION");
  35216. }
  35217. if (defines.REFRACTION) {
  35218. fallbacks.addFallback(0, "REFRACTION");
  35219. }
  35220. if (defines.REFLECTIVITY) {
  35221. fallbacks.addFallback(0, "REFLECTIVITY");
  35222. }
  35223. if (defines.BUMP) {
  35224. fallbacks.addFallback(0, "BUMP");
  35225. }
  35226. if (defines.PARALLAX) {
  35227. fallbacks.addFallback(1, "PARALLAX");
  35228. }
  35229. if (defines.PARALLAXOCCLUSION) {
  35230. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35231. }
  35232. if (defines.SPECULAROVERALPHA) {
  35233. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35234. }
  35235. if (defines.FOG) {
  35236. fallbacks.addFallback(1, "FOG");
  35237. }
  35238. if (defines.POINTSIZE) {
  35239. fallbacks.addFallback(0, "POINTSIZE");
  35240. }
  35241. if (defines.LOGARITHMICDEPTH) {
  35242. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35243. }
  35244. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35245. if (defines.SPECULARTERM) {
  35246. fallbacks.addFallback(0, "SPECULARTERM");
  35247. }
  35248. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35249. fallbacks.addCPUSkinningFallback(0, mesh);
  35250. }
  35251. //Attributes
  35252. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35253. if (defines.NORMAL) {
  35254. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35255. }
  35256. if (defines.TANGENT) {
  35257. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35258. }
  35259. if (defines.UV1) {
  35260. attribs.push(BABYLON.VertexBuffer.UVKind);
  35261. }
  35262. if (defines.UV2) {
  35263. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35264. }
  35265. if (defines.VERTEXCOLOR) {
  35266. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35267. }
  35268. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35269. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35270. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35271. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35272. "vFogInfos", "vFogColor", "pointSize",
  35273. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35274. "mBones",
  35275. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35276. "vLightingIntensity",
  35277. "logarithmicDepthConstant",
  35278. "vSphericalX", "vSphericalY", "vSphericalZ",
  35279. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35280. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35281. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  35282. "vTangentSpaceParams"
  35283. ];
  35284. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35285. "bumpSampler", "lightmapSampler", "opacitySampler",
  35286. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35287. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35288. "microSurfaceSampler", "environmentBrdfSampler"];
  35289. var uniformBuffers = ["Material", "Scene"];
  35290. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35291. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35292. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35293. uniformsNames: uniforms,
  35294. uniformBuffersNames: uniformBuffers,
  35295. samplers: samplers,
  35296. defines: defines,
  35297. maxSimultaneousLights: this._maxSimultaneousLights
  35298. });
  35299. var onCompiled = function (effect) {
  35300. if (_this.onCompiled) {
  35301. _this.onCompiled(effect);
  35302. }
  35303. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35304. };
  35305. var join = defines.toString();
  35306. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35307. attributes: attribs,
  35308. uniformsNames: uniforms,
  35309. uniformBuffersNames: uniformBuffers,
  35310. samplers: samplers,
  35311. defines: join,
  35312. fallbacks: fallbacks,
  35313. onCompiled: onCompiled,
  35314. onError: this.onError,
  35315. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35316. }, engine), defines);
  35317. this.buildUniformLayout();
  35318. }
  35319. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35320. return false;
  35321. }
  35322. defines._renderId = scene.getRenderId();
  35323. this._wasPreviouslyReady = true;
  35324. return true;
  35325. };
  35326. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35327. // Order is important !
  35328. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35329. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35330. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35331. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35332. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35333. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35334. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35335. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35336. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35337. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35338. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35339. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35340. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35341. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35342. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35343. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35344. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35345. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35346. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35347. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35348. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35349. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35350. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35351. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35352. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35353. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35354. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35355. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35356. this._uniformBuffer.addUniform("pointSize", 1);
  35357. this._uniformBuffer.create();
  35358. };
  35359. PBRBaseMaterial.prototype.unbind = function () {
  35360. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35361. this._uniformBuffer.setTexture("reflectionSampler", null);
  35362. }
  35363. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35364. this._uniformBuffer.setTexture("refractionSampler", null);
  35365. }
  35366. _super.prototype.unbind.call(this);
  35367. };
  35368. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35369. this._activeEffect.setMatrix("world", world);
  35370. };
  35371. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35372. var scene = this.getScene();
  35373. var defines = subMesh._materialDefines;
  35374. if (!defines) {
  35375. return;
  35376. }
  35377. var effect = subMesh.effect;
  35378. if (!effect) {
  35379. return;
  35380. }
  35381. this._activeEffect = effect;
  35382. // Matrices
  35383. this.bindOnlyWorldMatrix(world);
  35384. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35385. // Bones
  35386. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35387. var reflectionTexture = null;
  35388. if (mustRebind) {
  35389. this._uniformBuffer.bindToEffect(effect, "Material");
  35390. this.bindViewProjection(effect);
  35391. reflectionTexture = this._getReflectionTexture();
  35392. var refractionTexture = this._getRefractionTexture();
  35393. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35394. // Texture uniforms
  35395. if (scene.texturesEnabled) {
  35396. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35397. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35398. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35399. }
  35400. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35401. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35402. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35403. }
  35404. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35405. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35406. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35407. }
  35408. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35409. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35410. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35411. var polynomials = reflectionTexture.sphericalPolynomial;
  35412. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  35413. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35414. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35415. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35416. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35417. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35418. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35419. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35420. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35421. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35422. }
  35423. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35424. }
  35425. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35426. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35427. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35428. }
  35429. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35430. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35431. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35432. }
  35433. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35434. if (this._metallicTexture) {
  35435. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35436. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35437. }
  35438. else if (this._reflectivityTexture) {
  35439. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35440. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35441. }
  35442. if (this._microSurfaceTexture) {
  35443. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35444. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35445. }
  35446. }
  35447. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35448. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35449. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35450. if (scene._mirroredCameraPosition) {
  35451. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35452. }
  35453. else {
  35454. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35455. }
  35456. }
  35457. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35458. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35459. var depth = 1.0;
  35460. if (!refractionTexture.isCube) {
  35461. if (refractionTexture.depth) {
  35462. depth = refractionTexture.depth;
  35463. }
  35464. }
  35465. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35466. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35467. }
  35468. }
  35469. // Point size
  35470. if (this.pointsCloud) {
  35471. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35472. }
  35473. // Colors
  35474. if (defines.METALLICWORKFLOW) {
  35475. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35476. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35477. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35478. }
  35479. else {
  35480. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35481. }
  35482. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35483. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35484. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35485. // Misc
  35486. this._lightingInfos.x = this._directIntensity;
  35487. this._lightingInfos.y = this._emissiveIntensity;
  35488. this._lightingInfos.z = this._environmentIntensity;
  35489. this._lightingInfos.w = this._specularIntensity;
  35490. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35491. }
  35492. // Textures
  35493. if (scene.texturesEnabled) {
  35494. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35495. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35496. }
  35497. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35498. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35499. }
  35500. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35501. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35502. }
  35503. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35504. if (defines.LODBASEDMICROSFURACE) {
  35505. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35506. }
  35507. else {
  35508. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35509. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35510. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35511. }
  35512. }
  35513. if (defines.ENVIRONMENTBRDF) {
  35514. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35515. }
  35516. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35517. if (defines.LODBASEDMICROSFURACE) {
  35518. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35519. }
  35520. else {
  35521. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35522. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35523. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35524. }
  35525. }
  35526. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35527. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35528. }
  35529. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35530. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35531. }
  35532. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35533. if (this._metallicTexture) {
  35534. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35535. }
  35536. else if (this._reflectivityTexture) {
  35537. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35538. }
  35539. if (this._microSurfaceTexture) {
  35540. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35541. }
  35542. }
  35543. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35544. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35545. }
  35546. }
  35547. // Clip plane
  35548. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35549. // Colors
  35550. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35551. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35552. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  35553. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  35554. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35555. }
  35556. if (mustRebind || !this.isFrozen) {
  35557. // Lights
  35558. if (scene.lightsEnabled && !this._disableLighting) {
  35559. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35560. }
  35561. // View
  35562. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35563. this.bindView(effect);
  35564. }
  35565. // Fog
  35566. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35567. // Morph targets
  35568. if (defines.NUM_MORPH_INFLUENCERS) {
  35569. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35570. }
  35571. // image processing
  35572. this._imageProcessingConfiguration.bind(this._activeEffect);
  35573. // Log. depth
  35574. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35575. }
  35576. this._uniformBuffer.update();
  35577. this._afterBind(mesh);
  35578. };
  35579. PBRBaseMaterial.prototype.getAnimatables = function () {
  35580. var results = [];
  35581. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35582. results.push(this._albedoTexture);
  35583. }
  35584. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35585. results.push(this._ambientTexture);
  35586. }
  35587. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35588. results.push(this._opacityTexture);
  35589. }
  35590. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35591. results.push(this._reflectionTexture);
  35592. }
  35593. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35594. results.push(this._emissiveTexture);
  35595. }
  35596. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35597. results.push(this._metallicTexture);
  35598. }
  35599. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35600. results.push(this._reflectivityTexture);
  35601. }
  35602. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35603. results.push(this._bumpTexture);
  35604. }
  35605. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35606. results.push(this._lightmapTexture);
  35607. }
  35608. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35609. results.push(this._refractionTexture);
  35610. }
  35611. return results;
  35612. };
  35613. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  35614. if (this._reflectionTexture) {
  35615. return this._reflectionTexture;
  35616. }
  35617. return this.getScene().environmentTexture;
  35618. };
  35619. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  35620. if (this._refractionTexture) {
  35621. return this._refractionTexture;
  35622. }
  35623. if (this._linkRefractionWithTransparency) {
  35624. return this.getScene().environmentTexture;
  35625. }
  35626. return null;
  35627. };
  35628. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35629. if (forceDisposeTextures) {
  35630. if (this._albedoTexture) {
  35631. this._albedoTexture.dispose();
  35632. }
  35633. if (this._ambientTexture) {
  35634. this._ambientTexture.dispose();
  35635. }
  35636. if (this._opacityTexture) {
  35637. this._opacityTexture.dispose();
  35638. }
  35639. if (this._reflectionTexture) {
  35640. this._reflectionTexture.dispose();
  35641. }
  35642. if (this._environmentBRDFTexture) {
  35643. this._environmentBRDFTexture.dispose();
  35644. }
  35645. if (this._emissiveTexture) {
  35646. this._emissiveTexture.dispose();
  35647. }
  35648. if (this._metallicTexture) {
  35649. this._metallicTexture.dispose();
  35650. }
  35651. if (this._reflectivityTexture) {
  35652. this._reflectivityTexture.dispose();
  35653. }
  35654. if (this._bumpTexture) {
  35655. this._bumpTexture.dispose();
  35656. }
  35657. if (this._lightmapTexture) {
  35658. this._lightmapTexture.dispose();
  35659. }
  35660. if (this._refractionTexture) {
  35661. this._refractionTexture.dispose();
  35662. }
  35663. }
  35664. this._renderTargets.dispose();
  35665. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35666. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35667. }
  35668. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35669. };
  35670. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35671. __decorate([
  35672. BABYLON.serializeAsImageProcessingConfiguration()
  35673. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35674. __decorate([
  35675. BABYLON.serialize()
  35676. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35677. return PBRBaseMaterial;
  35678. }(BABYLON.PushMaterial));
  35679. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35680. })(BABYLON || (BABYLON = {}));
  35681. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35682. var BABYLON;
  35683. (function (BABYLON) {
  35684. var Internals;
  35685. (function (Internals) {
  35686. /**
  35687. * The Physically based simple base material of BJS.
  35688. *
  35689. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35690. * It is used as the base class for both the specGloss and metalRough conventions.
  35691. */
  35692. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  35693. __extends(PBRBaseSimpleMaterial, _super);
  35694. /**
  35695. * Instantiates a new PBRMaterial instance.
  35696. *
  35697. * @param name The material name
  35698. * @param scene The scene the material will be use in.
  35699. */
  35700. function PBRBaseSimpleMaterial(name, scene) {
  35701. var _this = _super.call(this, name, scene) || this;
  35702. /**
  35703. * Number of Simultaneous lights allowed on the material.
  35704. */
  35705. _this.maxSimultaneousLights = 4;
  35706. /**
  35707. * If sets to true, disables all the lights affecting the material.
  35708. */
  35709. _this.disableLighting = false;
  35710. /**
  35711. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35712. */
  35713. _this.invertNormalMapX = false;
  35714. /**
  35715. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35716. */
  35717. _this.invertNormalMapY = false;
  35718. /**
  35719. * Emissivie color used to self-illuminate the model.
  35720. */
  35721. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35722. /**
  35723. * Occlusion Channel Strenght.
  35724. */
  35725. _this.occlusionStrength = 1.0;
  35726. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35727. _this._useAmbientInGrayScale = true;
  35728. return _this;
  35729. }
  35730. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35731. /**
  35732. * Gets the current transparency mode.
  35733. */
  35734. get: function () {
  35735. return this._transparencyMode;
  35736. },
  35737. /**
  35738. * Sets the transparency mode of the material.
  35739. */
  35740. set: function (value) {
  35741. if (this._transparencyMode === value) {
  35742. return;
  35743. }
  35744. this._transparencyMode = value;
  35745. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35746. this._forceAlphaTest = true;
  35747. }
  35748. else {
  35749. this._forceAlphaTest = false;
  35750. }
  35751. this._markAllSubMeshesAsTexturesDirty();
  35752. },
  35753. enumerable: true,
  35754. configurable: true
  35755. });
  35756. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35757. /**
  35758. * Gets the current double sided mode.
  35759. */
  35760. get: function () {
  35761. return this._twoSidedLighting;
  35762. },
  35763. /**
  35764. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35765. */
  35766. set: function (value) {
  35767. if (this._twoSidedLighting === value) {
  35768. return;
  35769. }
  35770. this._twoSidedLighting = value;
  35771. this.backFaceCulling = !value;
  35772. this._markAllSubMeshesAsTexturesDirty();
  35773. },
  35774. enumerable: true,
  35775. configurable: true
  35776. });
  35777. /**
  35778. * Specifies wether or not the alpha value of the albedo texture should be used.
  35779. */
  35780. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35781. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35782. };
  35783. /**
  35784. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35785. */
  35786. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35787. if (this._linkRefractionWithTransparency) {
  35788. return false;
  35789. }
  35790. return (this.alpha < 1.0) ||
  35791. (this._shouldUseAlphaFromAlbedoTexture() &&
  35792. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35793. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35794. };
  35795. /**
  35796. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35797. */
  35798. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35799. if (this._linkRefractionWithTransparency) {
  35800. return false;
  35801. }
  35802. return this._shouldUseAlphaFromAlbedoTexture() &&
  35803. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35804. };
  35805. /**
  35806. * Return the active textures of the material.
  35807. */
  35808. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  35809. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35810. if (this.environmentTexture) {
  35811. activeTextures.push(this.environmentTexture);
  35812. }
  35813. if (this.normalTexture) {
  35814. activeTextures.push(this.normalTexture);
  35815. }
  35816. if (this.emissiveTexture) {
  35817. activeTextures.push(this.emissiveTexture);
  35818. }
  35819. if (this.occlusionTexture) {
  35820. activeTextures.push(this.occlusionTexture);
  35821. }
  35822. return activeTextures;
  35823. };
  35824. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  35825. return "PBRBaseSimpleMaterial";
  35826. };
  35827. __decorate([
  35828. BABYLON.serialize(),
  35829. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35830. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35831. __decorate([
  35832. BABYLON.serialize(),
  35833. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35834. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35835. __decorate([
  35836. BABYLON.serializeAsTexture(),
  35837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35838. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35839. __decorate([
  35840. BABYLON.serialize(),
  35841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35842. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  35843. __decorate([
  35844. BABYLON.serialize(),
  35845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35846. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  35847. __decorate([
  35848. BABYLON.serializeAsTexture(),
  35849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  35850. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  35851. __decorate([
  35852. BABYLON.serializeAsColor3("emissive"),
  35853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35854. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  35855. __decorate([
  35856. BABYLON.serializeAsTexture(),
  35857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35858. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  35859. __decorate([
  35860. BABYLON.serialize(),
  35861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  35862. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  35863. __decorate([
  35864. BABYLON.serializeAsTexture(),
  35865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  35866. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  35867. __decorate([
  35868. BABYLON.serialize(),
  35869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  35870. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  35871. __decorate([
  35872. BABYLON.serialize()
  35873. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  35874. __decorate([
  35875. BABYLON.serialize()
  35876. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  35877. return PBRBaseSimpleMaterial;
  35878. }(BABYLON.PBRBaseMaterial));
  35879. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  35880. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35881. })(BABYLON || (BABYLON = {}));
  35882. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  35883. var BABYLON;
  35884. (function (BABYLON) {
  35885. /**
  35886. * The Physically based material of BJS.
  35887. *
  35888. * This offers the main features of a standard PBR material.
  35889. * For more information, please refer to the documentation :
  35890. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35891. */
  35892. var PBRMaterial = /** @class */ (function (_super) {
  35893. __extends(PBRMaterial, _super);
  35894. /**
  35895. * Instantiates a new PBRMaterial instance.
  35896. *
  35897. * @param name The material name
  35898. * @param scene The scene the material will be use in.
  35899. */
  35900. function PBRMaterial(name, scene) {
  35901. var _this = _super.call(this, name, scene) || this;
  35902. /**
  35903. * Intensity of the direct lights e.g. the four lights available in your scene.
  35904. * This impacts both the direct diffuse and specular highlights.
  35905. */
  35906. _this.directIntensity = 1.0;
  35907. /**
  35908. * Intensity of the emissive part of the material.
  35909. * This helps controlling the emissive effect without modifying the emissive color.
  35910. */
  35911. _this.emissiveIntensity = 1.0;
  35912. /**
  35913. * Intensity of the environment e.g. how much the environment will light the object
  35914. * either through harmonics for rough material or through the refelction for shiny ones.
  35915. */
  35916. _this.environmentIntensity = 1.0;
  35917. /**
  35918. * This is a special control allowing the reduction of the specular highlights coming from the
  35919. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35920. */
  35921. _this.specularIntensity = 1.0;
  35922. /**
  35923. * Debug Control allowing disabling the bump map on this material.
  35924. */
  35925. _this.disableBumpMap = false;
  35926. /**
  35927. * AKA Occlusion Texture Intensity in other nomenclature.
  35928. */
  35929. _this.ambientTextureStrength = 1.0;
  35930. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35931. /**
  35932. * AKA Diffuse Color in other nomenclature.
  35933. */
  35934. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35935. /**
  35936. * AKA Specular Color in other nomenclature.
  35937. */
  35938. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35939. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  35940. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35941. /**
  35942. * AKA Glossiness in other nomenclature.
  35943. */
  35944. _this.microSurface = 1.0;
  35945. /**
  35946. * source material index of refraction (IOR)' / 'destination material IOR.
  35947. */
  35948. _this.indexOfRefraction = 0.66;
  35949. /**
  35950. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35951. */
  35952. _this.invertRefractionY = false;
  35953. /**
  35954. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35955. * Materials half opaque for instance using refraction could benefit from this control.
  35956. */
  35957. _this.linkRefractionWithTransparency = false;
  35958. _this.useLightmapAsShadowmap = false;
  35959. /**
  35960. * Specifies that the alpha is coming form the albedo channel alpha channel.
  35961. */
  35962. _this.useAlphaFromAlbedoTexture = false;
  35963. /**
  35964. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35965. */
  35966. _this.forceAlphaTest = false;
  35967. /**
  35968. * Defines the alpha limits in alpha test mode.
  35969. */
  35970. _this.alphaCutOff = 0.4;
  35971. /**
  35972. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35973. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35974. */
  35975. _this.useSpecularOverAlpha = true;
  35976. /**
  35977. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35978. */
  35979. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  35980. /**
  35981. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35982. */
  35983. _this.useRoughnessFromMetallicTextureAlpha = true;
  35984. /**
  35985. * Specifies if the metallic texture contains the roughness information in its green channel.
  35986. */
  35987. _this.useRoughnessFromMetallicTextureGreen = false;
  35988. /**
  35989. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35990. */
  35991. _this.useMetallnessFromMetallicTextureBlue = false;
  35992. /**
  35993. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35994. */
  35995. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  35996. /**
  35997. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35998. */
  35999. _this.useAmbientInGrayScale = false;
  36000. /**
  36001. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36002. * The material will try to infer what glossiness each pixel should be.
  36003. */
  36004. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36005. /**
  36006. * BJS is using an harcoded light falloff based on a manually sets up range.
  36007. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36008. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36009. */
  36010. _this.usePhysicalLightFalloff = true;
  36011. /**
  36012. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36013. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36014. */
  36015. _this.useRadianceOverAlpha = true;
  36016. /**
  36017. * Allows using the bump map in parallax mode.
  36018. */
  36019. _this.useParallax = false;
  36020. /**
  36021. * Allows using the bump map in parallax occlusion mode.
  36022. */
  36023. _this.useParallaxOcclusion = false;
  36024. /**
  36025. * Controls the scale bias of the parallax mode.
  36026. */
  36027. _this.parallaxScaleBias = 0.05;
  36028. /**
  36029. * If sets to true, disables all the lights affecting the material.
  36030. */
  36031. _this.disableLighting = false;
  36032. /**
  36033. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36034. */
  36035. _this.forceIrradianceInFragment = false;
  36036. /**
  36037. * Number of Simultaneous lights allowed on the material.
  36038. */
  36039. _this.maxSimultaneousLights = 4;
  36040. /**
  36041. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36042. */
  36043. _this.invertNormalMapX = false;
  36044. /**
  36045. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36046. */
  36047. _this.invertNormalMapY = false;
  36048. /**
  36049. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36050. */
  36051. _this.twoSidedLighting = false;
  36052. /**
  36053. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36054. * And/Or occlude the blended part.
  36055. */
  36056. _this.useAlphaFresnel = false;
  36057. /**
  36058. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36059. * And/Or occlude the blended part.
  36060. */
  36061. _this.environmentBRDFTexture = null;
  36062. /**
  36063. * Force normal to face away from face.
  36064. * (Temporary internal fix to remove before 3.1)
  36065. */
  36066. _this.forceNormalForward = false;
  36067. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36068. return _this;
  36069. }
  36070. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36071. /**
  36072. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36073. */
  36074. get: function () {
  36075. return this._PBRMATERIAL_OPAQUE;
  36076. },
  36077. enumerable: true,
  36078. configurable: true
  36079. });
  36080. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36081. /**
  36082. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36083. */
  36084. get: function () {
  36085. return this._PBRMATERIAL_ALPHATEST;
  36086. },
  36087. enumerable: true,
  36088. configurable: true
  36089. });
  36090. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36091. /**
  36092. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36093. */
  36094. get: function () {
  36095. return this._PBRMATERIAL_ALPHABLEND;
  36096. },
  36097. enumerable: true,
  36098. configurable: true
  36099. });
  36100. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36101. /**
  36102. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36103. * They are also discarded below the alpha cutoff threshold to improve performances.
  36104. */
  36105. get: function () {
  36106. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36107. },
  36108. enumerable: true,
  36109. configurable: true
  36110. });
  36111. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36112. /**
  36113. * Gets the image processing configuration used either in this material.
  36114. */
  36115. get: function () {
  36116. return this._imageProcessingConfiguration;
  36117. },
  36118. /**
  36119. * Sets the Default image processing configuration used either in the this material.
  36120. *
  36121. * If sets to null, the scene one is in use.
  36122. */
  36123. set: function (value) {
  36124. this._attachImageProcessingConfiguration(value);
  36125. // Ensure the effect will be rebuilt.
  36126. this._markAllSubMeshesAsTexturesDirty();
  36127. },
  36128. enumerable: true,
  36129. configurable: true
  36130. });
  36131. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36132. /**
  36133. * Gets wether the color curves effect is enabled.
  36134. */
  36135. get: function () {
  36136. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36137. },
  36138. /**
  36139. * Sets wether the color curves effect is enabled.
  36140. */
  36141. set: function (value) {
  36142. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36143. },
  36144. enumerable: true,
  36145. configurable: true
  36146. });
  36147. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36148. /**
  36149. * Gets wether the color grading effect is enabled.
  36150. */
  36151. get: function () {
  36152. return this.imageProcessingConfiguration.colorGradingEnabled;
  36153. },
  36154. /**
  36155. * Gets wether the color grading effect is enabled.
  36156. */
  36157. set: function (value) {
  36158. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36159. },
  36160. enumerable: true,
  36161. configurable: true
  36162. });
  36163. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36164. /**
  36165. * Gets wether tonemapping is enabled or not.
  36166. */
  36167. get: function () {
  36168. return this._imageProcessingConfiguration.toneMappingEnabled;
  36169. },
  36170. /**
  36171. * Sets wether tonemapping is enabled or not
  36172. */
  36173. set: function (value) {
  36174. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36175. },
  36176. enumerable: true,
  36177. configurable: true
  36178. });
  36179. ;
  36180. ;
  36181. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36182. /**
  36183. * The camera exposure used on this material.
  36184. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36185. * This corresponds to a photographic exposure.
  36186. */
  36187. get: function () {
  36188. return this._imageProcessingConfiguration.exposure;
  36189. },
  36190. /**
  36191. * The camera exposure used on this material.
  36192. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36193. * This corresponds to a photographic exposure.
  36194. */
  36195. set: function (value) {
  36196. this._imageProcessingConfiguration.exposure = value;
  36197. },
  36198. enumerable: true,
  36199. configurable: true
  36200. });
  36201. ;
  36202. ;
  36203. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36204. /**
  36205. * Gets The camera contrast used on this material.
  36206. */
  36207. get: function () {
  36208. return this._imageProcessingConfiguration.contrast;
  36209. },
  36210. /**
  36211. * Sets The camera contrast used on this material.
  36212. */
  36213. set: function (value) {
  36214. this._imageProcessingConfiguration.contrast = value;
  36215. },
  36216. enumerable: true,
  36217. configurable: true
  36218. });
  36219. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36220. /**
  36221. * Gets the Color Grading 2D Lookup Texture.
  36222. */
  36223. get: function () {
  36224. return this._imageProcessingConfiguration.colorGradingTexture;
  36225. },
  36226. /**
  36227. * Sets the Color Grading 2D Lookup Texture.
  36228. */
  36229. set: function (value) {
  36230. this._imageProcessingConfiguration.colorGradingTexture = value;
  36231. },
  36232. enumerable: true,
  36233. configurable: true
  36234. });
  36235. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36236. /**
  36237. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36238. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36239. * 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;
  36240. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36241. */
  36242. get: function () {
  36243. return this._imageProcessingConfiguration.colorCurves;
  36244. },
  36245. /**
  36246. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36247. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36248. * 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;
  36249. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36250. */
  36251. set: function (value) {
  36252. this._imageProcessingConfiguration.colorCurves = value;
  36253. },
  36254. enumerable: true,
  36255. configurable: true
  36256. });
  36257. PBRMaterial.prototype.getClassName = function () {
  36258. return "PBRMaterial";
  36259. };
  36260. PBRMaterial.prototype.getActiveTextures = function () {
  36261. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36262. if (this._albedoTexture) {
  36263. activeTextures.push(this._albedoTexture);
  36264. }
  36265. if (this._ambientTexture) {
  36266. activeTextures.push(this._ambientTexture);
  36267. }
  36268. if (this._opacityTexture) {
  36269. activeTextures.push(this._opacityTexture);
  36270. }
  36271. if (this._reflectionTexture) {
  36272. activeTextures.push(this._reflectionTexture);
  36273. }
  36274. if (this._emissiveTexture) {
  36275. activeTextures.push(this._emissiveTexture);
  36276. }
  36277. if (this._reflectivityTexture) {
  36278. activeTextures.push(this._reflectivityTexture);
  36279. }
  36280. if (this._metallicTexture) {
  36281. activeTextures.push(this._metallicTexture);
  36282. }
  36283. if (this._microSurfaceTexture) {
  36284. activeTextures.push(this._microSurfaceTexture);
  36285. }
  36286. if (this._bumpTexture) {
  36287. activeTextures.push(this._bumpTexture);
  36288. }
  36289. if (this._lightmapTexture) {
  36290. activeTextures.push(this._lightmapTexture);
  36291. }
  36292. if (this._refractionTexture) {
  36293. activeTextures.push(this._refractionTexture);
  36294. }
  36295. return activeTextures;
  36296. };
  36297. PBRMaterial.prototype.hasTexture = function (texture) {
  36298. if (_super.prototype.hasTexture.call(this, texture)) {
  36299. return true;
  36300. }
  36301. if (this._albedoTexture === texture) {
  36302. return true;
  36303. }
  36304. if (this._ambientTexture === texture) {
  36305. return true;
  36306. }
  36307. if (this._opacityTexture === texture) {
  36308. return true;
  36309. }
  36310. if (this._reflectionTexture === texture) {
  36311. return true;
  36312. }
  36313. if (this._reflectivityTexture === texture) {
  36314. return true;
  36315. }
  36316. if (this._metallicTexture === texture) {
  36317. return true;
  36318. }
  36319. if (this._microSurfaceTexture === texture) {
  36320. return true;
  36321. }
  36322. if (this._bumpTexture === texture) {
  36323. return true;
  36324. }
  36325. if (this._lightmapTexture === texture) {
  36326. return true;
  36327. }
  36328. if (this._refractionTexture === texture) {
  36329. return true;
  36330. }
  36331. return false;
  36332. };
  36333. PBRMaterial.prototype.clone = function (name) {
  36334. var _this = this;
  36335. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36336. clone.id = name;
  36337. clone.name = name;
  36338. return clone;
  36339. };
  36340. PBRMaterial.prototype.serialize = function () {
  36341. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36342. serializationObject.customType = "BABYLON.PBRMaterial";
  36343. return serializationObject;
  36344. };
  36345. // Statics
  36346. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36347. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36348. };
  36349. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36350. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36351. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36352. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36353. __decorate([
  36354. BABYLON.serialize(),
  36355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36356. ], PBRMaterial.prototype, "directIntensity", void 0);
  36357. __decorate([
  36358. BABYLON.serialize(),
  36359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36360. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36361. __decorate([
  36362. BABYLON.serialize(),
  36363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36364. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36365. __decorate([
  36366. BABYLON.serialize(),
  36367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36368. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36369. __decorate([
  36370. BABYLON.serialize(),
  36371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36372. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36373. __decorate([
  36374. BABYLON.serializeAsTexture(),
  36375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36376. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36377. __decorate([
  36378. BABYLON.serializeAsTexture(),
  36379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36380. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36381. __decorate([
  36382. BABYLON.serialize(),
  36383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36384. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36385. __decorate([
  36386. BABYLON.serializeAsTexture(),
  36387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36388. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36389. __decorate([
  36390. BABYLON.serializeAsTexture(),
  36391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36392. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36393. __decorate([
  36394. BABYLON.serializeAsTexture(),
  36395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36396. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36397. __decorate([
  36398. BABYLON.serializeAsTexture(),
  36399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36400. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36401. __decorate([
  36402. BABYLON.serializeAsTexture(),
  36403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36404. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36405. __decorate([
  36406. BABYLON.serialize(),
  36407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36408. ], PBRMaterial.prototype, "metallic", void 0);
  36409. __decorate([
  36410. BABYLON.serialize(),
  36411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36412. ], PBRMaterial.prototype, "roughness", void 0);
  36413. __decorate([
  36414. BABYLON.serializeAsTexture(),
  36415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36416. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36417. __decorate([
  36418. BABYLON.serializeAsTexture(),
  36419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36420. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36421. __decorate([
  36422. BABYLON.serializeAsTexture(),
  36423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36424. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36425. __decorate([
  36426. BABYLON.serializeAsTexture(),
  36427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36428. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36429. __decorate([
  36430. BABYLON.serializeAsColor3("ambient"),
  36431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36432. ], PBRMaterial.prototype, "ambientColor", void 0);
  36433. __decorate([
  36434. BABYLON.serializeAsColor3("albedo"),
  36435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36436. ], PBRMaterial.prototype, "albedoColor", void 0);
  36437. __decorate([
  36438. BABYLON.serializeAsColor3("reflectivity"),
  36439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36440. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36441. __decorate([
  36442. BABYLON.serializeAsColor3("reflection"),
  36443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36444. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36445. __decorate([
  36446. BABYLON.serializeAsColor3("emissive"),
  36447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36448. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36449. __decorate([
  36450. BABYLON.serialize(),
  36451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36452. ], PBRMaterial.prototype, "microSurface", void 0);
  36453. __decorate([
  36454. BABYLON.serialize(),
  36455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36456. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36457. __decorate([
  36458. BABYLON.serialize(),
  36459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36460. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36461. __decorate([
  36462. BABYLON.serialize(),
  36463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36464. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36465. __decorate([
  36466. BABYLON.serialize(),
  36467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36468. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36469. __decorate([
  36470. BABYLON.serialize(),
  36471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36472. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36473. __decorate([
  36474. BABYLON.serialize(),
  36475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36476. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  36477. __decorate([
  36478. BABYLON.serialize(),
  36479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36480. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  36481. __decorate([
  36482. BABYLON.serialize(),
  36483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36484. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36485. __decorate([
  36486. BABYLON.serialize(),
  36487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36488. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36489. __decorate([
  36490. BABYLON.serialize(),
  36491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36492. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36493. __decorate([
  36494. BABYLON.serialize(),
  36495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36496. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36497. __decorate([
  36498. BABYLON.serialize(),
  36499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36500. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36501. __decorate([
  36502. BABYLON.serialize(),
  36503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36504. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36505. __decorate([
  36506. BABYLON.serialize(),
  36507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36508. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36509. __decorate([
  36510. BABYLON.serialize(),
  36511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36512. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36513. __decorate([
  36514. BABYLON.serialize(),
  36515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36516. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36517. __decorate([
  36518. BABYLON.serialize(),
  36519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36520. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36521. __decorate([
  36522. BABYLON.serialize(),
  36523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36524. ], PBRMaterial.prototype, "useParallax", void 0);
  36525. __decorate([
  36526. BABYLON.serialize(),
  36527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36528. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36529. __decorate([
  36530. BABYLON.serialize(),
  36531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36532. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36533. __decorate([
  36534. BABYLON.serialize(),
  36535. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36536. ], PBRMaterial.prototype, "disableLighting", void 0);
  36537. __decorate([
  36538. BABYLON.serialize(),
  36539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36540. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  36541. __decorate([
  36542. BABYLON.serialize(),
  36543. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36544. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36545. __decorate([
  36546. BABYLON.serialize(),
  36547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36548. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36549. __decorate([
  36550. BABYLON.serialize(),
  36551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36552. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36553. __decorate([
  36554. BABYLON.serialize(),
  36555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36556. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36557. __decorate([
  36558. BABYLON.serialize(),
  36559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36560. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36561. __decorate([
  36562. BABYLON.serializeAsTexture(),
  36563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36564. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36565. __decorate([
  36566. BABYLON.serialize(),
  36567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36568. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36569. return PBRMaterial;
  36570. }(BABYLON.PBRBaseMaterial));
  36571. BABYLON.PBRMaterial = PBRMaterial;
  36572. })(BABYLON || (BABYLON = {}));
  36573. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36574. var BABYLON;
  36575. (function (BABYLON) {
  36576. /**
  36577. * The PBR material of BJS following the metal roughness convention.
  36578. *
  36579. * This fits to the PBR convention in the GLTF definition:
  36580. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36581. */
  36582. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36583. __extends(PBRMetallicRoughnessMaterial, _super);
  36584. /**
  36585. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36586. *
  36587. * @param name The material name
  36588. * @param scene The scene the material will be use in.
  36589. */
  36590. function PBRMetallicRoughnessMaterial(name, scene) {
  36591. var _this = _super.call(this, name, scene) || this;
  36592. _this._useRoughnessFromMetallicTextureAlpha = false;
  36593. _this._useRoughnessFromMetallicTextureGreen = true;
  36594. _this._useMetallnessFromMetallicTextureBlue = true;
  36595. return _this;
  36596. }
  36597. /**
  36598. * Return the currrent class name of the material.
  36599. */
  36600. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36601. return "PBRMetallicRoughnessMaterial";
  36602. };
  36603. /**
  36604. * Return the active textures of the material.
  36605. */
  36606. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36607. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36608. if (this.baseTexture) {
  36609. activeTextures.push(this.baseTexture);
  36610. }
  36611. if (this.metallicRoughnessTexture) {
  36612. activeTextures.push(this.metallicRoughnessTexture);
  36613. }
  36614. return activeTextures;
  36615. };
  36616. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36617. if (_super.prototype.hasTexture.call(this, texture)) {
  36618. return true;
  36619. }
  36620. if (this.baseTexture === texture) {
  36621. return true;
  36622. }
  36623. if (this.metallicRoughnessTexture === texture) {
  36624. return true;
  36625. }
  36626. return false;
  36627. };
  36628. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36629. var _this = this;
  36630. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36631. clone.id = name;
  36632. clone.name = name;
  36633. return clone;
  36634. };
  36635. /**
  36636. * Serialize the material to a parsable JSON object.
  36637. */
  36638. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36639. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36640. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36641. return serializationObject;
  36642. };
  36643. /**
  36644. * Parses a JSON object correponding to the serialize function.
  36645. */
  36646. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36647. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36648. };
  36649. __decorate([
  36650. BABYLON.serializeAsColor3(),
  36651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36652. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36653. __decorate([
  36654. BABYLON.serializeAsTexture(),
  36655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36656. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36657. __decorate([
  36658. BABYLON.serialize(),
  36659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36660. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36661. __decorate([
  36662. BABYLON.serialize(),
  36663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36664. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36665. __decorate([
  36666. BABYLON.serializeAsTexture(),
  36667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36668. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36669. return PBRMetallicRoughnessMaterial;
  36670. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36671. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36672. })(BABYLON || (BABYLON = {}));
  36673. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36674. var BABYLON;
  36675. (function (BABYLON) {
  36676. /**
  36677. * The PBR material of BJS following the specular glossiness convention.
  36678. *
  36679. * This fits to the PBR convention in the GLTF definition:
  36680. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36681. */
  36682. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  36683. __extends(PBRSpecularGlossinessMaterial, _super);
  36684. /**
  36685. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36686. *
  36687. * @param name The material name
  36688. * @param scene The scene the material will be use in.
  36689. */
  36690. function PBRSpecularGlossinessMaterial(name, scene) {
  36691. var _this = _super.call(this, name, scene) || this;
  36692. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36693. return _this;
  36694. }
  36695. /**
  36696. * Return the currrent class name of the material.
  36697. */
  36698. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36699. return "PBRSpecularGlossinessMaterial";
  36700. };
  36701. /**
  36702. * Return the active textures of the material.
  36703. */
  36704. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36705. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36706. if (this.diffuseTexture) {
  36707. activeTextures.push(this.diffuseTexture);
  36708. }
  36709. if (this.specularGlossinessTexture) {
  36710. activeTextures.push(this.specularGlossinessTexture);
  36711. }
  36712. return activeTextures;
  36713. };
  36714. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  36715. if (_super.prototype.hasTexture.call(this, texture)) {
  36716. return true;
  36717. }
  36718. if (this.diffuseTexture === texture) {
  36719. return true;
  36720. }
  36721. if (this.specularGlossinessTexture === texture) {
  36722. return true;
  36723. }
  36724. return false;
  36725. };
  36726. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36727. var _this = this;
  36728. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36729. clone.id = name;
  36730. clone.name = name;
  36731. return clone;
  36732. };
  36733. /**
  36734. * Serialize the material to a parsable JSON object.
  36735. */
  36736. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36737. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36738. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36739. return serializationObject;
  36740. };
  36741. /**
  36742. * Parses a JSON object correponding to the serialize function.
  36743. */
  36744. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36745. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36746. };
  36747. __decorate([
  36748. BABYLON.serializeAsColor3("diffuse"),
  36749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36750. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36751. __decorate([
  36752. BABYLON.serializeAsTexture(),
  36753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36754. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36755. __decorate([
  36756. BABYLON.serializeAsColor3("specular"),
  36757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36758. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36759. __decorate([
  36760. BABYLON.serialize(),
  36761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36762. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36763. __decorate([
  36764. BABYLON.serializeAsTexture(),
  36765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36766. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36767. return PBRSpecularGlossinessMaterial;
  36768. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36769. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36770. })(BABYLON || (BABYLON = {}));
  36771. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36772. var BABYLON;
  36773. (function (BABYLON) {
  36774. BABYLON.CameraInputTypes = {};
  36775. var CameraInputsManager = /** @class */ (function () {
  36776. function CameraInputsManager(camera) {
  36777. this.attached = {};
  36778. this.camera = camera;
  36779. this.checkInputs = function () { };
  36780. }
  36781. CameraInputsManager.prototype.add = function (input) {
  36782. var type = input.getSimpleName();
  36783. if (this.attached[type]) {
  36784. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  36785. return;
  36786. }
  36787. this.attached[type] = input;
  36788. input.camera = this.camera;
  36789. //for checkInputs, we are dynamically creating a function
  36790. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  36791. if (input.checkInputs) {
  36792. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36793. }
  36794. if (this.attachedElement) {
  36795. input.attachControl(this.attachedElement);
  36796. }
  36797. };
  36798. CameraInputsManager.prototype.remove = function (inputToRemove) {
  36799. for (var cam in this.attached) {
  36800. var input = this.attached[cam];
  36801. if (input === inputToRemove) {
  36802. input.detachControl(this.attachedElement);
  36803. input.camera = null;
  36804. delete this.attached[cam];
  36805. this.rebuildInputCheck();
  36806. }
  36807. }
  36808. };
  36809. CameraInputsManager.prototype.removeByType = function (inputType) {
  36810. for (var cam in this.attached) {
  36811. var input = this.attached[cam];
  36812. if (input.getClassName() === inputType) {
  36813. input.detachControl(this.attachedElement);
  36814. input.camera = null;
  36815. delete this.attached[cam];
  36816. this.rebuildInputCheck();
  36817. }
  36818. }
  36819. };
  36820. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  36821. var current = this.checkInputs;
  36822. return function () {
  36823. current();
  36824. fn();
  36825. };
  36826. };
  36827. CameraInputsManager.prototype.attachInput = function (input) {
  36828. if (this.attachedElement) {
  36829. input.attachControl(this.attachedElement, this.noPreventDefault);
  36830. }
  36831. };
  36832. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  36833. if (noPreventDefault === void 0) { noPreventDefault = false; }
  36834. if (this.attachedElement) {
  36835. return;
  36836. }
  36837. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  36838. this.attachedElement = element;
  36839. this.noPreventDefault = noPreventDefault;
  36840. for (var cam in this.attached) {
  36841. this.attached[cam].attachControl(element, noPreventDefault);
  36842. }
  36843. };
  36844. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  36845. if (disconnect === void 0) { disconnect = false; }
  36846. if (this.attachedElement !== element) {
  36847. return;
  36848. }
  36849. for (var cam in this.attached) {
  36850. this.attached[cam].detachControl(element);
  36851. if (disconnect) {
  36852. this.attached[cam].camera = null;
  36853. }
  36854. }
  36855. this.attachedElement = null;
  36856. };
  36857. CameraInputsManager.prototype.rebuildInputCheck = function () {
  36858. this.checkInputs = function () { };
  36859. for (var cam in this.attached) {
  36860. var input = this.attached[cam];
  36861. if (input.checkInputs) {
  36862. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36863. }
  36864. }
  36865. };
  36866. CameraInputsManager.prototype.clear = function () {
  36867. if (this.attachedElement) {
  36868. this.detachElement(this.attachedElement, true);
  36869. }
  36870. this.attached = {};
  36871. this.attachedElement = null;
  36872. this.checkInputs = function () { };
  36873. };
  36874. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  36875. var inputs = {};
  36876. for (var cam in this.attached) {
  36877. var input = this.attached[cam];
  36878. var res = BABYLON.SerializationHelper.Serialize(input);
  36879. inputs[input.getClassName()] = res;
  36880. }
  36881. serializedCamera.inputsmgr = inputs;
  36882. };
  36883. CameraInputsManager.prototype.parse = function (parsedCamera) {
  36884. var parsedInputs = parsedCamera.inputsmgr;
  36885. if (parsedInputs) {
  36886. this.clear();
  36887. for (var n in parsedInputs) {
  36888. var construct = BABYLON.CameraInputTypes[n];
  36889. if (construct) {
  36890. var parsedinput = parsedInputs[n];
  36891. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  36892. this.add(input);
  36893. }
  36894. }
  36895. }
  36896. else {
  36897. //2016-03-08 this part is for managing backward compatibility
  36898. for (var n in this.attached) {
  36899. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  36900. if (construct) {
  36901. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  36902. this.remove(this.attached[n]);
  36903. this.add(input);
  36904. }
  36905. }
  36906. }
  36907. };
  36908. return CameraInputsManager;
  36909. }());
  36910. BABYLON.CameraInputsManager = CameraInputsManager;
  36911. })(BABYLON || (BABYLON = {}));
  36912. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  36913. var BABYLON;
  36914. (function (BABYLON) {
  36915. var FreeCameraMouseInput = /** @class */ (function () {
  36916. function FreeCameraMouseInput(touchEnabled) {
  36917. if (touchEnabled === void 0) { touchEnabled = true; }
  36918. this.touchEnabled = touchEnabled;
  36919. this.buttons = [0, 1, 2];
  36920. this.angularSensibility = 2000.0;
  36921. this.previousPosition = null;
  36922. }
  36923. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  36924. var _this = this;
  36925. var engine = this.camera.getEngine();
  36926. if (!this._pointerInput) {
  36927. this._pointerInput = function (p, s) {
  36928. var evt = p.event;
  36929. if (engine.isInVRExclusivePointerMode) {
  36930. return;
  36931. }
  36932. if (!_this.touchEnabled && evt.pointerType === "touch") {
  36933. return;
  36934. }
  36935. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  36936. return;
  36937. }
  36938. var srcElement = (evt.srcElement || evt.target);
  36939. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  36940. try {
  36941. srcElement.setPointerCapture(evt.pointerId);
  36942. }
  36943. catch (e) {
  36944. //Nothing to do with the error. Execution will continue.
  36945. }
  36946. _this.previousPosition = {
  36947. x: evt.clientX,
  36948. y: evt.clientY
  36949. };
  36950. if (!noPreventDefault) {
  36951. evt.preventDefault();
  36952. element.focus();
  36953. }
  36954. }
  36955. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  36956. try {
  36957. srcElement.releasePointerCapture(evt.pointerId);
  36958. }
  36959. catch (e) {
  36960. //Nothing to do with the error.
  36961. }
  36962. _this.previousPosition = null;
  36963. if (!noPreventDefault) {
  36964. evt.preventDefault();
  36965. }
  36966. }
  36967. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  36968. if (!_this.previousPosition || engine.isPointerLock) {
  36969. return;
  36970. }
  36971. var offsetX = evt.clientX - _this.previousPosition.x;
  36972. var offsetY = evt.clientY - _this.previousPosition.y;
  36973. if (_this.camera.getScene().useRightHandedSystem) {
  36974. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  36975. }
  36976. else {
  36977. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  36978. }
  36979. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  36980. _this.previousPosition = {
  36981. x: evt.clientX,
  36982. y: evt.clientY
  36983. };
  36984. if (!noPreventDefault) {
  36985. evt.preventDefault();
  36986. }
  36987. }
  36988. };
  36989. }
  36990. this._onMouseMove = function (evt) {
  36991. if (!engine.isPointerLock) {
  36992. return;
  36993. }
  36994. if (engine.isInVRExclusivePointerMode) {
  36995. return;
  36996. }
  36997. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  36998. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  36999. if (_this.camera.getScene().useRightHandedSystem) {
  37000. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37001. }
  37002. else {
  37003. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37004. }
  37005. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37006. _this.previousPosition = null;
  37007. if (!noPreventDefault) {
  37008. evt.preventDefault();
  37009. }
  37010. };
  37011. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37012. element.addEventListener("mousemove", this._onMouseMove, false);
  37013. };
  37014. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37015. if (this._observer && element) {
  37016. this.camera.getScene().onPointerObservable.remove(this._observer);
  37017. if (this._onMouseMove) {
  37018. element.removeEventListener("mousemove", this._onMouseMove);
  37019. }
  37020. this._observer = null;
  37021. this._onMouseMove = null;
  37022. this.previousPosition = null;
  37023. }
  37024. };
  37025. FreeCameraMouseInput.prototype.getClassName = function () {
  37026. return "FreeCameraMouseInput";
  37027. };
  37028. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37029. return "mouse";
  37030. };
  37031. __decorate([
  37032. BABYLON.serialize()
  37033. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37034. __decorate([
  37035. BABYLON.serialize()
  37036. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37037. return FreeCameraMouseInput;
  37038. }());
  37039. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37040. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37041. })(BABYLON || (BABYLON = {}));
  37042. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37043. var BABYLON;
  37044. (function (BABYLON) {
  37045. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37046. function FreeCameraKeyboardMoveInput() {
  37047. this._keys = new Array();
  37048. this.keysUp = [38];
  37049. this.keysDown = [40];
  37050. this.keysLeft = [37];
  37051. this.keysRight = [39];
  37052. }
  37053. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37054. var _this = this;
  37055. if (this._onCanvasBlurObserver) {
  37056. return;
  37057. }
  37058. this._scene = this.camera.getScene();
  37059. this._engine = this._scene.getEngine();
  37060. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37061. _this._keys = [];
  37062. });
  37063. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37064. var evt = info.event;
  37065. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37066. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37067. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37068. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37069. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37070. var index = _this._keys.indexOf(evt.keyCode);
  37071. if (index === -1) {
  37072. _this._keys.push(evt.keyCode);
  37073. }
  37074. if (!noPreventDefault) {
  37075. evt.preventDefault();
  37076. }
  37077. }
  37078. }
  37079. else {
  37080. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37081. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37082. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37083. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37084. var index = _this._keys.indexOf(evt.keyCode);
  37085. if (index >= 0) {
  37086. _this._keys.splice(index, 1);
  37087. }
  37088. if (!noPreventDefault) {
  37089. evt.preventDefault();
  37090. }
  37091. }
  37092. }
  37093. });
  37094. };
  37095. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37096. if (this._scene) {
  37097. if (this._onKeyboardObserver) {
  37098. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37099. }
  37100. if (this._onCanvasBlurObserver) {
  37101. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37102. }
  37103. this._onKeyboardObserver = null;
  37104. this._onCanvasBlurObserver = null;
  37105. }
  37106. this._keys = [];
  37107. };
  37108. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37109. if (this._onKeyboardObserver) {
  37110. var camera = this.camera;
  37111. // Keyboard
  37112. for (var index = 0; index < this._keys.length; index++) {
  37113. var keyCode = this._keys[index];
  37114. var speed = camera._computeLocalCameraSpeed();
  37115. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37116. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37117. }
  37118. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37119. camera._localDirection.copyFromFloats(0, 0, speed);
  37120. }
  37121. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37122. camera._localDirection.copyFromFloats(speed, 0, 0);
  37123. }
  37124. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37125. camera._localDirection.copyFromFloats(0, 0, -speed);
  37126. }
  37127. if (camera.getScene().useRightHandedSystem) {
  37128. camera._localDirection.z *= -1;
  37129. }
  37130. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37131. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37132. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37133. }
  37134. }
  37135. };
  37136. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37137. return "FreeCameraKeyboardMoveInput";
  37138. };
  37139. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37140. this._keys = [];
  37141. };
  37142. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37143. return "keyboard";
  37144. };
  37145. __decorate([
  37146. BABYLON.serialize()
  37147. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37148. __decorate([
  37149. BABYLON.serialize()
  37150. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37151. __decorate([
  37152. BABYLON.serialize()
  37153. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37154. __decorate([
  37155. BABYLON.serialize()
  37156. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37157. return FreeCameraKeyboardMoveInput;
  37158. }());
  37159. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37160. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37161. })(BABYLON || (BABYLON = {}));
  37162. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37163. var BABYLON;
  37164. (function (BABYLON) {
  37165. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37166. __extends(FreeCameraInputsManager, _super);
  37167. function FreeCameraInputsManager(camera) {
  37168. return _super.call(this, camera) || this;
  37169. }
  37170. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37171. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37172. return this;
  37173. };
  37174. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37175. if (touchEnabled === void 0) { touchEnabled = true; }
  37176. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37177. return this;
  37178. };
  37179. FreeCameraInputsManager.prototype.addGamepad = function () {
  37180. this.add(new BABYLON.FreeCameraGamepadInput());
  37181. return this;
  37182. };
  37183. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37184. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37185. return this;
  37186. };
  37187. FreeCameraInputsManager.prototype.addTouch = function () {
  37188. this.add(new BABYLON.FreeCameraTouchInput());
  37189. return this;
  37190. };
  37191. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37192. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37193. return this;
  37194. };
  37195. return FreeCameraInputsManager;
  37196. }(BABYLON.CameraInputsManager));
  37197. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37198. })(BABYLON || (BABYLON = {}));
  37199. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37200. var BABYLON;
  37201. (function (BABYLON) {
  37202. var TargetCamera = /** @class */ (function (_super) {
  37203. __extends(TargetCamera, _super);
  37204. function TargetCamera(name, position, scene) {
  37205. var _this = _super.call(this, name, position, scene) || this;
  37206. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37207. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37208. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37209. _this.speed = 2.0;
  37210. _this.noRotationConstraint = false;
  37211. _this.lockedTarget = null;
  37212. _this._currentTarget = BABYLON.Vector3.Zero();
  37213. _this._viewMatrix = BABYLON.Matrix.Zero();
  37214. _this._camMatrix = BABYLON.Matrix.Zero();
  37215. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37216. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37217. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37218. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37219. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37220. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37221. _this._tempMatrix = BABYLON.Matrix.Zero();
  37222. return _this;
  37223. }
  37224. TargetCamera.prototype.getFrontPosition = function (distance) {
  37225. var direction = this.getTarget().subtract(this.position);
  37226. direction.normalize();
  37227. direction.scaleInPlace(distance);
  37228. return this.globalPosition.add(direction);
  37229. };
  37230. TargetCamera.prototype._getLockedTargetPosition = function () {
  37231. if (!this.lockedTarget) {
  37232. return null;
  37233. }
  37234. if (this.lockedTarget.absolutePosition) {
  37235. this.lockedTarget.computeWorldMatrix();
  37236. }
  37237. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37238. };
  37239. TargetCamera.prototype.storeState = function () {
  37240. this._storedPosition = this.position.clone();
  37241. this._storedRotation = this.rotation.clone();
  37242. if (this.rotationQuaternion) {
  37243. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37244. }
  37245. return _super.prototype.storeState.call(this);
  37246. };
  37247. /**
  37248. * Restored camera state. You must call storeState() first
  37249. */
  37250. TargetCamera.prototype._restoreStateValues = function () {
  37251. if (!_super.prototype._restoreStateValues.call(this)) {
  37252. return false;
  37253. }
  37254. this.position = this._storedPosition.clone();
  37255. this.rotation = this._storedRotation.clone();
  37256. if (this.rotationQuaternion) {
  37257. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37258. }
  37259. this.cameraDirection.copyFromFloats(0, 0, 0);
  37260. this.cameraRotation.copyFromFloats(0, 0);
  37261. return true;
  37262. };
  37263. // Cache
  37264. TargetCamera.prototype._initCache = function () {
  37265. _super.prototype._initCache.call(this);
  37266. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37267. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37268. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37269. };
  37270. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37271. if (!ignoreParentClass) {
  37272. _super.prototype._updateCache.call(this);
  37273. }
  37274. var lockedTargetPosition = this._getLockedTargetPosition();
  37275. if (!lockedTargetPosition) {
  37276. this._cache.lockedTarget = null;
  37277. }
  37278. else {
  37279. if (!this._cache.lockedTarget) {
  37280. this._cache.lockedTarget = lockedTargetPosition.clone();
  37281. }
  37282. else {
  37283. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37284. }
  37285. }
  37286. this._cache.rotation.copyFrom(this.rotation);
  37287. if (this.rotationQuaternion)
  37288. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37289. };
  37290. // Synchronized
  37291. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37292. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37293. return false;
  37294. }
  37295. var lockedTargetPosition = this._getLockedTargetPosition();
  37296. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37297. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37298. };
  37299. // Methods
  37300. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37301. var engine = this.getEngine();
  37302. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37303. };
  37304. // Target
  37305. TargetCamera.prototype.setTarget = function (target) {
  37306. this.upVector.normalize();
  37307. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37308. this._camMatrix.invert();
  37309. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37310. var vDir = target.subtract(this.position);
  37311. if (vDir.x >= 0.0) {
  37312. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37313. }
  37314. else {
  37315. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37316. }
  37317. this.rotation.z = 0;
  37318. if (isNaN(this.rotation.x)) {
  37319. this.rotation.x = 0;
  37320. }
  37321. if (isNaN(this.rotation.y)) {
  37322. this.rotation.y = 0;
  37323. }
  37324. if (isNaN(this.rotation.z)) {
  37325. this.rotation.z = 0;
  37326. }
  37327. if (this.rotationQuaternion) {
  37328. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37329. }
  37330. };
  37331. /**
  37332. * Return the current target position of the camera. This value is expressed in local space.
  37333. */
  37334. TargetCamera.prototype.getTarget = function () {
  37335. return this._currentTarget;
  37336. };
  37337. TargetCamera.prototype._decideIfNeedsToMove = function () {
  37338. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37339. };
  37340. TargetCamera.prototype._updatePosition = function () {
  37341. if (this.parent) {
  37342. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  37343. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  37344. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  37345. return;
  37346. }
  37347. this.position.addInPlace(this.cameraDirection);
  37348. };
  37349. TargetCamera.prototype._checkInputs = function () {
  37350. var needToMove = this._decideIfNeedsToMove();
  37351. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  37352. // Move
  37353. if (needToMove) {
  37354. this._updatePosition();
  37355. }
  37356. // Rotate
  37357. if (needToRotate) {
  37358. this.rotation.x += this.cameraRotation.x;
  37359. this.rotation.y += this.cameraRotation.y;
  37360. //rotate, if quaternion is set and rotation was used
  37361. if (this.rotationQuaternion) {
  37362. var len = this.rotation.lengthSquared();
  37363. if (len) {
  37364. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37365. }
  37366. }
  37367. if (!this.noRotationConstraint) {
  37368. var limit = (Math.PI / 2) * 0.95;
  37369. if (this.rotation.x > limit)
  37370. this.rotation.x = limit;
  37371. if (this.rotation.x < -limit)
  37372. this.rotation.x = -limit;
  37373. }
  37374. }
  37375. // Inertia
  37376. if (needToMove) {
  37377. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  37378. this.cameraDirection.x = 0;
  37379. }
  37380. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  37381. this.cameraDirection.y = 0;
  37382. }
  37383. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  37384. this.cameraDirection.z = 0;
  37385. }
  37386. this.cameraDirection.scaleInPlace(this.inertia);
  37387. }
  37388. if (needToRotate) {
  37389. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  37390. this.cameraRotation.x = 0;
  37391. }
  37392. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  37393. this.cameraRotation.y = 0;
  37394. }
  37395. this.cameraRotation.scaleInPlace(this.inertia);
  37396. }
  37397. _super.prototype._checkInputs.call(this);
  37398. };
  37399. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  37400. if (this.rotationQuaternion) {
  37401. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  37402. }
  37403. else {
  37404. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  37405. }
  37406. //update the up vector!
  37407. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  37408. };
  37409. TargetCamera.prototype._getViewMatrix = function () {
  37410. if (!this.lockedTarget) {
  37411. // Compute
  37412. this._updateCameraRotationMatrix();
  37413. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  37414. // Computing target and final matrix
  37415. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  37416. }
  37417. else {
  37418. var targetPosition = this._getLockedTargetPosition();
  37419. if (targetPosition) {
  37420. this._currentTarget.copyFrom(targetPosition);
  37421. }
  37422. }
  37423. if (this.getScene().useRightHandedSystem) {
  37424. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37425. }
  37426. else {
  37427. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37428. }
  37429. return this._viewMatrix;
  37430. };
  37431. /**
  37432. * @override
  37433. * Override Camera.createRigCamera
  37434. */
  37435. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37436. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  37437. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  37438. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  37439. if (!this.rotationQuaternion) {
  37440. this.rotationQuaternion = new BABYLON.Quaternion();
  37441. }
  37442. rigCamera._cameraRigParams = {};
  37443. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  37444. }
  37445. return rigCamera;
  37446. }
  37447. return null;
  37448. };
  37449. /**
  37450. * @override
  37451. * Override Camera._updateRigCameras
  37452. */
  37453. TargetCamera.prototype._updateRigCameras = function () {
  37454. var camLeft = this._rigCameras[0];
  37455. var camRight = this._rigCameras[1];
  37456. switch (this.cameraRigMode) {
  37457. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37458. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37459. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37460. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37461. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  37462. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  37463. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  37464. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  37465. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  37466. camLeft.setTarget(this.getTarget());
  37467. camRight.setTarget(this.getTarget());
  37468. break;
  37469. case BABYLON.Camera.RIG_MODE_VR:
  37470. if (camLeft.rotationQuaternion) {
  37471. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37472. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37473. }
  37474. else {
  37475. camLeft.rotation.copyFrom(this.rotation);
  37476. camRight.rotation.copyFrom(this.rotation);
  37477. }
  37478. camLeft.position.copyFrom(this.position);
  37479. camRight.position.copyFrom(this.position);
  37480. break;
  37481. }
  37482. _super.prototype._updateRigCameras.call(this);
  37483. };
  37484. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  37485. if (!this._rigCamTransformMatrix) {
  37486. this._rigCamTransformMatrix = new BABYLON.Matrix();
  37487. }
  37488. var target = this.getTarget();
  37489. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  37490. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  37491. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  37492. };
  37493. TargetCamera.prototype.getClassName = function () {
  37494. return "TargetCamera";
  37495. };
  37496. __decorate([
  37497. BABYLON.serializeAsVector3()
  37498. ], TargetCamera.prototype, "rotation", void 0);
  37499. __decorate([
  37500. BABYLON.serialize()
  37501. ], TargetCamera.prototype, "speed", void 0);
  37502. __decorate([
  37503. BABYLON.serializeAsMeshReference("lockedTargetId")
  37504. ], TargetCamera.prototype, "lockedTarget", void 0);
  37505. return TargetCamera;
  37506. }(BABYLON.Camera));
  37507. BABYLON.TargetCamera = TargetCamera;
  37508. })(BABYLON || (BABYLON = {}));
  37509. //# sourceMappingURL=babylon.targetCamera.js.map
  37510. var BABYLON;
  37511. (function (BABYLON) {
  37512. var FreeCamera = /** @class */ (function (_super) {
  37513. __extends(FreeCamera, _super);
  37514. function FreeCamera(name, position, scene) {
  37515. var _this = _super.call(this, name, position, scene) || this;
  37516. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  37517. _this.checkCollisions = false;
  37518. _this.applyGravity = false;
  37519. _this._needMoveForGravity = false;
  37520. _this._oldPosition = BABYLON.Vector3.Zero();
  37521. _this._diffPosition = BABYLON.Vector3.Zero();
  37522. _this._newPosition = BABYLON.Vector3.Zero();
  37523. // Collisions
  37524. _this._collisionMask = -1;
  37525. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37526. if (collidedMesh === void 0) { collidedMesh = null; }
  37527. //TODO move this to the collision coordinator!
  37528. if (_this.getScene().workerCollisions)
  37529. newPosition.multiplyInPlace(_this._collider.radius);
  37530. var updatePosition = function (newPos) {
  37531. _this._newPosition.copyFrom(newPos);
  37532. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  37533. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  37534. _this.position.addInPlace(_this._diffPosition);
  37535. if (_this.onCollide && collidedMesh) {
  37536. _this.onCollide(collidedMesh);
  37537. }
  37538. }
  37539. };
  37540. updatePosition(newPosition);
  37541. };
  37542. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  37543. _this.inputs.addKeyboard().addMouse();
  37544. return _this;
  37545. }
  37546. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  37547. //-- begin properties for backward compatibility for inputs
  37548. get: function () {
  37549. var mouse = this.inputs.attached["mouse"];
  37550. if (mouse)
  37551. return mouse.angularSensibility;
  37552. return 0;
  37553. },
  37554. set: function (value) {
  37555. var mouse = this.inputs.attached["mouse"];
  37556. if (mouse)
  37557. mouse.angularSensibility = value;
  37558. },
  37559. enumerable: true,
  37560. configurable: true
  37561. });
  37562. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37563. get: function () {
  37564. var keyboard = this.inputs.attached["keyboard"];
  37565. if (keyboard)
  37566. return keyboard.keysUp;
  37567. return [];
  37568. },
  37569. set: function (value) {
  37570. var keyboard = this.inputs.attached["keyboard"];
  37571. if (keyboard)
  37572. keyboard.keysUp = value;
  37573. },
  37574. enumerable: true,
  37575. configurable: true
  37576. });
  37577. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37578. get: function () {
  37579. var keyboard = this.inputs.attached["keyboard"];
  37580. if (keyboard)
  37581. return keyboard.keysDown;
  37582. return [];
  37583. },
  37584. set: function (value) {
  37585. var keyboard = this.inputs.attached["keyboard"];
  37586. if (keyboard)
  37587. keyboard.keysDown = value;
  37588. },
  37589. enumerable: true,
  37590. configurable: true
  37591. });
  37592. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37593. get: function () {
  37594. var keyboard = this.inputs.attached["keyboard"];
  37595. if (keyboard)
  37596. return keyboard.keysLeft;
  37597. return [];
  37598. },
  37599. set: function (value) {
  37600. var keyboard = this.inputs.attached["keyboard"];
  37601. if (keyboard)
  37602. keyboard.keysLeft = value;
  37603. },
  37604. enumerable: true,
  37605. configurable: true
  37606. });
  37607. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37608. get: function () {
  37609. var keyboard = this.inputs.attached["keyboard"];
  37610. if (keyboard)
  37611. return keyboard.keysRight;
  37612. return [];
  37613. },
  37614. set: function (value) {
  37615. var keyboard = this.inputs.attached["keyboard"];
  37616. if (keyboard)
  37617. keyboard.keysRight = value;
  37618. },
  37619. enumerable: true,
  37620. configurable: true
  37621. });
  37622. // Controls
  37623. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37624. this.inputs.attachElement(element, noPreventDefault);
  37625. };
  37626. FreeCamera.prototype.detachControl = function (element) {
  37627. this.inputs.detachElement(element);
  37628. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37629. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37630. };
  37631. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37632. get: function () {
  37633. return this._collisionMask;
  37634. },
  37635. set: function (mask) {
  37636. this._collisionMask = !isNaN(mask) ? mask : -1;
  37637. },
  37638. enumerable: true,
  37639. configurable: true
  37640. });
  37641. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37642. var globalPosition;
  37643. if (this.parent) {
  37644. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37645. }
  37646. else {
  37647. globalPosition = this.position;
  37648. }
  37649. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37650. if (!this._collider) {
  37651. this._collider = new BABYLON.Collider();
  37652. }
  37653. this._collider.radius = this.ellipsoid;
  37654. this._collider.collisionMask = this._collisionMask;
  37655. //no need for clone, as long as gravity is not on.
  37656. var actualDisplacement = displacement;
  37657. //add gravity to the direction to prevent the dual-collision checking
  37658. if (this.applyGravity) {
  37659. //this prevents mending with cameraDirection, a global variable of the free camera class.
  37660. actualDisplacement = displacement.add(this.getScene().gravity);
  37661. }
  37662. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37663. };
  37664. FreeCamera.prototype._checkInputs = function () {
  37665. if (!this._localDirection) {
  37666. this._localDirection = BABYLON.Vector3.Zero();
  37667. this._transformedDirection = BABYLON.Vector3.Zero();
  37668. }
  37669. this.inputs.checkInputs();
  37670. _super.prototype._checkInputs.call(this);
  37671. };
  37672. FreeCamera.prototype._decideIfNeedsToMove = function () {
  37673. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37674. };
  37675. FreeCamera.prototype._updatePosition = function () {
  37676. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  37677. this._collideWithWorld(this.cameraDirection);
  37678. }
  37679. else {
  37680. _super.prototype._updatePosition.call(this);
  37681. }
  37682. };
  37683. FreeCamera.prototype.dispose = function () {
  37684. this.inputs.clear();
  37685. _super.prototype.dispose.call(this);
  37686. };
  37687. FreeCamera.prototype.getClassName = function () {
  37688. return "FreeCamera";
  37689. };
  37690. __decorate([
  37691. BABYLON.serializeAsVector3()
  37692. ], FreeCamera.prototype, "ellipsoid", void 0);
  37693. __decorate([
  37694. BABYLON.serialize()
  37695. ], FreeCamera.prototype, "checkCollisions", void 0);
  37696. __decorate([
  37697. BABYLON.serialize()
  37698. ], FreeCamera.prototype, "applyGravity", void 0);
  37699. return FreeCamera;
  37700. }(BABYLON.TargetCamera));
  37701. BABYLON.FreeCamera = FreeCamera;
  37702. })(BABYLON || (BABYLON = {}));
  37703. //# sourceMappingURL=babylon.freeCamera.js.map
  37704. var BABYLON;
  37705. (function (BABYLON) {
  37706. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  37707. function ArcRotateCameraKeyboardMoveInput() {
  37708. this._keys = new Array();
  37709. this.keysUp = [38];
  37710. this.keysDown = [40];
  37711. this.keysLeft = [37];
  37712. this.keysRight = [39];
  37713. this.keysReset = [220];
  37714. this.panningSensibility = 50.0;
  37715. this.zoomingSensibility = 25.0;
  37716. this.useAltToZoom = true;
  37717. }
  37718. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37719. var _this = this;
  37720. if (this._onCanvasBlurObserver) {
  37721. return;
  37722. }
  37723. this._scene = this.camera.getScene();
  37724. this._engine = this._scene.getEngine();
  37725. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37726. _this._keys = [];
  37727. });
  37728. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37729. var evt = info.event;
  37730. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37731. _this._ctrlPressed = evt.ctrlKey;
  37732. _this._altPressed = evt.altKey;
  37733. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37734. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37735. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37736. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37737. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37738. var index = _this._keys.indexOf(evt.keyCode);
  37739. if (index === -1) {
  37740. _this._keys.push(evt.keyCode);
  37741. }
  37742. if (evt.preventDefault) {
  37743. if (!noPreventDefault) {
  37744. evt.preventDefault();
  37745. }
  37746. }
  37747. }
  37748. }
  37749. else {
  37750. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37751. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37752. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37753. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37754. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37755. var index = _this._keys.indexOf(evt.keyCode);
  37756. if (index >= 0) {
  37757. _this._keys.splice(index, 1);
  37758. }
  37759. if (evt.preventDefault) {
  37760. if (!noPreventDefault) {
  37761. evt.preventDefault();
  37762. }
  37763. }
  37764. }
  37765. }
  37766. });
  37767. };
  37768. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37769. if (this._scene) {
  37770. if (this._onKeyboardObserver) {
  37771. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37772. }
  37773. if (this._onCanvasBlurObserver) {
  37774. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37775. }
  37776. this._onKeyboardObserver = null;
  37777. this._onCanvasBlurObserver = null;
  37778. }
  37779. this._keys = [];
  37780. };
  37781. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37782. if (this._onKeyboardObserver) {
  37783. var camera = this.camera;
  37784. for (var index = 0; index < this._keys.length; index++) {
  37785. var keyCode = this._keys[index];
  37786. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37787. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37788. camera.inertialPanningX -= 1 / this.panningSensibility;
  37789. }
  37790. else {
  37791. camera.inertialAlphaOffset -= 0.01;
  37792. }
  37793. }
  37794. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37795. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37796. camera.inertialPanningY += 1 / this.panningSensibility;
  37797. }
  37798. else if (this._altPressed && this.useAltToZoom) {
  37799. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  37800. }
  37801. else {
  37802. camera.inertialBetaOffset -= 0.01;
  37803. }
  37804. }
  37805. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37806. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37807. camera.inertialPanningX += 1 / this.panningSensibility;
  37808. }
  37809. else {
  37810. camera.inertialAlphaOffset += 0.01;
  37811. }
  37812. }
  37813. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37814. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37815. camera.inertialPanningY -= 1 / this.panningSensibility;
  37816. }
  37817. else if (this._altPressed && this.useAltToZoom) {
  37818. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  37819. }
  37820. else {
  37821. camera.inertialBetaOffset += 0.01;
  37822. }
  37823. }
  37824. else if (this.keysReset.indexOf(keyCode) !== -1) {
  37825. camera.restoreState();
  37826. }
  37827. }
  37828. }
  37829. };
  37830. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  37831. return "ArcRotateCameraKeyboardMoveInput";
  37832. };
  37833. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37834. return "keyboard";
  37835. };
  37836. __decorate([
  37837. BABYLON.serialize()
  37838. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37839. __decorate([
  37840. BABYLON.serialize()
  37841. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37842. __decorate([
  37843. BABYLON.serialize()
  37844. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37845. __decorate([
  37846. BABYLON.serialize()
  37847. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37848. __decorate([
  37849. BABYLON.serialize()
  37850. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  37851. __decorate([
  37852. BABYLON.serialize()
  37853. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  37854. __decorate([
  37855. BABYLON.serialize()
  37856. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  37857. __decorate([
  37858. BABYLON.serialize()
  37859. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  37860. return ArcRotateCameraKeyboardMoveInput;
  37861. }());
  37862. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  37863. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  37864. })(BABYLON || (BABYLON = {}));
  37865. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  37866. var BABYLON;
  37867. (function (BABYLON) {
  37868. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  37869. function ArcRotateCameraMouseWheelInput() {
  37870. this.wheelPrecision = 3.0;
  37871. /**
  37872. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  37873. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  37874. */
  37875. this.wheelDeltaPercentage = 0;
  37876. }
  37877. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  37878. var _this = this;
  37879. this._wheel = function (p, s) {
  37880. //sanity check - this should be a PointerWheel event.
  37881. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  37882. return;
  37883. var event = p.event;
  37884. var delta = 0;
  37885. if (event.wheelDelta) {
  37886. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  37887. }
  37888. else if (event.detail) {
  37889. delta = -event.detail / _this.wheelPrecision;
  37890. }
  37891. if (delta)
  37892. _this.camera.inertialRadiusOffset += delta;
  37893. if (event.preventDefault) {
  37894. if (!noPreventDefault) {
  37895. event.preventDefault();
  37896. }
  37897. }
  37898. };
  37899. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  37900. };
  37901. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  37902. if (this._observer && element) {
  37903. this.camera.getScene().onPointerObservable.remove(this._observer);
  37904. this._observer = null;
  37905. this._wheel = null;
  37906. }
  37907. };
  37908. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  37909. return "ArcRotateCameraMouseWheelInput";
  37910. };
  37911. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  37912. return "mousewheel";
  37913. };
  37914. __decorate([
  37915. BABYLON.serialize()
  37916. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  37917. __decorate([
  37918. BABYLON.serialize()
  37919. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  37920. return ArcRotateCameraMouseWheelInput;
  37921. }());
  37922. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  37923. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  37924. })(BABYLON || (BABYLON = {}));
  37925. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  37926. var BABYLON;
  37927. (function (BABYLON) {
  37928. var ArcRotateCameraPointersInput = /** @class */ (function () {
  37929. function ArcRotateCameraPointersInput() {
  37930. this.buttons = [0, 1, 2];
  37931. this.angularSensibilityX = 1000.0;
  37932. this.angularSensibilityY = 1000.0;
  37933. this.pinchPrecision = 12.0;
  37934. /**
  37935. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  37936. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  37937. */
  37938. this.pinchDeltaPercentage = 0;
  37939. this.panningSensibility = 1000.0;
  37940. this.multiTouchPanning = true;
  37941. this.multiTouchPanAndZoom = true;
  37942. this._isPanClick = false;
  37943. this.pinchInwards = true;
  37944. }
  37945. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  37946. var _this = this;
  37947. var engine = this.camera.getEngine();
  37948. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  37949. var pointA = null;
  37950. var pointB = null;
  37951. var previousPinchSquaredDistance = 0;
  37952. var initialDistance = 0;
  37953. var twoFingerActivityCount = 0;
  37954. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  37955. this._pointerInput = function (p, s) {
  37956. var evt = p.event;
  37957. if (engine.isInVRExclusivePointerMode) {
  37958. return;
  37959. }
  37960. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37961. return;
  37962. }
  37963. var srcElement = (evt.srcElement || evt.target);
  37964. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37965. try {
  37966. srcElement.setPointerCapture(evt.pointerId);
  37967. }
  37968. catch (e) {
  37969. //Nothing to do with the error. Execution will continue.
  37970. }
  37971. // Manage panning with pan button click
  37972. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  37973. // manage pointers
  37974. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  37975. if (pointA === null) {
  37976. pointA = cacheSoloPointer;
  37977. }
  37978. else if (pointB === null) {
  37979. pointB = cacheSoloPointer;
  37980. }
  37981. if (!noPreventDefault) {
  37982. evt.preventDefault();
  37983. element.focus();
  37984. }
  37985. }
  37986. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  37987. _this.camera.restoreState();
  37988. }
  37989. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37990. try {
  37991. srcElement.releasePointerCapture(evt.pointerId);
  37992. }
  37993. catch (e) {
  37994. //Nothing to do with the error.
  37995. }
  37996. cacheSoloPointer = null;
  37997. previousPinchSquaredDistance = 0;
  37998. previousMultiTouchPanPosition.isPaning = false;
  37999. previousMultiTouchPanPosition.isPinching = false;
  38000. twoFingerActivityCount = 0;
  38001. initialDistance = 0;
  38002. if (p.event.pointerType !== "touch") {
  38003. pointB = null; // Mouse and pen are mono pointer
  38004. }
  38005. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38006. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38007. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38008. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38009. if (engine.badOS) {
  38010. pointA = pointB = null;
  38011. }
  38012. else {
  38013. //only remove the impacted pointer in case of multitouch allowing on most
  38014. //platforms switching from rotate to zoom and pan seamlessly.
  38015. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38016. pointA = pointB;
  38017. pointB = null;
  38018. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38019. }
  38020. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38021. pointB = null;
  38022. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38023. }
  38024. else {
  38025. pointA = pointB = null;
  38026. }
  38027. }
  38028. if (!noPreventDefault) {
  38029. evt.preventDefault();
  38030. }
  38031. }
  38032. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38033. if (!noPreventDefault) {
  38034. evt.preventDefault();
  38035. }
  38036. // One button down
  38037. if (pointA && pointB === null && cacheSoloPointer) {
  38038. if (_this.panningSensibility !== 0 &&
  38039. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38040. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38041. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38042. }
  38043. else {
  38044. var offsetX = evt.clientX - cacheSoloPointer.x;
  38045. var offsetY = evt.clientY - cacheSoloPointer.y;
  38046. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38047. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38048. }
  38049. cacheSoloPointer.x = evt.clientX;
  38050. cacheSoloPointer.y = evt.clientY;
  38051. }
  38052. else if (pointA && pointB) {
  38053. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38054. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38055. ed.x = evt.clientX;
  38056. ed.y = evt.clientY;
  38057. var direction = _this.pinchInwards ? 1 : -1;
  38058. var distX = pointA.x - pointB.x;
  38059. var distY = pointA.y - pointB.y;
  38060. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38061. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38062. if (previousPinchSquaredDistance === 0) {
  38063. initialDistance = pinchDistance;
  38064. previousPinchSquaredDistance = pinchSquaredDistance;
  38065. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38066. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38067. return;
  38068. }
  38069. if (_this.multiTouchPanAndZoom) {
  38070. if (_this.pinchDeltaPercentage) {
  38071. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38072. }
  38073. else {
  38074. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38075. (_this.pinchPrecision *
  38076. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38077. direction);
  38078. }
  38079. if (_this.panningSensibility !== 0) {
  38080. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38081. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38082. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38083. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38084. previousMultiTouchPanPosition.x = pointersCenterX;
  38085. previousMultiTouchPanPosition.y = pointersCenterY;
  38086. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38087. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38088. }
  38089. }
  38090. else {
  38091. twoFingerActivityCount++;
  38092. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38093. if (_this.pinchDeltaPercentage) {
  38094. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38095. }
  38096. else {
  38097. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38098. (_this.pinchPrecision *
  38099. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38100. direction);
  38101. }
  38102. previousMultiTouchPanPosition.isPaning = false;
  38103. previousMultiTouchPanPosition.isPinching = true;
  38104. }
  38105. else {
  38106. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38107. if (!previousMultiTouchPanPosition.isPaning) {
  38108. previousMultiTouchPanPosition.isPaning = true;
  38109. previousMultiTouchPanPosition.isPinching = false;
  38110. previousMultiTouchPanPosition.x = ed.x;
  38111. previousMultiTouchPanPosition.y = ed.y;
  38112. return;
  38113. }
  38114. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38115. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38116. }
  38117. }
  38118. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38119. previousMultiTouchPanPosition.x = ed.x;
  38120. previousMultiTouchPanPosition.y = ed.y;
  38121. }
  38122. }
  38123. previousPinchSquaredDistance = pinchSquaredDistance;
  38124. }
  38125. }
  38126. };
  38127. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38128. this._onContextMenu = function (evt) {
  38129. evt.preventDefault();
  38130. };
  38131. if (!this.camera._useCtrlForPanning) {
  38132. element.addEventListener("contextmenu", this._onContextMenu, false);
  38133. }
  38134. this._onLostFocus = function () {
  38135. //this._keys = [];
  38136. pointA = pointB = null;
  38137. previousPinchSquaredDistance = 0;
  38138. previousMultiTouchPanPosition.isPaning = false;
  38139. previousMultiTouchPanPosition.isPinching = false;
  38140. twoFingerActivityCount = 0;
  38141. cacheSoloPointer = null;
  38142. initialDistance = 0;
  38143. };
  38144. this._onMouseMove = function (evt) {
  38145. if (!engine.isPointerLock) {
  38146. return;
  38147. }
  38148. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38149. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38150. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38151. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38152. if (!noPreventDefault) {
  38153. evt.preventDefault();
  38154. }
  38155. };
  38156. this._onGestureStart = function (e) {
  38157. if (window.MSGesture === undefined) {
  38158. return;
  38159. }
  38160. if (!_this._MSGestureHandler) {
  38161. _this._MSGestureHandler = new MSGesture();
  38162. _this._MSGestureHandler.target = element;
  38163. }
  38164. _this._MSGestureHandler.addPointer(e.pointerId);
  38165. };
  38166. this._onGesture = function (e) {
  38167. _this.camera.radius *= e.scale;
  38168. if (e.preventDefault) {
  38169. if (!noPreventDefault) {
  38170. e.stopPropagation();
  38171. e.preventDefault();
  38172. }
  38173. }
  38174. };
  38175. element.addEventListener("mousemove", this._onMouseMove, false);
  38176. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38177. element.addEventListener("MSGestureChange", this._onGesture, false);
  38178. BABYLON.Tools.RegisterTopRootEvents([
  38179. { name: "blur", handler: this._onLostFocus }
  38180. ]);
  38181. };
  38182. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38183. if (this._onLostFocus) {
  38184. BABYLON.Tools.UnregisterTopRootEvents([
  38185. { name: "blur", handler: this._onLostFocus }
  38186. ]);
  38187. }
  38188. if (element && this._observer) {
  38189. this.camera.getScene().onPointerObservable.remove(this._observer);
  38190. this._observer = null;
  38191. if (this._onContextMenu) {
  38192. element.removeEventListener("contextmenu", this._onContextMenu);
  38193. }
  38194. if (this._onMouseMove) {
  38195. element.removeEventListener("mousemove", this._onMouseMove);
  38196. }
  38197. if (this._onGestureStart) {
  38198. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38199. }
  38200. if (this._onGesture) {
  38201. element.removeEventListener("MSGestureChange", this._onGesture);
  38202. }
  38203. this._isPanClick = false;
  38204. this.pinchInwards = true;
  38205. this._onMouseMove = null;
  38206. this._onGestureStart = null;
  38207. this._onGesture = null;
  38208. this._MSGestureHandler = null;
  38209. this._onLostFocus = null;
  38210. this._onContextMenu = null;
  38211. }
  38212. };
  38213. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38214. return "ArcRotateCameraPointersInput";
  38215. };
  38216. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38217. return "pointers";
  38218. };
  38219. __decorate([
  38220. BABYLON.serialize()
  38221. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38222. __decorate([
  38223. BABYLON.serialize()
  38224. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38225. __decorate([
  38226. BABYLON.serialize()
  38227. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38228. __decorate([
  38229. BABYLON.serialize()
  38230. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38231. __decorate([
  38232. BABYLON.serialize()
  38233. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38234. __decorate([
  38235. BABYLON.serialize()
  38236. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38237. __decorate([
  38238. BABYLON.serialize()
  38239. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38240. __decorate([
  38241. BABYLON.serialize()
  38242. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38243. return ArcRotateCameraPointersInput;
  38244. }());
  38245. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38246. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38247. })(BABYLON || (BABYLON = {}));
  38248. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38249. var BABYLON;
  38250. (function (BABYLON) {
  38251. var ArcRotateCamera = /** @class */ (function (_super) {
  38252. __extends(ArcRotateCamera, _super);
  38253. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38254. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38255. _this.inertialAlphaOffset = 0;
  38256. _this.inertialBetaOffset = 0;
  38257. _this.inertialRadiusOffset = 0;
  38258. _this.lowerAlphaLimit = null;
  38259. _this.upperAlphaLimit = null;
  38260. _this.lowerBetaLimit = 0.01;
  38261. _this.upperBetaLimit = Math.PI;
  38262. _this.lowerRadiusLimit = null;
  38263. _this.upperRadiusLimit = null;
  38264. _this.inertialPanningX = 0;
  38265. _this.inertialPanningY = 0;
  38266. _this.pinchToPanMaxDistance = 20;
  38267. _this.panningDistanceLimit = null;
  38268. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38269. _this.panningInertia = 0.9;
  38270. //-- end properties for backward compatibility for inputs
  38271. _this.zoomOnFactor = 1;
  38272. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38273. _this.allowUpsideDown = true;
  38274. _this._viewMatrix = new BABYLON.Matrix();
  38275. // Panning
  38276. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38277. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38278. _this.checkCollisions = false;
  38279. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38280. _this._previousPosition = BABYLON.Vector3.Zero();
  38281. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38282. _this._newPosition = BABYLON.Vector3.Zero();
  38283. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38284. if (collidedMesh === void 0) { collidedMesh = null; }
  38285. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38286. newPosition.multiplyInPlace(_this._collider.radius);
  38287. }
  38288. if (!collidedMesh) {
  38289. _this._previousPosition.copyFrom(_this.position);
  38290. }
  38291. else {
  38292. _this.setPosition(newPosition);
  38293. if (_this.onCollide) {
  38294. _this.onCollide(collidedMesh);
  38295. }
  38296. }
  38297. // Recompute because of constraints
  38298. var cosa = Math.cos(_this.alpha);
  38299. var sina = Math.sin(_this.alpha);
  38300. var cosb = Math.cos(_this.beta);
  38301. var sinb = Math.sin(_this.beta);
  38302. if (sinb === 0) {
  38303. sinb = 0.0001;
  38304. }
  38305. var target = _this._getTargetPosition();
  38306. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38307. _this.position.copyFrom(_this._newPosition);
  38308. var up = _this.upVector;
  38309. if (_this.allowUpsideDown && _this.beta < 0) {
  38310. up = up.clone();
  38311. up = up.negate();
  38312. }
  38313. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38314. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38315. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38316. _this._collisionTriggered = false;
  38317. };
  38318. _this._target = BABYLON.Vector3.Zero();
  38319. if (target) {
  38320. _this.setTarget(target);
  38321. }
  38322. _this.alpha = alpha;
  38323. _this.beta = beta;
  38324. _this.radius = radius;
  38325. _this.getViewMatrix();
  38326. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  38327. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  38328. return _this;
  38329. }
  38330. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  38331. get: function () {
  38332. return this._target;
  38333. },
  38334. set: function (value) {
  38335. this.setTarget(value);
  38336. },
  38337. enumerable: true,
  38338. configurable: true
  38339. });
  38340. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  38341. //-- begin properties for backward compatibility for inputs
  38342. get: function () {
  38343. var pointers = this.inputs.attached["pointers"];
  38344. if (pointers)
  38345. return pointers.angularSensibilityX;
  38346. return 0;
  38347. },
  38348. set: function (value) {
  38349. var pointers = this.inputs.attached["pointers"];
  38350. if (pointers) {
  38351. pointers.angularSensibilityX = value;
  38352. }
  38353. },
  38354. enumerable: true,
  38355. configurable: true
  38356. });
  38357. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  38358. get: function () {
  38359. var pointers = this.inputs.attached["pointers"];
  38360. if (pointers)
  38361. return pointers.angularSensibilityY;
  38362. return 0;
  38363. },
  38364. set: function (value) {
  38365. var pointers = this.inputs.attached["pointers"];
  38366. if (pointers) {
  38367. pointers.angularSensibilityY = value;
  38368. }
  38369. },
  38370. enumerable: true,
  38371. configurable: true
  38372. });
  38373. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  38374. get: function () {
  38375. var pointers = this.inputs.attached["pointers"];
  38376. if (pointers)
  38377. return pointers.pinchPrecision;
  38378. return 0;
  38379. },
  38380. set: function (value) {
  38381. var pointers = this.inputs.attached["pointers"];
  38382. if (pointers) {
  38383. pointers.pinchPrecision = value;
  38384. }
  38385. },
  38386. enumerable: true,
  38387. configurable: true
  38388. });
  38389. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  38390. get: function () {
  38391. var pointers = this.inputs.attached["pointers"];
  38392. if (pointers)
  38393. return pointers.pinchDeltaPercentage;
  38394. return 0;
  38395. },
  38396. set: function (value) {
  38397. var pointers = this.inputs.attached["pointers"];
  38398. if (pointers) {
  38399. pointers.pinchDeltaPercentage = value;
  38400. }
  38401. },
  38402. enumerable: true,
  38403. configurable: true
  38404. });
  38405. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  38406. get: function () {
  38407. var pointers = this.inputs.attached["pointers"];
  38408. if (pointers)
  38409. return pointers.panningSensibility;
  38410. return 0;
  38411. },
  38412. set: function (value) {
  38413. var pointers = this.inputs.attached["pointers"];
  38414. if (pointers) {
  38415. pointers.panningSensibility = value;
  38416. }
  38417. },
  38418. enumerable: true,
  38419. configurable: true
  38420. });
  38421. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  38422. get: function () {
  38423. var keyboard = this.inputs.attached["keyboard"];
  38424. if (keyboard)
  38425. return keyboard.keysUp;
  38426. return [];
  38427. },
  38428. set: function (value) {
  38429. var keyboard = this.inputs.attached["keyboard"];
  38430. if (keyboard)
  38431. keyboard.keysUp = value;
  38432. },
  38433. enumerable: true,
  38434. configurable: true
  38435. });
  38436. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  38437. get: function () {
  38438. var keyboard = this.inputs.attached["keyboard"];
  38439. if (keyboard)
  38440. return keyboard.keysDown;
  38441. return [];
  38442. },
  38443. set: function (value) {
  38444. var keyboard = this.inputs.attached["keyboard"];
  38445. if (keyboard)
  38446. keyboard.keysDown = value;
  38447. },
  38448. enumerable: true,
  38449. configurable: true
  38450. });
  38451. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  38452. get: function () {
  38453. var keyboard = this.inputs.attached["keyboard"];
  38454. if (keyboard)
  38455. return keyboard.keysLeft;
  38456. return [];
  38457. },
  38458. set: function (value) {
  38459. var keyboard = this.inputs.attached["keyboard"];
  38460. if (keyboard)
  38461. keyboard.keysLeft = value;
  38462. },
  38463. enumerable: true,
  38464. configurable: true
  38465. });
  38466. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  38467. get: function () {
  38468. var keyboard = this.inputs.attached["keyboard"];
  38469. if (keyboard)
  38470. return keyboard.keysRight;
  38471. return [];
  38472. },
  38473. set: function (value) {
  38474. var keyboard = this.inputs.attached["keyboard"];
  38475. if (keyboard)
  38476. keyboard.keysRight = value;
  38477. },
  38478. enumerable: true,
  38479. configurable: true
  38480. });
  38481. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  38482. get: function () {
  38483. var mousewheel = this.inputs.attached["mousewheel"];
  38484. if (mousewheel)
  38485. return mousewheel.wheelPrecision;
  38486. return 0;
  38487. },
  38488. set: function (value) {
  38489. var mousewheel = this.inputs.attached["mousewheel"];
  38490. if (mousewheel)
  38491. mousewheel.wheelPrecision = value;
  38492. },
  38493. enumerable: true,
  38494. configurable: true
  38495. });
  38496. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  38497. get: function () {
  38498. var mousewheel = this.inputs.attached["mousewheel"];
  38499. if (mousewheel)
  38500. return mousewheel.wheelDeltaPercentage;
  38501. return 0;
  38502. },
  38503. set: function (value) {
  38504. var mousewheel = this.inputs.attached["mousewheel"];
  38505. if (mousewheel)
  38506. mousewheel.wheelDeltaPercentage = value;
  38507. },
  38508. enumerable: true,
  38509. configurable: true
  38510. });
  38511. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  38512. get: function () {
  38513. return this._bouncingBehavior;
  38514. },
  38515. enumerable: true,
  38516. configurable: true
  38517. });
  38518. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  38519. get: function () {
  38520. return this._bouncingBehavior != null;
  38521. },
  38522. set: function (value) {
  38523. if (value === this.useBouncingBehavior) {
  38524. return;
  38525. }
  38526. if (value) {
  38527. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  38528. this.addBehavior(this._bouncingBehavior);
  38529. }
  38530. else if (this._bouncingBehavior) {
  38531. this.removeBehavior(this._bouncingBehavior);
  38532. this._bouncingBehavior = null;
  38533. }
  38534. },
  38535. enumerable: true,
  38536. configurable: true
  38537. });
  38538. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  38539. get: function () {
  38540. return this._framingBehavior;
  38541. },
  38542. enumerable: true,
  38543. configurable: true
  38544. });
  38545. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  38546. get: function () {
  38547. return this._framingBehavior != null;
  38548. },
  38549. set: function (value) {
  38550. if (value === this.useFramingBehavior) {
  38551. return;
  38552. }
  38553. if (value) {
  38554. this._framingBehavior = new BABYLON.FramingBehavior();
  38555. this.addBehavior(this._framingBehavior);
  38556. }
  38557. else if (this._framingBehavior) {
  38558. this.removeBehavior(this._framingBehavior);
  38559. this._framingBehavior = null;
  38560. }
  38561. },
  38562. enumerable: true,
  38563. configurable: true
  38564. });
  38565. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38566. get: function () {
  38567. return this._autoRotationBehavior;
  38568. },
  38569. enumerable: true,
  38570. configurable: true
  38571. });
  38572. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38573. get: function () {
  38574. return this._autoRotationBehavior != null;
  38575. },
  38576. set: function (value) {
  38577. if (value === this.useAutoRotationBehavior) {
  38578. return;
  38579. }
  38580. if (value) {
  38581. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38582. this.addBehavior(this._autoRotationBehavior);
  38583. }
  38584. else if (this._autoRotationBehavior) {
  38585. this.removeBehavior(this._autoRotationBehavior);
  38586. this._autoRotationBehavior = null;
  38587. }
  38588. },
  38589. enumerable: true,
  38590. configurable: true
  38591. });
  38592. // Cache
  38593. ArcRotateCamera.prototype._initCache = function () {
  38594. _super.prototype._initCache.call(this);
  38595. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38596. this._cache.alpha = undefined;
  38597. this._cache.beta = undefined;
  38598. this._cache.radius = undefined;
  38599. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38600. };
  38601. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38602. if (!ignoreParentClass) {
  38603. _super.prototype._updateCache.call(this);
  38604. }
  38605. this._cache._target.copyFrom(this._getTargetPosition());
  38606. this._cache.alpha = this.alpha;
  38607. this._cache.beta = this.beta;
  38608. this._cache.radius = this.radius;
  38609. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38610. };
  38611. ArcRotateCamera.prototype._getTargetPosition = function () {
  38612. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38613. var pos = this._targetHost.getAbsolutePosition();
  38614. if (this._targetBoundingCenter) {
  38615. pos.addToRef(this._targetBoundingCenter, this._target);
  38616. }
  38617. else {
  38618. this._target.copyFrom(pos);
  38619. }
  38620. }
  38621. var lockedTargetPosition = this._getLockedTargetPosition();
  38622. if (lockedTargetPosition) {
  38623. return lockedTargetPosition;
  38624. }
  38625. return this._target;
  38626. };
  38627. ArcRotateCamera.prototype.storeState = function () {
  38628. this._storedAlpha = this.alpha;
  38629. this._storedBeta = this.beta;
  38630. this._storedRadius = this.radius;
  38631. this._storedTarget = this._getTargetPosition().clone();
  38632. return _super.prototype.storeState.call(this);
  38633. };
  38634. /**
  38635. * Restored camera state. You must call storeState() first
  38636. */
  38637. ArcRotateCamera.prototype._restoreStateValues = function () {
  38638. if (!_super.prototype._restoreStateValues.call(this)) {
  38639. return false;
  38640. }
  38641. this.alpha = this._storedAlpha;
  38642. this.beta = this._storedBeta;
  38643. this.radius = this._storedRadius;
  38644. this.setTarget(this._storedTarget.clone());
  38645. this.inertialAlphaOffset = 0;
  38646. this.inertialBetaOffset = 0;
  38647. this.inertialRadiusOffset = 0;
  38648. this.inertialPanningX = 0;
  38649. this.inertialPanningY = 0;
  38650. return true;
  38651. };
  38652. // Synchronized
  38653. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38654. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38655. return false;
  38656. return this._cache._target.equals(this._getTargetPosition())
  38657. && this._cache.alpha === this.alpha
  38658. && this._cache.beta === this.beta
  38659. && this._cache.radius === this.radius
  38660. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  38661. };
  38662. // Methods
  38663. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  38664. var _this = this;
  38665. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  38666. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  38667. this._useCtrlForPanning = useCtrlForPanning;
  38668. this._panningMouseButton = panningMouseButton;
  38669. this.inputs.attachElement(element, noPreventDefault);
  38670. this._reset = function () {
  38671. _this.inertialAlphaOffset = 0;
  38672. _this.inertialBetaOffset = 0;
  38673. _this.inertialRadiusOffset = 0;
  38674. _this.inertialPanningX = 0;
  38675. _this.inertialPanningY = 0;
  38676. };
  38677. };
  38678. ArcRotateCamera.prototype.detachControl = function (element) {
  38679. this.inputs.detachElement(element);
  38680. if (this._reset) {
  38681. this._reset();
  38682. }
  38683. };
  38684. ArcRotateCamera.prototype._checkInputs = function () {
  38685. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  38686. if (this._collisionTriggered) {
  38687. return;
  38688. }
  38689. this.inputs.checkInputs();
  38690. // Inertia
  38691. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  38692. if (this.getScene().useRightHandedSystem) {
  38693. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38694. }
  38695. else {
  38696. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38697. }
  38698. this.beta += this.inertialBetaOffset;
  38699. this.radius -= this.inertialRadiusOffset;
  38700. this.inertialAlphaOffset *= this.inertia;
  38701. this.inertialBetaOffset *= this.inertia;
  38702. this.inertialRadiusOffset *= this.inertia;
  38703. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  38704. this.inertialAlphaOffset = 0;
  38705. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  38706. this.inertialBetaOffset = 0;
  38707. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  38708. this.inertialRadiusOffset = 0;
  38709. }
  38710. // Panning inertia
  38711. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  38712. if (!this._localDirection) {
  38713. this._localDirection = BABYLON.Vector3.Zero();
  38714. this._transformedDirection = BABYLON.Vector3.Zero();
  38715. }
  38716. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  38717. this._localDirection.multiplyInPlace(this.panningAxis);
  38718. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  38719. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  38720. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  38721. if (!this.panningAxis.y) {
  38722. this._transformedDirection.y = 0;
  38723. }
  38724. if (!this._targetHost) {
  38725. if (this.panningDistanceLimit) {
  38726. this._transformedDirection.addInPlace(this._target);
  38727. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  38728. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  38729. this._target.copyFrom(this._transformedDirection);
  38730. }
  38731. }
  38732. else {
  38733. this._target.addInPlace(this._transformedDirection);
  38734. }
  38735. }
  38736. this.inertialPanningX *= this.panningInertia;
  38737. this.inertialPanningY *= this.panningInertia;
  38738. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  38739. this.inertialPanningX = 0;
  38740. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  38741. this.inertialPanningY = 0;
  38742. }
  38743. // Limits
  38744. this._checkLimits();
  38745. _super.prototype._checkInputs.call(this);
  38746. };
  38747. ArcRotateCamera.prototype._checkLimits = function () {
  38748. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  38749. if (this.allowUpsideDown && this.beta > Math.PI) {
  38750. this.beta = this.beta - (2 * Math.PI);
  38751. }
  38752. }
  38753. else {
  38754. if (this.beta < this.lowerBetaLimit) {
  38755. this.beta = this.lowerBetaLimit;
  38756. }
  38757. }
  38758. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  38759. if (this.allowUpsideDown && this.beta < -Math.PI) {
  38760. this.beta = this.beta + (2 * Math.PI);
  38761. }
  38762. }
  38763. else {
  38764. if (this.beta > this.upperBetaLimit) {
  38765. this.beta = this.upperBetaLimit;
  38766. }
  38767. }
  38768. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  38769. this.alpha = this.lowerAlphaLimit;
  38770. }
  38771. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  38772. this.alpha = this.upperAlphaLimit;
  38773. }
  38774. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  38775. this.radius = this.lowerRadiusLimit;
  38776. }
  38777. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  38778. this.radius = this.upperRadiusLimit;
  38779. }
  38780. };
  38781. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  38782. var radiusv3 = this.position.subtract(this._getTargetPosition());
  38783. this.radius = radiusv3.length();
  38784. if (this.radius === 0) {
  38785. this.radius = 0.0001; // Just to avoid division by zero
  38786. }
  38787. // Alpha
  38788. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  38789. if (radiusv3.z < 0) {
  38790. this.alpha = 2 * Math.PI - this.alpha;
  38791. }
  38792. // Beta
  38793. this.beta = Math.acos(radiusv3.y / this.radius);
  38794. this._checkLimits();
  38795. };
  38796. ArcRotateCamera.prototype.setPosition = function (position) {
  38797. if (this.position.equals(position)) {
  38798. return;
  38799. }
  38800. this.position.copyFrom(position);
  38801. this.rebuildAnglesAndRadius();
  38802. };
  38803. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  38804. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  38805. if (allowSamePosition === void 0) { allowSamePosition = false; }
  38806. if (target.getBoundingInfo) {
  38807. if (toBoundingCenter) {
  38808. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  38809. }
  38810. else {
  38811. this._targetBoundingCenter = null;
  38812. }
  38813. this._targetHost = target;
  38814. this._target = this._getTargetPosition();
  38815. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  38816. }
  38817. else {
  38818. var newTarget = target;
  38819. var currentTarget = this._getTargetPosition();
  38820. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  38821. return;
  38822. }
  38823. this._targetHost = null;
  38824. this._target = newTarget;
  38825. this._targetBoundingCenter = null;
  38826. this.onMeshTargetChangedObservable.notifyObservers(null);
  38827. }
  38828. this.rebuildAnglesAndRadius();
  38829. };
  38830. ArcRotateCamera.prototype._getViewMatrix = function () {
  38831. // Compute
  38832. var cosa = Math.cos(this.alpha);
  38833. var sina = Math.sin(this.alpha);
  38834. var cosb = Math.cos(this.beta);
  38835. var sinb = Math.sin(this.beta);
  38836. if (sinb === 0) {
  38837. sinb = 0.0001;
  38838. }
  38839. var target = this._getTargetPosition();
  38840. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  38841. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  38842. if (!this._collider) {
  38843. this._collider = new BABYLON.Collider();
  38844. }
  38845. this._collider.radius = this.collisionRadius;
  38846. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  38847. this._collisionTriggered = true;
  38848. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38849. }
  38850. else {
  38851. this.position.copyFrom(this._newPosition);
  38852. var up = this.upVector;
  38853. if (this.allowUpsideDown && sinb < 0) {
  38854. up = up.clone();
  38855. up = up.negate();
  38856. }
  38857. if (this.getScene().useRightHandedSystem) {
  38858. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  38859. }
  38860. else {
  38861. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  38862. }
  38863. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  38864. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  38865. }
  38866. this._currentTarget = target;
  38867. return this._viewMatrix;
  38868. };
  38869. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  38870. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  38871. meshes = meshes || this.getScene().meshes;
  38872. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  38873. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  38874. this.radius = distance * this.zoomOnFactor;
  38875. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  38876. };
  38877. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  38878. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  38879. var meshesOrMinMaxVector;
  38880. var distance;
  38881. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  38882. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  38883. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  38884. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  38885. }
  38886. else {
  38887. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  38888. meshesOrMinMaxVector = minMaxVectorAndDistance;
  38889. distance = minMaxVectorAndDistance.distance;
  38890. }
  38891. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  38892. if (!doNotUpdateMaxZ) {
  38893. this.maxZ = distance * 2;
  38894. }
  38895. };
  38896. /**
  38897. * @override
  38898. * Override Camera.createRigCamera
  38899. */
  38900. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38901. var alphaShift = 0;
  38902. switch (this.cameraRigMode) {
  38903. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38904. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38905. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38906. case BABYLON.Camera.RIG_MODE_VR:
  38907. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  38908. break;
  38909. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38910. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  38911. break;
  38912. }
  38913. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  38914. rigCam._cameraRigParams = {};
  38915. return rigCam;
  38916. };
  38917. /**
  38918. * @override
  38919. * Override Camera._updateRigCameras
  38920. */
  38921. ArcRotateCamera.prototype._updateRigCameras = function () {
  38922. var camLeft = this._rigCameras[0];
  38923. var camRight = this._rigCameras[1];
  38924. camLeft.beta = camRight.beta = this.beta;
  38925. camLeft.radius = camRight.radius = this.radius;
  38926. switch (this.cameraRigMode) {
  38927. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38928. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38929. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38930. case BABYLON.Camera.RIG_MODE_VR:
  38931. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  38932. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  38933. break;
  38934. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38935. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  38936. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  38937. break;
  38938. }
  38939. _super.prototype._updateRigCameras.call(this);
  38940. };
  38941. ArcRotateCamera.prototype.dispose = function () {
  38942. this.inputs.clear();
  38943. _super.prototype.dispose.call(this);
  38944. };
  38945. ArcRotateCamera.prototype.getClassName = function () {
  38946. return "ArcRotateCamera";
  38947. };
  38948. __decorate([
  38949. BABYLON.serialize()
  38950. ], ArcRotateCamera.prototype, "alpha", void 0);
  38951. __decorate([
  38952. BABYLON.serialize()
  38953. ], ArcRotateCamera.prototype, "beta", void 0);
  38954. __decorate([
  38955. BABYLON.serialize()
  38956. ], ArcRotateCamera.prototype, "radius", void 0);
  38957. __decorate([
  38958. BABYLON.serializeAsVector3("target")
  38959. ], ArcRotateCamera.prototype, "_target", void 0);
  38960. __decorate([
  38961. BABYLON.serialize()
  38962. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  38963. __decorate([
  38964. BABYLON.serialize()
  38965. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  38966. __decorate([
  38967. BABYLON.serialize()
  38968. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  38969. __decorate([
  38970. BABYLON.serialize()
  38971. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  38972. __decorate([
  38973. BABYLON.serialize()
  38974. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  38975. __decorate([
  38976. BABYLON.serialize()
  38977. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  38978. __decorate([
  38979. BABYLON.serialize()
  38980. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  38981. __decorate([
  38982. BABYLON.serialize()
  38983. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  38984. __decorate([
  38985. BABYLON.serialize()
  38986. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  38987. __decorate([
  38988. BABYLON.serialize()
  38989. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  38990. __decorate([
  38991. BABYLON.serialize()
  38992. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  38993. __decorate([
  38994. BABYLON.serialize()
  38995. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  38996. __decorate([
  38997. BABYLON.serialize()
  38998. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  38999. __decorate([
  39000. BABYLON.serializeAsVector3()
  39001. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39002. __decorate([
  39003. BABYLON.serialize()
  39004. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39005. __decorate([
  39006. BABYLON.serialize()
  39007. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39008. __decorate([
  39009. BABYLON.serialize()
  39010. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39011. return ArcRotateCamera;
  39012. }(BABYLON.TargetCamera));
  39013. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39014. })(BABYLON || (BABYLON = {}));
  39015. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39016. var BABYLON;
  39017. (function (BABYLON) {
  39018. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39019. __extends(ArcRotateCameraInputsManager, _super);
  39020. function ArcRotateCameraInputsManager(camera) {
  39021. return _super.call(this, camera) || this;
  39022. }
  39023. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39024. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39025. return this;
  39026. };
  39027. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39028. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39029. return this;
  39030. };
  39031. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39032. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39033. return this;
  39034. };
  39035. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39036. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39037. return this;
  39038. };
  39039. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39040. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39041. return this;
  39042. };
  39043. return ArcRotateCameraInputsManager;
  39044. }(BABYLON.CameraInputsManager));
  39045. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39046. })(BABYLON || (BABYLON = {}));
  39047. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39048. var BABYLON;
  39049. (function (BABYLON) {
  39050. var HemisphericLight = /** @class */ (function (_super) {
  39051. __extends(HemisphericLight, _super);
  39052. /**
  39053. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39054. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39055. * The HemisphericLight can't cast shadows.
  39056. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39057. */
  39058. function HemisphericLight(name, direction, scene) {
  39059. var _this = _super.call(this, name, scene) || this;
  39060. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39061. _this.direction = direction || BABYLON.Vector3.Up();
  39062. return _this;
  39063. }
  39064. HemisphericLight.prototype._buildUniformLayout = function () {
  39065. this._uniformBuffer.addUniform("vLightData", 4);
  39066. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39067. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39068. this._uniformBuffer.addUniform("vLightGround", 3);
  39069. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39070. this._uniformBuffer.addUniform("depthValues", 2);
  39071. this._uniformBuffer.create();
  39072. };
  39073. /**
  39074. * Returns the string "HemisphericLight".
  39075. */
  39076. HemisphericLight.prototype.getClassName = function () {
  39077. return "HemisphericLight";
  39078. };
  39079. /**
  39080. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39081. * Returns the updated direction.
  39082. */
  39083. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39084. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39085. return this.direction;
  39086. };
  39087. HemisphericLight.prototype.getShadowGenerator = function () {
  39088. return null;
  39089. };
  39090. /**
  39091. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39092. * Returns the HemisphericLight.
  39093. */
  39094. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39095. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39096. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39097. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39098. return this;
  39099. };
  39100. HemisphericLight.prototype._getWorldMatrix = function () {
  39101. if (!this._worldMatrix) {
  39102. this._worldMatrix = BABYLON.Matrix.Identity();
  39103. }
  39104. return this._worldMatrix;
  39105. };
  39106. /**
  39107. * Returns the integer 3.
  39108. */
  39109. HemisphericLight.prototype.getTypeID = function () {
  39110. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39111. };
  39112. __decorate([
  39113. BABYLON.serializeAsColor3()
  39114. ], HemisphericLight.prototype, "groundColor", void 0);
  39115. __decorate([
  39116. BABYLON.serializeAsVector3()
  39117. ], HemisphericLight.prototype, "direction", void 0);
  39118. return HemisphericLight;
  39119. }(BABYLON.Light));
  39120. BABYLON.HemisphericLight = HemisphericLight;
  39121. })(BABYLON || (BABYLON = {}));
  39122. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39123. var BABYLON;
  39124. (function (BABYLON) {
  39125. var ShadowLight = /** @class */ (function (_super) {
  39126. __extends(ShadowLight, _super);
  39127. function ShadowLight() {
  39128. var _this = _super !== null && _super.apply(this, arguments) || this;
  39129. _this._needProjectionMatrixCompute = true;
  39130. return _this;
  39131. }
  39132. Object.defineProperty(ShadowLight.prototype, "direction", {
  39133. get: function () {
  39134. return this._direction;
  39135. },
  39136. set: function (value) {
  39137. this._direction = value;
  39138. },
  39139. enumerable: true,
  39140. configurable: true
  39141. });
  39142. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39143. get: function () {
  39144. return this._shadowMinZ;
  39145. },
  39146. set: function (value) {
  39147. this._shadowMinZ = value;
  39148. this.forceProjectionMatrixCompute();
  39149. },
  39150. enumerable: true,
  39151. configurable: true
  39152. });
  39153. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39154. get: function () {
  39155. return this._shadowMaxZ;
  39156. },
  39157. set: function (value) {
  39158. this._shadowMaxZ = value;
  39159. this.forceProjectionMatrixCompute();
  39160. },
  39161. enumerable: true,
  39162. configurable: true
  39163. });
  39164. /**
  39165. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39166. */
  39167. ShadowLight.prototype.computeTransformedInformation = function () {
  39168. if (this.parent && this.parent.getWorldMatrix) {
  39169. if (!this.transformedPosition) {
  39170. this.transformedPosition = BABYLON.Vector3.Zero();
  39171. }
  39172. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39173. // In case the direction is present.
  39174. if (this.direction) {
  39175. if (!this.transformedDirection) {
  39176. this.transformedDirection = BABYLON.Vector3.Zero();
  39177. }
  39178. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39179. }
  39180. return true;
  39181. }
  39182. return false;
  39183. };
  39184. /**
  39185. * Return the depth scale used for the shadow map.
  39186. */
  39187. ShadowLight.prototype.getDepthScale = function () {
  39188. return 50.0;
  39189. };
  39190. /**
  39191. * Returns the light direction (Vector3) for any passed face index.
  39192. */
  39193. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39194. return this.transformedDirection ? this.transformedDirection : this.direction;
  39195. };
  39196. /**
  39197. * Returns the DirectionalLight absolute position in the World.
  39198. */
  39199. ShadowLight.prototype.getAbsolutePosition = function () {
  39200. return this.transformedPosition ? this.transformedPosition : this.position;
  39201. };
  39202. /**
  39203. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39204. * Returns the updated DirectionalLight direction (Vector3).
  39205. */
  39206. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39207. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39208. return this.direction;
  39209. };
  39210. /**
  39211. * Returns the light rotation (Vector3).
  39212. */
  39213. ShadowLight.prototype.getRotation = function () {
  39214. this.direction.normalize();
  39215. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39216. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39217. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39218. };
  39219. /**
  39220. * Boolean : false by default.
  39221. */
  39222. ShadowLight.prototype.needCube = function () {
  39223. return false;
  39224. };
  39225. /**
  39226. * Specifies wether or not the projection matrix should be recomputed this frame.
  39227. */
  39228. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39229. return this._needProjectionMatrixCompute;
  39230. };
  39231. /**
  39232. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39233. */
  39234. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39235. this._needProjectionMatrixCompute = true;
  39236. };
  39237. /**
  39238. * Get the world matrix of the sahdow lights.
  39239. */
  39240. ShadowLight.prototype._getWorldMatrix = function () {
  39241. if (!this._worldMatrix) {
  39242. this._worldMatrix = BABYLON.Matrix.Identity();
  39243. }
  39244. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39245. return this._worldMatrix;
  39246. };
  39247. /**
  39248. * Gets the minZ used for shadow according to both the scene and the light.
  39249. * @param activeCamera
  39250. */
  39251. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39252. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39253. };
  39254. /**
  39255. * Gets the maxZ used for shadow according to both the scene and the light.
  39256. * @param activeCamera
  39257. */
  39258. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39259. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39260. };
  39261. /**
  39262. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39263. * Returns the light.
  39264. */
  39265. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39266. if (this.customProjectionMatrixBuilder) {
  39267. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39268. }
  39269. else {
  39270. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39271. }
  39272. return this;
  39273. };
  39274. __decorate([
  39275. BABYLON.serializeAsVector3()
  39276. ], ShadowLight.prototype, "position", void 0);
  39277. __decorate([
  39278. BABYLON.serializeAsVector3()
  39279. ], ShadowLight.prototype, "direction", null);
  39280. __decorate([
  39281. BABYLON.serialize()
  39282. ], ShadowLight.prototype, "shadowMinZ", null);
  39283. __decorate([
  39284. BABYLON.serialize()
  39285. ], ShadowLight.prototype, "shadowMaxZ", null);
  39286. return ShadowLight;
  39287. }(BABYLON.Light));
  39288. BABYLON.ShadowLight = ShadowLight;
  39289. })(BABYLON || (BABYLON = {}));
  39290. //# sourceMappingURL=babylon.shadowLight.js.map
  39291. var BABYLON;
  39292. (function (BABYLON) {
  39293. var PointLight = /** @class */ (function (_super) {
  39294. __extends(PointLight, _super);
  39295. /**
  39296. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39297. * A PointLight emits the light in every direction.
  39298. * It can cast shadows.
  39299. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39300. * ```javascript
  39301. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39302. * ```
  39303. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39304. */
  39305. function PointLight(name, position, scene) {
  39306. var _this = _super.call(this, name, scene) || this;
  39307. _this._shadowAngle = Math.PI / 2;
  39308. _this.position = position;
  39309. return _this;
  39310. }
  39311. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39312. /**
  39313. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39314. * This specifies what angle the shadow will use to be created.
  39315. *
  39316. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39317. */
  39318. get: function () {
  39319. return this._shadowAngle;
  39320. },
  39321. /**
  39322. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39323. * This specifies what angle the shadow will use to be created.
  39324. *
  39325. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39326. */
  39327. set: function (value) {
  39328. this._shadowAngle = value;
  39329. this.forceProjectionMatrixCompute();
  39330. },
  39331. enumerable: true,
  39332. configurable: true
  39333. });
  39334. Object.defineProperty(PointLight.prototype, "direction", {
  39335. get: function () {
  39336. return this._direction;
  39337. },
  39338. /**
  39339. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39340. */
  39341. set: function (value) {
  39342. var previousNeedCube = this.needCube();
  39343. this._direction = value;
  39344. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  39345. this._shadowGenerator.recreateShadowMap();
  39346. }
  39347. },
  39348. enumerable: true,
  39349. configurable: true
  39350. });
  39351. /**
  39352. * Returns the string "PointLight"
  39353. */
  39354. PointLight.prototype.getClassName = function () {
  39355. return "PointLight";
  39356. };
  39357. /**
  39358. * Returns the integer 0.
  39359. */
  39360. PointLight.prototype.getTypeID = function () {
  39361. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  39362. };
  39363. /**
  39364. * Specifies wether or not the shadowmap should be a cube texture.
  39365. */
  39366. PointLight.prototype.needCube = function () {
  39367. return !this.direction;
  39368. };
  39369. /**
  39370. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  39371. */
  39372. PointLight.prototype.getShadowDirection = function (faceIndex) {
  39373. if (this.direction) {
  39374. return _super.prototype.getShadowDirection.call(this, faceIndex);
  39375. }
  39376. else {
  39377. switch (faceIndex) {
  39378. case 0:
  39379. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  39380. case 1:
  39381. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  39382. case 2:
  39383. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  39384. case 3:
  39385. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  39386. case 4:
  39387. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  39388. case 5:
  39389. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  39390. }
  39391. }
  39392. return BABYLON.Vector3.Zero();
  39393. };
  39394. /**
  39395. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  39396. * - fov = PI / 2
  39397. * - aspect ratio : 1.0
  39398. * - z-near and far equal to the active camera minZ and maxZ.
  39399. * Returns the PointLight.
  39400. */
  39401. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39402. var activeCamera = this.getScene().activeCamera;
  39403. if (!activeCamera) {
  39404. return;
  39405. }
  39406. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39407. };
  39408. PointLight.prototype._buildUniformLayout = function () {
  39409. this._uniformBuffer.addUniform("vLightData", 4);
  39410. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39411. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39412. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39413. this._uniformBuffer.addUniform("depthValues", 2);
  39414. this._uniformBuffer.create();
  39415. };
  39416. /**
  39417. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  39418. * Returns the PointLight.
  39419. */
  39420. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  39421. if (this.computeTransformedInformation()) {
  39422. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  39423. return this;
  39424. }
  39425. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  39426. return this;
  39427. };
  39428. __decorate([
  39429. BABYLON.serialize()
  39430. ], PointLight.prototype, "shadowAngle", null);
  39431. return PointLight;
  39432. }(BABYLON.ShadowLight));
  39433. BABYLON.PointLight = PointLight;
  39434. })(BABYLON || (BABYLON = {}));
  39435. //# sourceMappingURL=babylon.pointLight.js.map
  39436. var BABYLON;
  39437. (function (BABYLON) {
  39438. var DirectionalLight = /** @class */ (function (_super) {
  39439. __extends(DirectionalLight, _super);
  39440. /**
  39441. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  39442. * The directional light is emitted from everywhere in the given direction.
  39443. * It can cast shawdows.
  39444. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39445. */
  39446. function DirectionalLight(name, direction, scene) {
  39447. var _this = _super.call(this, name, scene) || this;
  39448. _this._shadowFrustumSize = 0;
  39449. _this._shadowOrthoScale = 0.5;
  39450. _this.autoUpdateExtends = true;
  39451. // Cache
  39452. _this._orthoLeft = Number.MAX_VALUE;
  39453. _this._orthoRight = Number.MIN_VALUE;
  39454. _this._orthoTop = Number.MIN_VALUE;
  39455. _this._orthoBottom = Number.MAX_VALUE;
  39456. _this.position = direction.scale(-1.0);
  39457. _this.direction = direction;
  39458. return _this;
  39459. }
  39460. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  39461. /**
  39462. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  39463. */
  39464. get: function () {
  39465. return this._shadowFrustumSize;
  39466. },
  39467. /**
  39468. * Specifies a fix frustum size for the shadow generation.
  39469. */
  39470. set: function (value) {
  39471. this._shadowFrustumSize = value;
  39472. this.forceProjectionMatrixCompute();
  39473. },
  39474. enumerable: true,
  39475. configurable: true
  39476. });
  39477. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  39478. get: function () {
  39479. return this._shadowOrthoScale;
  39480. },
  39481. set: function (value) {
  39482. this._shadowOrthoScale = value;
  39483. this.forceProjectionMatrixCompute();
  39484. },
  39485. enumerable: true,
  39486. configurable: true
  39487. });
  39488. /**
  39489. * Returns the string "DirectionalLight".
  39490. */
  39491. DirectionalLight.prototype.getClassName = function () {
  39492. return "DirectionalLight";
  39493. };
  39494. /**
  39495. * Returns the integer 1.
  39496. */
  39497. DirectionalLight.prototype.getTypeID = function () {
  39498. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  39499. };
  39500. /**
  39501. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  39502. * Returns the DirectionalLight Shadow projection matrix.
  39503. */
  39504. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39505. if (this.shadowFrustumSize > 0) {
  39506. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  39507. }
  39508. else {
  39509. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39510. }
  39511. };
  39512. /**
  39513. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  39514. * Returns the DirectionalLight Shadow projection matrix.
  39515. */
  39516. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  39517. var activeCamera = this.getScene().activeCamera;
  39518. if (!activeCamera) {
  39519. return;
  39520. }
  39521. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39522. };
  39523. /**
  39524. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  39525. * Returns the DirectionalLight Shadow projection matrix.
  39526. */
  39527. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39528. var activeCamera = this.getScene().activeCamera;
  39529. if (!activeCamera) {
  39530. return;
  39531. }
  39532. // Check extends
  39533. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  39534. var tempVector3 = BABYLON.Vector3.Zero();
  39535. this._orthoLeft = Number.MAX_VALUE;
  39536. this._orthoRight = Number.MIN_VALUE;
  39537. this._orthoTop = Number.MIN_VALUE;
  39538. this._orthoBottom = Number.MAX_VALUE;
  39539. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  39540. var mesh = renderList[meshIndex];
  39541. if (!mesh) {
  39542. continue;
  39543. }
  39544. var boundingInfo = mesh.getBoundingInfo();
  39545. if (!boundingInfo) {
  39546. continue;
  39547. }
  39548. var boundingBox = boundingInfo.boundingBox;
  39549. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  39550. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  39551. if (tempVector3.x < this._orthoLeft)
  39552. this._orthoLeft = tempVector3.x;
  39553. if (tempVector3.y < this._orthoBottom)
  39554. this._orthoBottom = tempVector3.y;
  39555. if (tempVector3.x > this._orthoRight)
  39556. this._orthoRight = tempVector3.x;
  39557. if (tempVector3.y > this._orthoTop)
  39558. this._orthoTop = tempVector3.y;
  39559. }
  39560. }
  39561. }
  39562. var xOffset = this._orthoRight - this._orthoLeft;
  39563. var yOffset = this._orthoTop - this._orthoBottom;
  39564. 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);
  39565. };
  39566. DirectionalLight.prototype._buildUniformLayout = function () {
  39567. this._uniformBuffer.addUniform("vLightData", 4);
  39568. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39569. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39570. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39571. this._uniformBuffer.addUniform("depthValues", 2);
  39572. this._uniformBuffer.create();
  39573. };
  39574. /**
  39575. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39576. * Returns the DirectionalLight.
  39577. */
  39578. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39579. if (this.computeTransformedInformation()) {
  39580. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39581. return this;
  39582. }
  39583. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39584. return this;
  39585. };
  39586. /**
  39587. * Gets the minZ used for shadow according to both the scene and the light.
  39588. *
  39589. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39590. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39591. * @param activeCamera
  39592. */
  39593. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39594. return 1;
  39595. };
  39596. /**
  39597. * Gets the maxZ used for shadow according to both the scene and the light.
  39598. *
  39599. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39600. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39601. * @param activeCamera
  39602. */
  39603. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39604. return 1;
  39605. };
  39606. __decorate([
  39607. BABYLON.serialize()
  39608. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39609. __decorate([
  39610. BABYLON.serialize()
  39611. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39612. __decorate([
  39613. BABYLON.serialize()
  39614. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39615. return DirectionalLight;
  39616. }(BABYLON.ShadowLight));
  39617. BABYLON.DirectionalLight = DirectionalLight;
  39618. })(BABYLON || (BABYLON = {}));
  39619. //# sourceMappingURL=babylon.directionalLight.js.map
  39620. var BABYLON;
  39621. (function (BABYLON) {
  39622. var SpotLight = /** @class */ (function (_super) {
  39623. __extends(SpotLight, _super);
  39624. /**
  39625. * Creates a SpotLight object in the scene with the passed parameters :
  39626. * - `position` (Vector3) is the initial SpotLight position,
  39627. * - `direction` (Vector3) is the initial SpotLight direction,
  39628. * - `angle` (float, in radians) is the spot light cone angle,
  39629. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39630. * A spot light is a simply light oriented cone.
  39631. * It can cast shadows.
  39632. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39633. */
  39634. function SpotLight(name, position, direction, angle, exponent, scene) {
  39635. var _this = _super.call(this, name, scene) || this;
  39636. _this.position = position;
  39637. _this.direction = direction;
  39638. _this.angle = angle;
  39639. _this.exponent = exponent;
  39640. return _this;
  39641. }
  39642. Object.defineProperty(SpotLight.prototype, "angle", {
  39643. get: function () {
  39644. return this._angle;
  39645. },
  39646. set: function (value) {
  39647. this._angle = value;
  39648. this.forceProjectionMatrixCompute();
  39649. },
  39650. enumerable: true,
  39651. configurable: true
  39652. });
  39653. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39654. get: function () {
  39655. return this._shadowAngleScale;
  39656. },
  39657. /**
  39658. * Allows scaling the angle of the light for shadow generation only.
  39659. */
  39660. set: function (value) {
  39661. this._shadowAngleScale = value;
  39662. this.forceProjectionMatrixCompute();
  39663. },
  39664. enumerable: true,
  39665. configurable: true
  39666. });
  39667. /**
  39668. * Returns the string "SpotLight".
  39669. */
  39670. SpotLight.prototype.getClassName = function () {
  39671. return "SpotLight";
  39672. };
  39673. /**
  39674. * Returns the integer 2.
  39675. */
  39676. SpotLight.prototype.getTypeID = function () {
  39677. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  39678. };
  39679. /**
  39680. * 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.
  39681. * Returns the SpotLight.
  39682. */
  39683. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39684. var activeCamera = this.getScene().activeCamera;
  39685. if (!activeCamera) {
  39686. return;
  39687. }
  39688. this._shadowAngleScale = this._shadowAngleScale || 1;
  39689. var angle = this._shadowAngleScale * this._angle;
  39690. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39691. };
  39692. SpotLight.prototype._buildUniformLayout = function () {
  39693. this._uniformBuffer.addUniform("vLightData", 4);
  39694. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39695. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39696. this._uniformBuffer.addUniform("vLightDirection", 3);
  39697. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39698. this._uniformBuffer.addUniform("depthValues", 2);
  39699. this._uniformBuffer.create();
  39700. };
  39701. /**
  39702. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  39703. * Return the SpotLight.
  39704. */
  39705. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  39706. var normalizeDirection;
  39707. if (this.computeTransformedInformation()) {
  39708. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  39709. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  39710. }
  39711. else {
  39712. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  39713. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39714. }
  39715. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  39716. return this;
  39717. };
  39718. __decorate([
  39719. BABYLON.serialize()
  39720. ], SpotLight.prototype, "angle", null);
  39721. __decorate([
  39722. BABYLON.serialize()
  39723. /**
  39724. * Allows scaling the angle of the light for shadow generation only.
  39725. */
  39726. ], SpotLight.prototype, "shadowAngleScale", null);
  39727. __decorate([
  39728. BABYLON.serialize()
  39729. ], SpotLight.prototype, "exponent", void 0);
  39730. return SpotLight;
  39731. }(BABYLON.ShadowLight));
  39732. BABYLON.SpotLight = SpotLight;
  39733. })(BABYLON || (BABYLON = {}));
  39734. //# sourceMappingURL=babylon.spotLight.js.map
  39735. var BABYLON;
  39736. (function (BABYLON) {
  39737. var AnimationRange = /** @class */ (function () {
  39738. function AnimationRange(name, from, to) {
  39739. this.name = name;
  39740. this.from = from;
  39741. this.to = to;
  39742. }
  39743. AnimationRange.prototype.clone = function () {
  39744. return new AnimationRange(this.name, this.from, this.to);
  39745. };
  39746. return AnimationRange;
  39747. }());
  39748. BABYLON.AnimationRange = AnimationRange;
  39749. /**
  39750. * Composed of a frame, and an action function
  39751. */
  39752. var AnimationEvent = /** @class */ (function () {
  39753. function AnimationEvent(frame, action, onlyOnce) {
  39754. this.frame = frame;
  39755. this.action = action;
  39756. this.onlyOnce = onlyOnce;
  39757. this.isDone = false;
  39758. }
  39759. return AnimationEvent;
  39760. }());
  39761. BABYLON.AnimationEvent = AnimationEvent;
  39762. var PathCursor = /** @class */ (function () {
  39763. function PathCursor(path) {
  39764. this.path = path;
  39765. this._onchange = new Array();
  39766. this.value = 0;
  39767. this.animations = new Array();
  39768. }
  39769. PathCursor.prototype.getPoint = function () {
  39770. var point = this.path.getPointAtLengthPosition(this.value);
  39771. return new BABYLON.Vector3(point.x, 0, point.y);
  39772. };
  39773. PathCursor.prototype.moveAhead = function (step) {
  39774. if (step === void 0) { step = 0.002; }
  39775. this.move(step);
  39776. return this;
  39777. };
  39778. PathCursor.prototype.moveBack = function (step) {
  39779. if (step === void 0) { step = 0.002; }
  39780. this.move(-step);
  39781. return this;
  39782. };
  39783. PathCursor.prototype.move = function (step) {
  39784. if (Math.abs(step) > 1) {
  39785. throw "step size should be less than 1.";
  39786. }
  39787. this.value += step;
  39788. this.ensureLimits();
  39789. this.raiseOnChange();
  39790. return this;
  39791. };
  39792. PathCursor.prototype.ensureLimits = function () {
  39793. while (this.value > 1) {
  39794. this.value -= 1;
  39795. }
  39796. while (this.value < 0) {
  39797. this.value += 1;
  39798. }
  39799. return this;
  39800. };
  39801. // used by animation engine
  39802. PathCursor.prototype.raiseOnChange = function () {
  39803. var _this = this;
  39804. this._onchange.forEach(function (f) { return f(_this); });
  39805. return this;
  39806. };
  39807. PathCursor.prototype.onchange = function (f) {
  39808. this._onchange.push(f);
  39809. return this;
  39810. };
  39811. return PathCursor;
  39812. }());
  39813. BABYLON.PathCursor = PathCursor;
  39814. var Animation = /** @class */ (function () {
  39815. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  39816. this.name = name;
  39817. this.targetProperty = targetProperty;
  39818. this.framePerSecond = framePerSecond;
  39819. this.dataType = dataType;
  39820. this.loopMode = loopMode;
  39821. this.enableBlending = enableBlending;
  39822. this._runtimeAnimations = new Array();
  39823. // The set of event that will be linked to this animation
  39824. this._events = new Array();
  39825. this.blendingSpeed = 0.01;
  39826. this._ranges = {};
  39827. this.targetPropertyPath = targetProperty.split(".");
  39828. this.dataType = dataType;
  39829. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  39830. }
  39831. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  39832. var dataType = undefined;
  39833. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  39834. dataType = Animation.ANIMATIONTYPE_FLOAT;
  39835. }
  39836. else if (from instanceof BABYLON.Quaternion) {
  39837. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  39838. }
  39839. else if (from instanceof BABYLON.Vector3) {
  39840. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  39841. }
  39842. else if (from instanceof BABYLON.Vector2) {
  39843. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  39844. }
  39845. else if (from instanceof BABYLON.Color3) {
  39846. dataType = Animation.ANIMATIONTYPE_COLOR3;
  39847. }
  39848. else if (from instanceof BABYLON.Size) {
  39849. dataType = Animation.ANIMATIONTYPE_SIZE;
  39850. }
  39851. if (dataType == undefined) {
  39852. return null;
  39853. }
  39854. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  39855. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  39856. animation.setKeys(keys);
  39857. if (easingFunction !== undefined) {
  39858. animation.setEasingFunction(easingFunction);
  39859. }
  39860. return animation;
  39861. };
  39862. /**
  39863. * Sets up an animation.
  39864. * @param property the property to animate
  39865. * @param animationType the animation type to apply
  39866. * @param easingFunction the easing function used in the animation
  39867. * @returns The created animation
  39868. */
  39869. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  39870. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39871. animation.setEasingFunction(easingFunction);
  39872. return animation;
  39873. };
  39874. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  39875. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  39876. if (!animation) {
  39877. return null;
  39878. }
  39879. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  39880. };
  39881. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  39882. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  39883. if (!animation) {
  39884. return null;
  39885. }
  39886. node.animations.push(animation);
  39887. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  39888. };
  39889. /**
  39890. * Transition property of the Camera to the target Value.
  39891. * @param property The property to transition
  39892. * @param targetValue The target Value of the property
  39893. * @param host The object where the property to animate belongs
  39894. * @param scene Scene used to run the animation
  39895. * @param frameRate Framerate (in frame/s) to use
  39896. * @param transition The transition type we want to use
  39897. * @param duration The duration of the animation, in milliseconds
  39898. * @param onAnimationEnd Call back trigger at the end of the animation.
  39899. */
  39900. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  39901. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  39902. if (duration <= 0) {
  39903. host[property] = targetValue;
  39904. if (onAnimationEnd) {
  39905. onAnimationEnd();
  39906. }
  39907. return null;
  39908. }
  39909. var endFrame = frameRate * (duration / 1000);
  39910. transition.setKeys([{
  39911. frame: 0,
  39912. value: host[property].clone ? host[property].clone() : host[property]
  39913. },
  39914. {
  39915. frame: endFrame,
  39916. value: targetValue
  39917. }]);
  39918. if (!host.animations) {
  39919. host.animations = [];
  39920. }
  39921. host.animations.push(transition);
  39922. var animation = scene.beginAnimation(host, 0, endFrame, false);
  39923. animation.onAnimationEnd = onAnimationEnd;
  39924. return animation;
  39925. };
  39926. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  39927. /**
  39928. * Return the array of runtime animations currently using this animation
  39929. */
  39930. get: function () {
  39931. return this._runtimeAnimations;
  39932. },
  39933. enumerable: true,
  39934. configurable: true
  39935. });
  39936. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  39937. get: function () {
  39938. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  39939. var runtimeAnimation = _a[_i];
  39940. if (!runtimeAnimation.isStopped) {
  39941. return true;
  39942. }
  39943. }
  39944. return false;
  39945. },
  39946. enumerable: true,
  39947. configurable: true
  39948. });
  39949. // Methods
  39950. /**
  39951. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  39952. */
  39953. Animation.prototype.toString = function (fullDetails) {
  39954. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  39955. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  39956. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  39957. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  39958. if (fullDetails) {
  39959. ret += ", Ranges: {";
  39960. var first = true;
  39961. for (var name in this._ranges) {
  39962. if (first) {
  39963. ret += ", ";
  39964. first = false;
  39965. }
  39966. ret += name;
  39967. }
  39968. ret += "}";
  39969. }
  39970. return ret;
  39971. };
  39972. /**
  39973. * Add an event to this animation.
  39974. */
  39975. Animation.prototype.addEvent = function (event) {
  39976. this._events.push(event);
  39977. };
  39978. /**
  39979. * Remove all events found at the given frame
  39980. * @param frame
  39981. */
  39982. Animation.prototype.removeEvents = function (frame) {
  39983. for (var index = 0; index < this._events.length; index++) {
  39984. if (this._events[index].frame === frame) {
  39985. this._events.splice(index, 1);
  39986. index--;
  39987. }
  39988. }
  39989. };
  39990. Animation.prototype.getEvents = function () {
  39991. return this._events;
  39992. };
  39993. Animation.prototype.createRange = function (name, from, to) {
  39994. // check name not already in use; could happen for bones after serialized
  39995. if (!this._ranges[name]) {
  39996. this._ranges[name] = new AnimationRange(name, from, to);
  39997. }
  39998. };
  39999. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40000. if (deleteFrames === void 0) { deleteFrames = true; }
  40001. var range = this._ranges[name];
  40002. if (!range) {
  40003. return;
  40004. }
  40005. if (deleteFrames) {
  40006. var from = range.from;
  40007. var to = range.to;
  40008. // this loop MUST go high to low for multiple splices to work
  40009. for (var key = this._keys.length - 1; key >= 0; key--) {
  40010. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40011. this._keys.splice(key, 1);
  40012. }
  40013. }
  40014. }
  40015. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40016. };
  40017. Animation.prototype.getRange = function (name) {
  40018. return this._ranges[name];
  40019. };
  40020. Animation.prototype.getKeys = function () {
  40021. return this._keys;
  40022. };
  40023. Animation.prototype.getHighestFrame = function () {
  40024. var ret = 0;
  40025. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40026. if (ret < this._keys[key].frame) {
  40027. ret = this._keys[key].frame;
  40028. }
  40029. }
  40030. return ret;
  40031. };
  40032. Animation.prototype.getEasingFunction = function () {
  40033. return this._easingFunction;
  40034. };
  40035. Animation.prototype.setEasingFunction = function (easingFunction) {
  40036. this._easingFunction = easingFunction;
  40037. };
  40038. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40039. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40040. };
  40041. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40042. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40043. };
  40044. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40045. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40046. };
  40047. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40048. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40049. };
  40050. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40051. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40052. };
  40053. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40054. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40055. };
  40056. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40057. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40058. };
  40059. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40060. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40061. };
  40062. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40063. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40064. };
  40065. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40066. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40067. };
  40068. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40069. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40070. };
  40071. Animation.prototype.clone = function () {
  40072. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40073. clone.enableBlending = this.enableBlending;
  40074. clone.blendingSpeed = this.blendingSpeed;
  40075. if (this._keys) {
  40076. clone.setKeys(this._keys);
  40077. }
  40078. if (this._ranges) {
  40079. clone._ranges = {};
  40080. for (var name in this._ranges) {
  40081. var range = this._ranges[name];
  40082. if (!range) {
  40083. continue;
  40084. }
  40085. clone._ranges[name] = range.clone();
  40086. }
  40087. }
  40088. return clone;
  40089. };
  40090. Animation.prototype.setKeys = function (values) {
  40091. this._keys = values.slice(0);
  40092. };
  40093. Animation.prototype.serialize = function () {
  40094. var serializationObject = {};
  40095. serializationObject.name = this.name;
  40096. serializationObject.property = this.targetProperty;
  40097. serializationObject.framePerSecond = this.framePerSecond;
  40098. serializationObject.dataType = this.dataType;
  40099. serializationObject.loopBehavior = this.loopMode;
  40100. serializationObject.enableBlending = this.enableBlending;
  40101. serializationObject.blendingSpeed = this.blendingSpeed;
  40102. var dataType = this.dataType;
  40103. serializationObject.keys = [];
  40104. var keys = this.getKeys();
  40105. for (var index = 0; index < keys.length; index++) {
  40106. var animationKey = keys[index];
  40107. var key = {};
  40108. key.frame = animationKey.frame;
  40109. switch (dataType) {
  40110. case Animation.ANIMATIONTYPE_FLOAT:
  40111. key.values = [animationKey.value];
  40112. break;
  40113. case Animation.ANIMATIONTYPE_QUATERNION:
  40114. case Animation.ANIMATIONTYPE_MATRIX:
  40115. case Animation.ANIMATIONTYPE_VECTOR3:
  40116. case Animation.ANIMATIONTYPE_COLOR3:
  40117. key.values = animationKey.value.asArray();
  40118. break;
  40119. }
  40120. serializationObject.keys.push(key);
  40121. }
  40122. serializationObject.ranges = [];
  40123. for (var name in this._ranges) {
  40124. var source = this._ranges[name];
  40125. if (!source) {
  40126. continue;
  40127. }
  40128. var range = {};
  40129. range.name = name;
  40130. range.from = source.from;
  40131. range.to = source.to;
  40132. serializationObject.ranges.push(range);
  40133. }
  40134. return serializationObject;
  40135. };
  40136. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40137. get: function () {
  40138. return Animation._ANIMATIONTYPE_FLOAT;
  40139. },
  40140. enumerable: true,
  40141. configurable: true
  40142. });
  40143. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40144. get: function () {
  40145. return Animation._ANIMATIONTYPE_VECTOR3;
  40146. },
  40147. enumerable: true,
  40148. configurable: true
  40149. });
  40150. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40151. get: function () {
  40152. return Animation._ANIMATIONTYPE_VECTOR2;
  40153. },
  40154. enumerable: true,
  40155. configurable: true
  40156. });
  40157. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40158. get: function () {
  40159. return Animation._ANIMATIONTYPE_SIZE;
  40160. },
  40161. enumerable: true,
  40162. configurable: true
  40163. });
  40164. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40165. get: function () {
  40166. return Animation._ANIMATIONTYPE_QUATERNION;
  40167. },
  40168. enumerable: true,
  40169. configurable: true
  40170. });
  40171. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40172. get: function () {
  40173. return Animation._ANIMATIONTYPE_MATRIX;
  40174. },
  40175. enumerable: true,
  40176. configurable: true
  40177. });
  40178. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40179. get: function () {
  40180. return Animation._ANIMATIONTYPE_COLOR3;
  40181. },
  40182. enumerable: true,
  40183. configurable: true
  40184. });
  40185. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40186. get: function () {
  40187. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40188. },
  40189. enumerable: true,
  40190. configurable: true
  40191. });
  40192. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40193. get: function () {
  40194. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40195. },
  40196. enumerable: true,
  40197. configurable: true
  40198. });
  40199. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40200. get: function () {
  40201. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40202. },
  40203. enumerable: true,
  40204. configurable: true
  40205. });
  40206. Animation.Parse = function (parsedAnimation) {
  40207. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40208. var dataType = parsedAnimation.dataType;
  40209. var keys = [];
  40210. var data;
  40211. var index;
  40212. if (parsedAnimation.enableBlending) {
  40213. animation.enableBlending = parsedAnimation.enableBlending;
  40214. }
  40215. if (parsedAnimation.blendingSpeed) {
  40216. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40217. }
  40218. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40219. var key = parsedAnimation.keys[index];
  40220. var inTangent;
  40221. var outTangent;
  40222. switch (dataType) {
  40223. case Animation.ANIMATIONTYPE_FLOAT:
  40224. data = key.values[0];
  40225. if (key.values.length >= 1) {
  40226. inTangent = key.values[1];
  40227. }
  40228. if (key.values.length >= 2) {
  40229. outTangent = key.values[2];
  40230. }
  40231. break;
  40232. case Animation.ANIMATIONTYPE_QUATERNION:
  40233. data = BABYLON.Quaternion.FromArray(key.values);
  40234. if (key.values.length >= 8) {
  40235. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40236. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40237. inTangent = _inTangent;
  40238. }
  40239. }
  40240. if (key.values.length >= 12) {
  40241. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40242. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40243. outTangent = _outTangent;
  40244. }
  40245. }
  40246. break;
  40247. case Animation.ANIMATIONTYPE_MATRIX:
  40248. data = BABYLON.Matrix.FromArray(key.values);
  40249. break;
  40250. case Animation.ANIMATIONTYPE_COLOR3:
  40251. data = BABYLON.Color3.FromArray(key.values);
  40252. break;
  40253. case Animation.ANIMATIONTYPE_VECTOR3:
  40254. default:
  40255. data = BABYLON.Vector3.FromArray(key.values);
  40256. break;
  40257. }
  40258. var keyData = {};
  40259. keyData.frame = key.frame;
  40260. keyData.value = data;
  40261. if (inTangent != undefined) {
  40262. keyData.inTangent = inTangent;
  40263. }
  40264. if (outTangent != undefined) {
  40265. keyData.outTangent = outTangent;
  40266. }
  40267. keys.push(keyData);
  40268. }
  40269. animation.setKeys(keys);
  40270. if (parsedAnimation.ranges) {
  40271. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40272. data = parsedAnimation.ranges[index];
  40273. animation.createRange(data.name, data.from, data.to);
  40274. }
  40275. }
  40276. return animation;
  40277. };
  40278. Animation.AppendSerializedAnimations = function (source, destination) {
  40279. if (source.animations) {
  40280. destination.animations = [];
  40281. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40282. var animation = source.animations[animationIndex];
  40283. destination.animations.push(animation.serialize());
  40284. }
  40285. }
  40286. };
  40287. Animation.AllowMatricesInterpolation = false;
  40288. // Statics
  40289. Animation._ANIMATIONTYPE_FLOAT = 0;
  40290. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40291. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40292. Animation._ANIMATIONTYPE_MATRIX = 3;
  40293. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40294. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40295. Animation._ANIMATIONTYPE_SIZE = 6;
  40296. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40297. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40298. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40299. return Animation;
  40300. }());
  40301. BABYLON.Animation = Animation;
  40302. })(BABYLON || (BABYLON = {}));
  40303. //# sourceMappingURL=babylon.animation.js.map
  40304. var BABYLON;
  40305. (function (BABYLON) {
  40306. var RuntimeAnimation = /** @class */ (function () {
  40307. function RuntimeAnimation(target, animation) {
  40308. this._offsetsCache = {};
  40309. this._highLimitsCache = {};
  40310. this._stopped = false;
  40311. this._blendingFactor = 0;
  40312. this._ratioOffset = 0;
  40313. this._animation = animation;
  40314. this._target = target;
  40315. animation._runtimeAnimations.push(this);
  40316. }
  40317. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40318. get: function () {
  40319. return this._animation;
  40320. },
  40321. enumerable: true,
  40322. configurable: true
  40323. });
  40324. RuntimeAnimation.prototype.reset = function () {
  40325. this._offsetsCache = {};
  40326. this._highLimitsCache = {};
  40327. this.currentFrame = 0;
  40328. this._blendingFactor = 0;
  40329. this._originalBlendValue = null;
  40330. };
  40331. RuntimeAnimation.prototype.isStopped = function () {
  40332. return this._stopped;
  40333. };
  40334. RuntimeAnimation.prototype.dispose = function () {
  40335. var index = this._animation.runtimeAnimations.indexOf(this);
  40336. if (index > -1) {
  40337. this._animation.runtimeAnimations.splice(index, 1);
  40338. }
  40339. };
  40340. RuntimeAnimation.prototype._getKeyValue = function (value) {
  40341. if (typeof value === "function") {
  40342. return value();
  40343. }
  40344. return value;
  40345. };
  40346. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  40347. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  40348. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  40349. }
  40350. this.currentFrame = currentFrame;
  40351. var keys = this._animation.getKeys();
  40352. // Try to get a hash to find the right key
  40353. 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));
  40354. if (keys[startKeyIndex].frame >= currentFrame) {
  40355. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  40356. startKeyIndex--;
  40357. }
  40358. }
  40359. for (var key = startKeyIndex; key < keys.length; key++) {
  40360. var endKey = keys[key + 1];
  40361. if (endKey.frame >= currentFrame) {
  40362. var startKey = keys[key];
  40363. var startValue = this._getKeyValue(startKey.value);
  40364. var endValue = this._getKeyValue(endKey.value);
  40365. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  40366. var frameDelta = endKey.frame - startKey.frame;
  40367. // gradient : percent of currentFrame between the frame inf and the frame sup
  40368. var gradient = (currentFrame - startKey.frame) / frameDelta;
  40369. // check for easingFunction and correction of gradient
  40370. var easingFunction = this._animation.getEasingFunction();
  40371. if (easingFunction != null) {
  40372. gradient = easingFunction.ease(gradient);
  40373. }
  40374. switch (this._animation.dataType) {
  40375. // Float
  40376. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40377. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  40378. switch (loopMode) {
  40379. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40380. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40381. return floatValue;
  40382. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40383. return offsetValue * repeatCount + floatValue;
  40384. }
  40385. break;
  40386. // Quaternion
  40387. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40388. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  40389. switch (loopMode) {
  40390. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40391. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40392. return quatValue;
  40393. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40394. return quatValue.add(offsetValue.scale(repeatCount));
  40395. }
  40396. return quatValue;
  40397. // Vector3
  40398. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40399. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  40400. switch (loopMode) {
  40401. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40402. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40403. return vec3Value;
  40404. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40405. return vec3Value.add(offsetValue.scale(repeatCount));
  40406. }
  40407. // Vector2
  40408. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40409. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  40410. switch (loopMode) {
  40411. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40412. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40413. return vec2Value;
  40414. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40415. return vec2Value.add(offsetValue.scale(repeatCount));
  40416. }
  40417. // Size
  40418. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40419. switch (loopMode) {
  40420. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40421. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40422. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  40423. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40424. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40425. }
  40426. // Color3
  40427. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40428. switch (loopMode) {
  40429. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40430. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40431. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  40432. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40433. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40434. }
  40435. // Matrix
  40436. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  40437. switch (loopMode) {
  40438. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40439. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40440. if (BABYLON.Animation.AllowMatricesInterpolation) {
  40441. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  40442. }
  40443. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40444. return startValue;
  40445. }
  40446. default:
  40447. break;
  40448. }
  40449. break;
  40450. }
  40451. }
  40452. return this._getKeyValue(keys[keys.length - 1].value);
  40453. };
  40454. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  40455. if (blend === void 0) { blend = false; }
  40456. // Set value
  40457. var path;
  40458. var destination;
  40459. var targetPropertyPath = this._animation.targetPropertyPath;
  40460. if (targetPropertyPath.length > 1) {
  40461. var property = this._target[targetPropertyPath[0]];
  40462. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  40463. property = property[targetPropertyPath[index]];
  40464. }
  40465. path = targetPropertyPath[targetPropertyPath.length - 1];
  40466. destination = property;
  40467. }
  40468. else {
  40469. path = targetPropertyPath[0];
  40470. destination = this._target;
  40471. }
  40472. // Blending
  40473. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  40474. if (!this._originalBlendValue) {
  40475. if (destination[path].clone) {
  40476. this._originalBlendValue = destination[path].clone();
  40477. }
  40478. else {
  40479. this._originalBlendValue = destination[path];
  40480. }
  40481. }
  40482. if (this._originalBlendValue.prototype) {
  40483. if (this._originalBlendValue.prototype.Lerp) {
  40484. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  40485. }
  40486. else {
  40487. destination[path] = currentValue;
  40488. }
  40489. }
  40490. else if (this._originalBlendValue.m) {
  40491. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  40492. }
  40493. else {
  40494. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  40495. }
  40496. this._blendingFactor += this._animation.blendingSpeed;
  40497. }
  40498. else {
  40499. destination[path] = currentValue;
  40500. }
  40501. if (this._target.markAsDirty) {
  40502. this._target.markAsDirty(this._animation.targetProperty);
  40503. }
  40504. };
  40505. RuntimeAnimation.prototype.goToFrame = function (frame) {
  40506. var keys = this._animation.getKeys();
  40507. if (frame < keys[0].frame) {
  40508. frame = keys[0].frame;
  40509. }
  40510. else if (frame > keys[keys.length - 1].frame) {
  40511. frame = keys[keys.length - 1].frame;
  40512. }
  40513. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  40514. this.setValue(currentValue);
  40515. };
  40516. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  40517. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  40518. this._ratioOffset = this._previousRatio - newRatio;
  40519. };
  40520. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  40521. if (blend === void 0) { blend = false; }
  40522. var targetPropertyPath = this._animation.targetPropertyPath;
  40523. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  40524. this._stopped = true;
  40525. return false;
  40526. }
  40527. var returnValue = true;
  40528. var keys = this._animation.getKeys();
  40529. // Adding a start key at frame 0 if missing
  40530. if (keys[0].frame !== 0) {
  40531. var newKey = { frame: 0, value: keys[0].value };
  40532. keys.splice(0, 0, newKey);
  40533. }
  40534. // Check limits
  40535. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  40536. from = keys[0].frame;
  40537. }
  40538. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  40539. to = keys[keys.length - 1].frame;
  40540. }
  40541. //to and from cannot be the same key
  40542. if (from === to) {
  40543. if (from > keys[0].frame) {
  40544. from--;
  40545. }
  40546. else if (to < keys[keys.length - 1].frame) {
  40547. to++;
  40548. }
  40549. }
  40550. // Compute ratio
  40551. var range = to - from;
  40552. var offsetValue;
  40553. // ratio represents the frame delta between from and to
  40554. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40555. var highLimitValue = 0;
  40556. this._previousDelay = delay;
  40557. this._previousRatio = ratio;
  40558. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40559. returnValue = false;
  40560. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40561. }
  40562. else {
  40563. // Get max value if required
  40564. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40565. var keyOffset = to.toString() + from.toString();
  40566. if (!this._offsetsCache[keyOffset]) {
  40567. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40568. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40569. switch (this._animation.dataType) {
  40570. // Float
  40571. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40572. this._offsetsCache[keyOffset] = toValue - fromValue;
  40573. break;
  40574. // Quaternion
  40575. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40576. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40577. break;
  40578. // Vector3
  40579. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40580. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40581. // Vector2
  40582. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40583. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40584. // Size
  40585. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40586. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40587. // Color3
  40588. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40589. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40590. default:
  40591. break;
  40592. }
  40593. this._highLimitsCache[keyOffset] = toValue;
  40594. }
  40595. highLimitValue = this._highLimitsCache[keyOffset];
  40596. offsetValue = this._offsetsCache[keyOffset];
  40597. }
  40598. }
  40599. if (offsetValue === undefined) {
  40600. switch (this._animation.dataType) {
  40601. // Float
  40602. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40603. offsetValue = 0;
  40604. break;
  40605. // Quaternion
  40606. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40607. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40608. break;
  40609. // Vector3
  40610. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40611. offsetValue = BABYLON.Vector3.Zero();
  40612. break;
  40613. // Vector2
  40614. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40615. offsetValue = BABYLON.Vector2.Zero();
  40616. break;
  40617. // Size
  40618. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40619. offsetValue = BABYLON.Size.Zero();
  40620. break;
  40621. // Color3
  40622. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40623. offsetValue = BABYLON.Color3.Black();
  40624. }
  40625. }
  40626. // Compute value
  40627. var repeatCount = (ratio / range) >> 0;
  40628. var currentFrame = returnValue ? from + ratio % range : to;
  40629. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40630. // Set value
  40631. this.setValue(currentValue);
  40632. // Check events
  40633. var events = this._animation.getEvents();
  40634. for (var index = 0; index < events.length; index++) {
  40635. // Make sure current frame has passed event frame and that event frame is within the current range
  40636. // Also, handle both forward and reverse animations
  40637. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40638. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40639. var event = events[index];
  40640. if (!event.isDone) {
  40641. // If event should be done only once, remove it.
  40642. if (event.onlyOnce) {
  40643. events.splice(index, 1);
  40644. index--;
  40645. }
  40646. event.isDone = true;
  40647. event.action();
  40648. } // Don't do anything if the event has already be done.
  40649. }
  40650. else if (events[index].isDone && !events[index].onlyOnce) {
  40651. // reset event, the animation is looping
  40652. events[index].isDone = false;
  40653. }
  40654. }
  40655. if (!returnValue) {
  40656. this._stopped = true;
  40657. }
  40658. return returnValue;
  40659. };
  40660. return RuntimeAnimation;
  40661. }());
  40662. BABYLON.RuntimeAnimation = RuntimeAnimation;
  40663. })(BABYLON || (BABYLON = {}));
  40664. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  40665. var BABYLON;
  40666. (function (BABYLON) {
  40667. var Animatable = /** @class */ (function () {
  40668. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  40669. if (fromFrame === void 0) { fromFrame = 0; }
  40670. if (toFrame === void 0) { toFrame = 100; }
  40671. if (loopAnimation === void 0) { loopAnimation = false; }
  40672. if (speedRatio === void 0) { speedRatio = 1.0; }
  40673. this.target = target;
  40674. this.fromFrame = fromFrame;
  40675. this.toFrame = toFrame;
  40676. this.loopAnimation = loopAnimation;
  40677. this.onAnimationEnd = onAnimationEnd;
  40678. this._localDelayOffset = null;
  40679. this._pausedDelay = null;
  40680. this._runtimeAnimations = new Array();
  40681. this._paused = false;
  40682. this._speedRatio = 1;
  40683. this.animationStarted = false;
  40684. if (animations) {
  40685. this.appendAnimations(target, animations);
  40686. }
  40687. this._speedRatio = speedRatio;
  40688. this._scene = scene;
  40689. scene._activeAnimatables.push(this);
  40690. }
  40691. Object.defineProperty(Animatable.prototype, "speedRatio", {
  40692. get: function () {
  40693. return this._speedRatio;
  40694. },
  40695. set: function (value) {
  40696. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  40697. var animation = this._runtimeAnimations[index];
  40698. animation._prepareForSpeedRatioChange(value);
  40699. }
  40700. this._speedRatio = value;
  40701. },
  40702. enumerable: true,
  40703. configurable: true
  40704. });
  40705. // Methods
  40706. Animatable.prototype.getAnimations = function () {
  40707. return this._runtimeAnimations;
  40708. };
  40709. Animatable.prototype.appendAnimations = function (target, animations) {
  40710. for (var index = 0; index < animations.length; index++) {
  40711. var animation = animations[index];
  40712. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  40713. }
  40714. };
  40715. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  40716. var runtimeAnimations = this._runtimeAnimations;
  40717. for (var index = 0; index < runtimeAnimations.length; index++) {
  40718. if (runtimeAnimations[index].animation.targetProperty === property) {
  40719. return runtimeAnimations[index].animation;
  40720. }
  40721. }
  40722. return null;
  40723. };
  40724. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  40725. var runtimeAnimations = this._runtimeAnimations;
  40726. for (var index = 0; index < runtimeAnimations.length; index++) {
  40727. if (runtimeAnimations[index].animation.targetProperty === property) {
  40728. return runtimeAnimations[index];
  40729. }
  40730. }
  40731. return null;
  40732. };
  40733. Animatable.prototype.reset = function () {
  40734. var runtimeAnimations = this._runtimeAnimations;
  40735. for (var index = 0; index < runtimeAnimations.length; index++) {
  40736. runtimeAnimations[index].reset();
  40737. }
  40738. this._localDelayOffset = null;
  40739. this._pausedDelay = null;
  40740. };
  40741. Animatable.prototype.enableBlending = function (blendingSpeed) {
  40742. var runtimeAnimations = this._runtimeAnimations;
  40743. for (var index = 0; index < runtimeAnimations.length; index++) {
  40744. runtimeAnimations[index].animation.enableBlending = true;
  40745. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  40746. }
  40747. };
  40748. Animatable.prototype.disableBlending = function () {
  40749. var runtimeAnimations = this._runtimeAnimations;
  40750. for (var index = 0; index < runtimeAnimations.length; index++) {
  40751. runtimeAnimations[index].animation.enableBlending = false;
  40752. }
  40753. };
  40754. Animatable.prototype.goToFrame = function (frame) {
  40755. var runtimeAnimations = this._runtimeAnimations;
  40756. if (runtimeAnimations[0]) {
  40757. var fps = runtimeAnimations[0].animation.framePerSecond;
  40758. var currentFrame = runtimeAnimations[0].currentFrame;
  40759. var adjustTime = frame - currentFrame;
  40760. var delay = adjustTime * 1000 / fps;
  40761. if (this._localDelayOffset === null) {
  40762. this._localDelayOffset = 0;
  40763. }
  40764. this._localDelayOffset -= delay;
  40765. }
  40766. for (var index = 0; index < runtimeAnimations.length; index++) {
  40767. runtimeAnimations[index].goToFrame(frame);
  40768. }
  40769. };
  40770. Animatable.prototype.pause = function () {
  40771. if (this._paused) {
  40772. return;
  40773. }
  40774. this._paused = true;
  40775. };
  40776. Animatable.prototype.restart = function () {
  40777. this._paused = false;
  40778. };
  40779. Animatable.prototype.stop = function (animationName) {
  40780. if (animationName) {
  40781. var idx = this._scene._activeAnimatables.indexOf(this);
  40782. if (idx > -1) {
  40783. var runtimeAnimations = this._runtimeAnimations;
  40784. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  40785. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  40786. continue;
  40787. }
  40788. runtimeAnimations[index].dispose();
  40789. runtimeAnimations.splice(index, 1);
  40790. }
  40791. if (runtimeAnimations.length == 0) {
  40792. this._scene._activeAnimatables.splice(idx, 1);
  40793. if (this.onAnimationEnd) {
  40794. this.onAnimationEnd();
  40795. }
  40796. }
  40797. }
  40798. }
  40799. else {
  40800. var index = this._scene._activeAnimatables.indexOf(this);
  40801. if (index > -1) {
  40802. this._scene._activeAnimatables.splice(index, 1);
  40803. var runtimeAnimations = this._runtimeAnimations;
  40804. for (var index = 0; index < runtimeAnimations.length; index++) {
  40805. runtimeAnimations[index].dispose();
  40806. }
  40807. if (this.onAnimationEnd) {
  40808. this.onAnimationEnd();
  40809. }
  40810. }
  40811. }
  40812. };
  40813. Animatable.prototype._animate = function (delay) {
  40814. if (this._paused) {
  40815. this.animationStarted = false;
  40816. if (this._pausedDelay === null) {
  40817. this._pausedDelay = delay;
  40818. }
  40819. return true;
  40820. }
  40821. if (this._localDelayOffset === null) {
  40822. this._localDelayOffset = delay;
  40823. }
  40824. else if (this._pausedDelay !== null) {
  40825. this._localDelayOffset += delay - this._pausedDelay;
  40826. this._pausedDelay = null;
  40827. }
  40828. // Animating
  40829. var running = false;
  40830. var runtimeAnimations = this._runtimeAnimations;
  40831. var index;
  40832. for (index = 0; index < runtimeAnimations.length; index++) {
  40833. var animation = runtimeAnimations[index];
  40834. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  40835. running = running || isRunning;
  40836. }
  40837. this.animationStarted = running;
  40838. if (!running) {
  40839. // Remove from active animatables
  40840. index = this._scene._activeAnimatables.indexOf(this);
  40841. this._scene._activeAnimatables.splice(index, 1);
  40842. // Dispose all runtime animations
  40843. for (index = 0; index < runtimeAnimations.length; index++) {
  40844. runtimeAnimations[index].dispose();
  40845. }
  40846. }
  40847. if (!running && this.onAnimationEnd) {
  40848. this.onAnimationEnd();
  40849. this.onAnimationEnd = null;
  40850. }
  40851. return running;
  40852. };
  40853. return Animatable;
  40854. }());
  40855. BABYLON.Animatable = Animatable;
  40856. })(BABYLON || (BABYLON = {}));
  40857. //# sourceMappingURL=babylon.animatable.js.map
  40858. var BABYLON;
  40859. (function (BABYLON) {
  40860. var EasingFunction = /** @class */ (function () {
  40861. function EasingFunction() {
  40862. // Properties
  40863. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  40864. }
  40865. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  40866. get: function () {
  40867. return EasingFunction._EASINGMODE_EASEIN;
  40868. },
  40869. enumerable: true,
  40870. configurable: true
  40871. });
  40872. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  40873. get: function () {
  40874. return EasingFunction._EASINGMODE_EASEOUT;
  40875. },
  40876. enumerable: true,
  40877. configurable: true
  40878. });
  40879. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  40880. get: function () {
  40881. return EasingFunction._EASINGMODE_EASEINOUT;
  40882. },
  40883. enumerable: true,
  40884. configurable: true
  40885. });
  40886. EasingFunction.prototype.setEasingMode = function (easingMode) {
  40887. var n = Math.min(Math.max(easingMode, 0), 2);
  40888. this._easingMode = n;
  40889. };
  40890. EasingFunction.prototype.getEasingMode = function () {
  40891. return this._easingMode;
  40892. };
  40893. EasingFunction.prototype.easeInCore = function (gradient) {
  40894. throw new Error('You must implement this method');
  40895. };
  40896. EasingFunction.prototype.ease = function (gradient) {
  40897. switch (this._easingMode) {
  40898. case EasingFunction.EASINGMODE_EASEIN:
  40899. return this.easeInCore(gradient);
  40900. case EasingFunction.EASINGMODE_EASEOUT:
  40901. return (1 - this.easeInCore(1 - gradient));
  40902. }
  40903. if (gradient >= 0.5) {
  40904. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  40905. }
  40906. return (this.easeInCore(gradient * 2) * 0.5);
  40907. };
  40908. //Statics
  40909. EasingFunction._EASINGMODE_EASEIN = 0;
  40910. EasingFunction._EASINGMODE_EASEOUT = 1;
  40911. EasingFunction._EASINGMODE_EASEINOUT = 2;
  40912. return EasingFunction;
  40913. }());
  40914. BABYLON.EasingFunction = EasingFunction;
  40915. var CircleEase = /** @class */ (function (_super) {
  40916. __extends(CircleEase, _super);
  40917. function CircleEase() {
  40918. return _super !== null && _super.apply(this, arguments) || this;
  40919. }
  40920. CircleEase.prototype.easeInCore = function (gradient) {
  40921. gradient = Math.max(0, Math.min(1, gradient));
  40922. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  40923. };
  40924. return CircleEase;
  40925. }(EasingFunction));
  40926. BABYLON.CircleEase = CircleEase;
  40927. var BackEase = /** @class */ (function (_super) {
  40928. __extends(BackEase, _super);
  40929. function BackEase(amplitude) {
  40930. if (amplitude === void 0) { amplitude = 1; }
  40931. var _this = _super.call(this) || this;
  40932. _this.amplitude = amplitude;
  40933. return _this;
  40934. }
  40935. BackEase.prototype.easeInCore = function (gradient) {
  40936. var num = Math.max(0, this.amplitude);
  40937. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  40938. };
  40939. return BackEase;
  40940. }(EasingFunction));
  40941. BABYLON.BackEase = BackEase;
  40942. var BounceEase = /** @class */ (function (_super) {
  40943. __extends(BounceEase, _super);
  40944. function BounceEase(bounces, bounciness) {
  40945. if (bounces === void 0) { bounces = 3; }
  40946. if (bounciness === void 0) { bounciness = 2; }
  40947. var _this = _super.call(this) || this;
  40948. _this.bounces = bounces;
  40949. _this.bounciness = bounciness;
  40950. return _this;
  40951. }
  40952. BounceEase.prototype.easeInCore = function (gradient) {
  40953. var y = Math.max(0.0, this.bounces);
  40954. var bounciness = this.bounciness;
  40955. if (bounciness <= 1.0) {
  40956. bounciness = 1.001;
  40957. }
  40958. var num9 = Math.pow(bounciness, y);
  40959. var num5 = 1.0 - bounciness;
  40960. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  40961. var num15 = gradient * num4;
  40962. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  40963. var num3 = Math.floor(num65);
  40964. var num13 = num3 + 1.0;
  40965. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  40966. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  40967. var num7 = (num8 + num12) * 0.5;
  40968. var num6 = gradient - num7;
  40969. var num2 = num7 - num8;
  40970. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  40971. };
  40972. return BounceEase;
  40973. }(EasingFunction));
  40974. BABYLON.BounceEase = BounceEase;
  40975. var CubicEase = /** @class */ (function (_super) {
  40976. __extends(CubicEase, _super);
  40977. function CubicEase() {
  40978. return _super !== null && _super.apply(this, arguments) || this;
  40979. }
  40980. CubicEase.prototype.easeInCore = function (gradient) {
  40981. return (gradient * gradient * gradient);
  40982. };
  40983. return CubicEase;
  40984. }(EasingFunction));
  40985. BABYLON.CubicEase = CubicEase;
  40986. var ElasticEase = /** @class */ (function (_super) {
  40987. __extends(ElasticEase, _super);
  40988. function ElasticEase(oscillations, springiness) {
  40989. if (oscillations === void 0) { oscillations = 3; }
  40990. if (springiness === void 0) { springiness = 3; }
  40991. var _this = _super.call(this) || this;
  40992. _this.oscillations = oscillations;
  40993. _this.springiness = springiness;
  40994. return _this;
  40995. }
  40996. ElasticEase.prototype.easeInCore = function (gradient) {
  40997. var num2;
  40998. var num3 = Math.max(0.0, this.oscillations);
  40999. var num = Math.max(0.0, this.springiness);
  41000. if (num == 0) {
  41001. num2 = gradient;
  41002. }
  41003. else {
  41004. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41005. }
  41006. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41007. };
  41008. return ElasticEase;
  41009. }(EasingFunction));
  41010. BABYLON.ElasticEase = ElasticEase;
  41011. var ExponentialEase = /** @class */ (function (_super) {
  41012. __extends(ExponentialEase, _super);
  41013. function ExponentialEase(exponent) {
  41014. if (exponent === void 0) { exponent = 2; }
  41015. var _this = _super.call(this) || this;
  41016. _this.exponent = exponent;
  41017. return _this;
  41018. }
  41019. ExponentialEase.prototype.easeInCore = function (gradient) {
  41020. if (this.exponent <= 0) {
  41021. return gradient;
  41022. }
  41023. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41024. };
  41025. return ExponentialEase;
  41026. }(EasingFunction));
  41027. BABYLON.ExponentialEase = ExponentialEase;
  41028. var PowerEase = /** @class */ (function (_super) {
  41029. __extends(PowerEase, _super);
  41030. function PowerEase(power) {
  41031. if (power === void 0) { power = 2; }
  41032. var _this = _super.call(this) || this;
  41033. _this.power = power;
  41034. return _this;
  41035. }
  41036. PowerEase.prototype.easeInCore = function (gradient) {
  41037. var y = Math.max(0.0, this.power);
  41038. return Math.pow(gradient, y);
  41039. };
  41040. return PowerEase;
  41041. }(EasingFunction));
  41042. BABYLON.PowerEase = PowerEase;
  41043. var QuadraticEase = /** @class */ (function (_super) {
  41044. __extends(QuadraticEase, _super);
  41045. function QuadraticEase() {
  41046. return _super !== null && _super.apply(this, arguments) || this;
  41047. }
  41048. QuadraticEase.prototype.easeInCore = function (gradient) {
  41049. return (gradient * gradient);
  41050. };
  41051. return QuadraticEase;
  41052. }(EasingFunction));
  41053. BABYLON.QuadraticEase = QuadraticEase;
  41054. var QuarticEase = /** @class */ (function (_super) {
  41055. __extends(QuarticEase, _super);
  41056. function QuarticEase() {
  41057. return _super !== null && _super.apply(this, arguments) || this;
  41058. }
  41059. QuarticEase.prototype.easeInCore = function (gradient) {
  41060. return (gradient * gradient * gradient * gradient);
  41061. };
  41062. return QuarticEase;
  41063. }(EasingFunction));
  41064. BABYLON.QuarticEase = QuarticEase;
  41065. var QuinticEase = /** @class */ (function (_super) {
  41066. __extends(QuinticEase, _super);
  41067. function QuinticEase() {
  41068. return _super !== null && _super.apply(this, arguments) || this;
  41069. }
  41070. QuinticEase.prototype.easeInCore = function (gradient) {
  41071. return (gradient * gradient * gradient * gradient * gradient);
  41072. };
  41073. return QuinticEase;
  41074. }(EasingFunction));
  41075. BABYLON.QuinticEase = QuinticEase;
  41076. var SineEase = /** @class */ (function (_super) {
  41077. __extends(SineEase, _super);
  41078. function SineEase() {
  41079. return _super !== null && _super.apply(this, arguments) || this;
  41080. }
  41081. SineEase.prototype.easeInCore = function (gradient) {
  41082. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41083. };
  41084. return SineEase;
  41085. }(EasingFunction));
  41086. BABYLON.SineEase = SineEase;
  41087. var BezierCurveEase = /** @class */ (function (_super) {
  41088. __extends(BezierCurveEase, _super);
  41089. function BezierCurveEase(x1, y1, x2, y2) {
  41090. if (x1 === void 0) { x1 = 0; }
  41091. if (y1 === void 0) { y1 = 0; }
  41092. if (x2 === void 0) { x2 = 1; }
  41093. if (y2 === void 0) { y2 = 1; }
  41094. var _this = _super.call(this) || this;
  41095. _this.x1 = x1;
  41096. _this.y1 = y1;
  41097. _this.x2 = x2;
  41098. _this.y2 = y2;
  41099. return _this;
  41100. }
  41101. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41102. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41103. };
  41104. return BezierCurveEase;
  41105. }(EasingFunction));
  41106. BABYLON.BezierCurveEase = BezierCurveEase;
  41107. })(BABYLON || (BABYLON = {}));
  41108. //# sourceMappingURL=babylon.easing.js.map
  41109. var BABYLON;
  41110. (function (BABYLON) {
  41111. var Condition = /** @class */ (function () {
  41112. function Condition(actionManager) {
  41113. this._actionManager = actionManager;
  41114. }
  41115. Condition.prototype.isValid = function () {
  41116. return true;
  41117. };
  41118. Condition.prototype._getProperty = function (propertyPath) {
  41119. return this._actionManager._getProperty(propertyPath);
  41120. };
  41121. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41122. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41123. };
  41124. Condition.prototype.serialize = function () {
  41125. };
  41126. Condition.prototype._serialize = function (serializedCondition) {
  41127. return {
  41128. type: 2,
  41129. children: [],
  41130. name: serializedCondition.name,
  41131. properties: serializedCondition.properties
  41132. };
  41133. };
  41134. return Condition;
  41135. }());
  41136. BABYLON.Condition = Condition;
  41137. var ValueCondition = /** @class */ (function (_super) {
  41138. __extends(ValueCondition, _super);
  41139. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41140. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41141. var _this = _super.call(this, actionManager) || this;
  41142. _this.propertyPath = propertyPath;
  41143. _this.value = value;
  41144. _this.operator = operator;
  41145. _this._target = target;
  41146. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41147. _this._property = _this._getProperty(_this.propertyPath);
  41148. return _this;
  41149. }
  41150. Object.defineProperty(ValueCondition, "IsEqual", {
  41151. get: function () {
  41152. return ValueCondition._IsEqual;
  41153. },
  41154. enumerable: true,
  41155. configurable: true
  41156. });
  41157. Object.defineProperty(ValueCondition, "IsDifferent", {
  41158. get: function () {
  41159. return ValueCondition._IsDifferent;
  41160. },
  41161. enumerable: true,
  41162. configurable: true
  41163. });
  41164. Object.defineProperty(ValueCondition, "IsGreater", {
  41165. get: function () {
  41166. return ValueCondition._IsGreater;
  41167. },
  41168. enumerable: true,
  41169. configurable: true
  41170. });
  41171. Object.defineProperty(ValueCondition, "IsLesser", {
  41172. get: function () {
  41173. return ValueCondition._IsLesser;
  41174. },
  41175. enumerable: true,
  41176. configurable: true
  41177. });
  41178. // Methods
  41179. ValueCondition.prototype.isValid = function () {
  41180. switch (this.operator) {
  41181. case ValueCondition.IsGreater:
  41182. return this._effectiveTarget[this._property] > this.value;
  41183. case ValueCondition.IsLesser:
  41184. return this._effectiveTarget[this._property] < this.value;
  41185. case ValueCondition.IsEqual:
  41186. case ValueCondition.IsDifferent:
  41187. var check;
  41188. if (this.value.equals) {
  41189. check = this.value.equals(this._effectiveTarget[this._property]);
  41190. }
  41191. else {
  41192. check = this.value === this._effectiveTarget[this._property];
  41193. }
  41194. return this.operator === ValueCondition.IsEqual ? check : !check;
  41195. }
  41196. return false;
  41197. };
  41198. ValueCondition.prototype.serialize = function () {
  41199. return this._serialize({
  41200. name: "ValueCondition",
  41201. properties: [
  41202. BABYLON.Action._GetTargetProperty(this._target),
  41203. { name: "propertyPath", value: this.propertyPath },
  41204. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41205. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41206. ]
  41207. });
  41208. };
  41209. ValueCondition.GetOperatorName = function (operator) {
  41210. switch (operator) {
  41211. case ValueCondition._IsEqual: return "IsEqual";
  41212. case ValueCondition._IsDifferent: return "IsDifferent";
  41213. case ValueCondition._IsGreater: return "IsGreater";
  41214. case ValueCondition._IsLesser: return "IsLesser";
  41215. default: return "";
  41216. }
  41217. };
  41218. // Statics
  41219. ValueCondition._IsEqual = 0;
  41220. ValueCondition._IsDifferent = 1;
  41221. ValueCondition._IsGreater = 2;
  41222. ValueCondition._IsLesser = 3;
  41223. return ValueCondition;
  41224. }(Condition));
  41225. BABYLON.ValueCondition = ValueCondition;
  41226. var PredicateCondition = /** @class */ (function (_super) {
  41227. __extends(PredicateCondition, _super);
  41228. function PredicateCondition(actionManager, predicate) {
  41229. var _this = _super.call(this, actionManager) || this;
  41230. _this.predicate = predicate;
  41231. return _this;
  41232. }
  41233. PredicateCondition.prototype.isValid = function () {
  41234. return this.predicate();
  41235. };
  41236. return PredicateCondition;
  41237. }(Condition));
  41238. BABYLON.PredicateCondition = PredicateCondition;
  41239. var StateCondition = /** @class */ (function (_super) {
  41240. __extends(StateCondition, _super);
  41241. function StateCondition(actionManager, target, value) {
  41242. var _this = _super.call(this, actionManager) || this;
  41243. _this.value = value;
  41244. _this._target = target;
  41245. return _this;
  41246. }
  41247. // Methods
  41248. StateCondition.prototype.isValid = function () {
  41249. return this._target.state === this.value;
  41250. };
  41251. StateCondition.prototype.serialize = function () {
  41252. return this._serialize({
  41253. name: "StateCondition",
  41254. properties: [
  41255. BABYLON.Action._GetTargetProperty(this._target),
  41256. { name: "value", value: this.value }
  41257. ]
  41258. });
  41259. };
  41260. return StateCondition;
  41261. }(Condition));
  41262. BABYLON.StateCondition = StateCondition;
  41263. })(BABYLON || (BABYLON = {}));
  41264. //# sourceMappingURL=babylon.condition.js.map
  41265. var BABYLON;
  41266. (function (BABYLON) {
  41267. var Action = /** @class */ (function () {
  41268. function Action(triggerOptions, condition) {
  41269. this.triggerOptions = triggerOptions;
  41270. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41271. if (triggerOptions.parameter) {
  41272. this.trigger = triggerOptions.trigger;
  41273. this._triggerParameter = triggerOptions.parameter;
  41274. }
  41275. else {
  41276. this.trigger = triggerOptions;
  41277. }
  41278. this._nextActiveAction = this;
  41279. this._condition = condition;
  41280. }
  41281. // Methods
  41282. Action.prototype._prepare = function () {
  41283. };
  41284. Action.prototype.getTriggerParameter = function () {
  41285. return this._triggerParameter;
  41286. };
  41287. Action.prototype._executeCurrent = function (evt) {
  41288. if (this._nextActiveAction._condition) {
  41289. var condition = this._nextActiveAction._condition;
  41290. var currentRenderId = this._actionManager.getScene().getRenderId();
  41291. // We cache the current evaluation for the current frame
  41292. if (condition._evaluationId === currentRenderId) {
  41293. if (!condition._currentResult) {
  41294. return;
  41295. }
  41296. }
  41297. else {
  41298. condition._evaluationId = currentRenderId;
  41299. if (!condition.isValid()) {
  41300. condition._currentResult = false;
  41301. return;
  41302. }
  41303. condition._currentResult = true;
  41304. }
  41305. }
  41306. this.onBeforeExecuteObservable.notifyObservers(this);
  41307. this._nextActiveAction.execute(evt);
  41308. this.skipToNextActiveAction();
  41309. };
  41310. Action.prototype.execute = function (evt) {
  41311. };
  41312. Action.prototype.skipToNextActiveAction = function () {
  41313. if (this._nextActiveAction._child) {
  41314. if (!this._nextActiveAction._child._actionManager) {
  41315. this._nextActiveAction._child._actionManager = this._actionManager;
  41316. }
  41317. this._nextActiveAction = this._nextActiveAction._child;
  41318. }
  41319. else {
  41320. this._nextActiveAction = this;
  41321. }
  41322. };
  41323. Action.prototype.then = function (action) {
  41324. this._child = action;
  41325. action._actionManager = this._actionManager;
  41326. action._prepare();
  41327. return action;
  41328. };
  41329. Action.prototype._getProperty = function (propertyPath) {
  41330. return this._actionManager._getProperty(propertyPath);
  41331. };
  41332. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41333. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41334. };
  41335. Action.prototype.serialize = function (parent) {
  41336. };
  41337. // Called by BABYLON.Action objects in serialize(...). Internal use
  41338. Action.prototype._serialize = function (serializedAction, parent) {
  41339. var serializationObject = {
  41340. type: 1,
  41341. children: [],
  41342. name: serializedAction.name,
  41343. properties: serializedAction.properties || []
  41344. };
  41345. // Serialize child
  41346. if (this._child) {
  41347. this._child.serialize(serializationObject);
  41348. }
  41349. // Check if "this" has a condition
  41350. if (this._condition) {
  41351. var serializedCondition = this._condition.serialize();
  41352. serializedCondition.children.push(serializationObject);
  41353. if (parent) {
  41354. parent.children.push(serializedCondition);
  41355. }
  41356. return serializedCondition;
  41357. }
  41358. if (parent) {
  41359. parent.children.push(serializationObject);
  41360. }
  41361. return serializationObject;
  41362. };
  41363. Action._SerializeValueAsString = function (value) {
  41364. if (typeof value === "number") {
  41365. return value.toString();
  41366. }
  41367. if (typeof value === "boolean") {
  41368. return value ? "true" : "false";
  41369. }
  41370. if (value instanceof BABYLON.Vector2) {
  41371. return value.x + ", " + value.y;
  41372. }
  41373. if (value instanceof BABYLON.Vector3) {
  41374. return value.x + ", " + value.y + ", " + value.z;
  41375. }
  41376. if (value instanceof BABYLON.Color3) {
  41377. return value.r + ", " + value.g + ", " + value.b;
  41378. }
  41379. if (value instanceof BABYLON.Color4) {
  41380. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41381. }
  41382. return value; // string
  41383. };
  41384. Action._GetTargetProperty = function (target) {
  41385. return {
  41386. name: "target",
  41387. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41388. : target instanceof BABYLON.Light ? "LightProperties"
  41389. : target instanceof BABYLON.Camera ? "CameraProperties"
  41390. : "SceneProperties",
  41391. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41392. };
  41393. };
  41394. return Action;
  41395. }());
  41396. BABYLON.Action = Action;
  41397. })(BABYLON || (BABYLON = {}));
  41398. //# sourceMappingURL=babylon.action.js.map
  41399. var BABYLON;
  41400. (function (BABYLON) {
  41401. /**
  41402. * ActionEvent is the event beint sent when an action is triggered.
  41403. */
  41404. var ActionEvent = /** @class */ (function () {
  41405. /**
  41406. * @param source The mesh or sprite that triggered the action.
  41407. * @param pointerX The X mouse cursor position at the time of the event
  41408. * @param pointerY The Y mouse cursor position at the time of the event
  41409. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41410. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41411. */
  41412. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41413. this.source = source;
  41414. this.pointerX = pointerX;
  41415. this.pointerY = pointerY;
  41416. this.meshUnderPointer = meshUnderPointer;
  41417. this.sourceEvent = sourceEvent;
  41418. this.additionalData = additionalData;
  41419. }
  41420. /**
  41421. * Helper function to auto-create an ActionEvent from a source mesh.
  41422. * @param source The source mesh that triggered the event
  41423. * @param evt {Event} The original (browser) event
  41424. */
  41425. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41426. var scene = source.getScene();
  41427. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41428. };
  41429. /**
  41430. * Helper function to auto-create an ActionEvent from a source mesh.
  41431. * @param source The source sprite that triggered the event
  41432. * @param scene Scene associated with the sprite
  41433. * @param evt {Event} The original (browser) event
  41434. */
  41435. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41436. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41437. };
  41438. /**
  41439. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41440. * @param scene the scene where the event occurred
  41441. * @param evt {Event} The original (browser) event
  41442. */
  41443. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41444. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41445. };
  41446. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41447. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41448. };
  41449. return ActionEvent;
  41450. }());
  41451. BABYLON.ActionEvent = ActionEvent;
  41452. /**
  41453. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41454. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41455. */
  41456. var ActionManager = /** @class */ (function () {
  41457. function ActionManager(scene) {
  41458. // Members
  41459. this.actions = new Array();
  41460. this.hoverCursor = '';
  41461. this._scene = scene;
  41462. scene._actionManagers.push(this);
  41463. }
  41464. Object.defineProperty(ActionManager, "NothingTrigger", {
  41465. get: function () {
  41466. return ActionManager._NothingTrigger;
  41467. },
  41468. enumerable: true,
  41469. configurable: true
  41470. });
  41471. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41472. get: function () {
  41473. return ActionManager._OnPickTrigger;
  41474. },
  41475. enumerable: true,
  41476. configurable: true
  41477. });
  41478. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41479. get: function () {
  41480. return ActionManager._OnLeftPickTrigger;
  41481. },
  41482. enumerable: true,
  41483. configurable: true
  41484. });
  41485. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41486. get: function () {
  41487. return ActionManager._OnRightPickTrigger;
  41488. },
  41489. enumerable: true,
  41490. configurable: true
  41491. });
  41492. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41493. get: function () {
  41494. return ActionManager._OnCenterPickTrigger;
  41495. },
  41496. enumerable: true,
  41497. configurable: true
  41498. });
  41499. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41500. get: function () {
  41501. return ActionManager._OnPickDownTrigger;
  41502. },
  41503. enumerable: true,
  41504. configurable: true
  41505. });
  41506. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41507. get: function () {
  41508. return ActionManager._OnDoublePickTrigger;
  41509. },
  41510. enumerable: true,
  41511. configurable: true
  41512. });
  41513. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41514. get: function () {
  41515. return ActionManager._OnPickUpTrigger;
  41516. },
  41517. enumerable: true,
  41518. configurable: true
  41519. });
  41520. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41521. /// This trigger will only be raised if you also declared a OnPickDown
  41522. get: function () {
  41523. return ActionManager._OnPickOutTrigger;
  41524. },
  41525. enumerable: true,
  41526. configurable: true
  41527. });
  41528. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41529. get: function () {
  41530. return ActionManager._OnLongPressTrigger;
  41531. },
  41532. enumerable: true,
  41533. configurable: true
  41534. });
  41535. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41536. get: function () {
  41537. return ActionManager._OnPointerOverTrigger;
  41538. },
  41539. enumerable: true,
  41540. configurable: true
  41541. });
  41542. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41543. get: function () {
  41544. return ActionManager._OnPointerOutTrigger;
  41545. },
  41546. enumerable: true,
  41547. configurable: true
  41548. });
  41549. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41550. get: function () {
  41551. return ActionManager._OnEveryFrameTrigger;
  41552. },
  41553. enumerable: true,
  41554. configurable: true
  41555. });
  41556. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41557. get: function () {
  41558. return ActionManager._OnIntersectionEnterTrigger;
  41559. },
  41560. enumerable: true,
  41561. configurable: true
  41562. });
  41563. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41564. get: function () {
  41565. return ActionManager._OnIntersectionExitTrigger;
  41566. },
  41567. enumerable: true,
  41568. configurable: true
  41569. });
  41570. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41571. get: function () {
  41572. return ActionManager._OnKeyDownTrigger;
  41573. },
  41574. enumerable: true,
  41575. configurable: true
  41576. });
  41577. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41578. get: function () {
  41579. return ActionManager._OnKeyUpTrigger;
  41580. },
  41581. enumerable: true,
  41582. configurable: true
  41583. });
  41584. // Methods
  41585. ActionManager.prototype.dispose = function () {
  41586. var index = this._scene._actionManagers.indexOf(this);
  41587. for (var i = 0; i < this.actions.length; i++) {
  41588. var action = this.actions[i];
  41589. ActionManager.Triggers[action.trigger]--;
  41590. if (ActionManager.Triggers[action.trigger] === 0) {
  41591. delete ActionManager.Triggers[action.trigger];
  41592. }
  41593. }
  41594. if (index > -1) {
  41595. this._scene._actionManagers.splice(index, 1);
  41596. }
  41597. };
  41598. ActionManager.prototype.getScene = function () {
  41599. return this._scene;
  41600. };
  41601. /**
  41602. * Does this action manager handles actions of any of the given triggers
  41603. * @param {number[]} triggers - the triggers to be tested
  41604. * @return {boolean} whether one (or more) of the triggers is handeled
  41605. */
  41606. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41607. for (var index = 0; index < this.actions.length; index++) {
  41608. var action = this.actions[index];
  41609. if (triggers.indexOf(action.trigger) > -1) {
  41610. return true;
  41611. }
  41612. }
  41613. return false;
  41614. };
  41615. /**
  41616. * Does this action manager handles actions of a given trigger
  41617. * @param {number} trigger - the trigger to be tested
  41618. * @return {boolean} whether the trigger is handeled
  41619. */
  41620. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41621. for (var index = 0; index < this.actions.length; index++) {
  41622. var action = this.actions[index];
  41623. if (action.trigger === trigger) {
  41624. return true;
  41625. }
  41626. }
  41627. return false;
  41628. };
  41629. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41630. /**
  41631. * Does this action manager has pointer triggers
  41632. * @return {boolean} whether or not it has pointer triggers
  41633. */
  41634. get: function () {
  41635. for (var index = 0; index < this.actions.length; index++) {
  41636. var action = this.actions[index];
  41637. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41638. return true;
  41639. }
  41640. }
  41641. return false;
  41642. },
  41643. enumerable: true,
  41644. configurable: true
  41645. });
  41646. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41647. /**
  41648. * Does this action manager has pick triggers
  41649. * @return {boolean} whether or not it has pick triggers
  41650. */
  41651. get: function () {
  41652. for (var index = 0; index < this.actions.length; index++) {
  41653. var action = this.actions[index];
  41654. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41655. return true;
  41656. }
  41657. }
  41658. return false;
  41659. },
  41660. enumerable: true,
  41661. configurable: true
  41662. });
  41663. Object.defineProperty(ActionManager, "HasTriggers", {
  41664. /**
  41665. * Does exist one action manager with at least one trigger
  41666. * @return {boolean} whether or not it exists one action manager with one trigger
  41667. **/
  41668. get: function () {
  41669. for (var t in ActionManager.Triggers) {
  41670. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41671. return true;
  41672. }
  41673. }
  41674. return false;
  41675. },
  41676. enumerable: true,
  41677. configurable: true
  41678. });
  41679. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41680. /**
  41681. * Does exist one action manager with at least one pick trigger
  41682. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41683. **/
  41684. get: function () {
  41685. for (var t in ActionManager.Triggers) {
  41686. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41687. var t_int = parseInt(t);
  41688. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41689. return true;
  41690. }
  41691. }
  41692. }
  41693. return false;
  41694. },
  41695. enumerable: true,
  41696. configurable: true
  41697. });
  41698. /**
  41699. * Does exist one action manager that handles actions of a given trigger
  41700. * @param {number} trigger - the trigger to be tested
  41701. * @return {boolean} whether the trigger is handeled by at least one action manager
  41702. **/
  41703. ActionManager.HasSpecificTrigger = function (trigger) {
  41704. for (var t in ActionManager.Triggers) {
  41705. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41706. var t_int = parseInt(t);
  41707. if (t_int === trigger) {
  41708. return true;
  41709. }
  41710. }
  41711. }
  41712. return false;
  41713. };
  41714. /**
  41715. * Registers an action to this action manager
  41716. * @param {BABYLON.Action} action - the action to be registered
  41717. * @return {BABYLON.Action} the action amended (prepared) after registration
  41718. */
  41719. ActionManager.prototype.registerAction = function (action) {
  41720. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41721. if (this.getScene().actionManager !== this) {
  41722. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41723. return null;
  41724. }
  41725. }
  41726. this.actions.push(action);
  41727. if (ActionManager.Triggers[action.trigger]) {
  41728. ActionManager.Triggers[action.trigger]++;
  41729. }
  41730. else {
  41731. ActionManager.Triggers[action.trigger] = 1;
  41732. }
  41733. action._actionManager = this;
  41734. action._prepare();
  41735. return action;
  41736. };
  41737. /**
  41738. * Process a specific trigger
  41739. * @param {number} trigger - the trigger to process
  41740. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41741. */
  41742. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41743. for (var index = 0; index < this.actions.length; index++) {
  41744. var action = this.actions[index];
  41745. if (action.trigger === trigger) {
  41746. if (evt) {
  41747. if (trigger === ActionManager.OnKeyUpTrigger
  41748. || trigger === ActionManager.OnKeyDownTrigger) {
  41749. var parameter = action.getTriggerParameter();
  41750. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41751. if (!parameter.toLowerCase) {
  41752. continue;
  41753. }
  41754. var lowerCase = parameter.toLowerCase();
  41755. if (lowerCase !== evt.sourceEvent.key) {
  41756. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41757. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41758. if (actualkey !== lowerCase) {
  41759. continue;
  41760. }
  41761. }
  41762. }
  41763. }
  41764. }
  41765. action._executeCurrent(evt);
  41766. }
  41767. }
  41768. };
  41769. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41770. var properties = propertyPath.split(".");
  41771. for (var index = 0; index < properties.length - 1; index++) {
  41772. target = target[properties[index]];
  41773. }
  41774. return target;
  41775. };
  41776. ActionManager.prototype._getProperty = function (propertyPath) {
  41777. var properties = propertyPath.split(".");
  41778. return properties[properties.length - 1];
  41779. };
  41780. ActionManager.prototype.serialize = function (name) {
  41781. var root = {
  41782. children: new Array(),
  41783. name: name,
  41784. type: 3,
  41785. properties: new Array() // Empty for root but required
  41786. };
  41787. for (var i = 0; i < this.actions.length; i++) {
  41788. var triggerObject = {
  41789. type: 0,
  41790. children: new Array(),
  41791. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41792. properties: new Array()
  41793. };
  41794. var triggerOptions = this.actions[i].triggerOptions;
  41795. if (triggerOptions && typeof triggerOptions !== "number") {
  41796. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41797. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  41798. }
  41799. else {
  41800. var parameter = {};
  41801. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  41802. if (triggerOptions.parameter.mesh) {
  41803. parameter._meshId = triggerOptions.parameter.mesh.id;
  41804. }
  41805. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  41806. }
  41807. }
  41808. // Serialize child action, recursively
  41809. this.actions[i].serialize(triggerObject);
  41810. // Add serialized trigger
  41811. root.children.push(triggerObject);
  41812. }
  41813. return root;
  41814. };
  41815. ActionManager.Parse = function (parsedActions, object, scene) {
  41816. var actionManager = new BABYLON.ActionManager(scene);
  41817. if (object === null)
  41818. scene.actionManager = actionManager;
  41819. else
  41820. object.actionManager = actionManager;
  41821. // instanciate a new object
  41822. var instanciate = function (name, params) {
  41823. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  41824. newInstance.constructor.apply(newInstance, params);
  41825. return newInstance;
  41826. };
  41827. var parseParameter = function (name, value, target, propertyPath) {
  41828. if (propertyPath === null) {
  41829. // String, boolean or float
  41830. var floatValue = parseFloat(value);
  41831. if (value === "true" || value === "false")
  41832. return value === "true";
  41833. else
  41834. return isNaN(floatValue) ? value : floatValue;
  41835. }
  41836. var effectiveTarget = propertyPath.split(".");
  41837. var values = value.split(",");
  41838. // Get effective Target
  41839. for (var i = 0; i < effectiveTarget.length; i++) {
  41840. target = target[effectiveTarget[i]];
  41841. }
  41842. // Return appropriate value with its type
  41843. if (typeof (target) === "boolean")
  41844. return values[0] === "true";
  41845. if (typeof (target) === "string")
  41846. return values[0];
  41847. // Parameters with multiple values such as Vector3 etc.
  41848. var split = new Array();
  41849. for (var i = 0; i < values.length; i++)
  41850. split.push(parseFloat(values[i]));
  41851. if (target instanceof BABYLON.Vector3)
  41852. return BABYLON.Vector3.FromArray(split);
  41853. if (target instanceof BABYLON.Vector4)
  41854. return BABYLON.Vector4.FromArray(split);
  41855. if (target instanceof BABYLON.Color3)
  41856. return BABYLON.Color3.FromArray(split);
  41857. if (target instanceof BABYLON.Color4)
  41858. return BABYLON.Color4.FromArray(split);
  41859. return parseFloat(values[0]);
  41860. };
  41861. // traverse graph per trigger
  41862. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  41863. if (combineArray === void 0) { combineArray = null; }
  41864. if (parsedAction.detached)
  41865. return;
  41866. var parameters = new Array();
  41867. var target = null;
  41868. var propertyPath = null;
  41869. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  41870. // Parameters
  41871. if (parsedAction.type === 2)
  41872. parameters.push(actionManager);
  41873. else
  41874. parameters.push(trigger);
  41875. if (combine) {
  41876. var actions = new Array();
  41877. for (var j = 0; j < parsedAction.combine.length; j++) {
  41878. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  41879. }
  41880. parameters.push(actions);
  41881. }
  41882. else {
  41883. for (var i = 0; i < parsedAction.properties.length; i++) {
  41884. var value = parsedAction.properties[i].value;
  41885. var name = parsedAction.properties[i].name;
  41886. var targetType = parsedAction.properties[i].targetType;
  41887. if (name === "target")
  41888. if (targetType !== null && targetType === "SceneProperties")
  41889. value = target = scene;
  41890. else
  41891. value = target = scene.getNodeByName(value);
  41892. else if (name === "parent")
  41893. value = scene.getNodeByName(value);
  41894. else if (name === "sound")
  41895. value = scene.getSoundByName(value);
  41896. else if (name !== "propertyPath") {
  41897. if (parsedAction.type === 2 && name === "operator")
  41898. value = BABYLON.ValueCondition[value];
  41899. else
  41900. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  41901. }
  41902. else {
  41903. propertyPath = value;
  41904. }
  41905. parameters.push(value);
  41906. }
  41907. }
  41908. if (combineArray === null) {
  41909. parameters.push(condition);
  41910. }
  41911. else {
  41912. parameters.push(null);
  41913. }
  41914. // If interpolate value action
  41915. if (parsedAction.name === "InterpolateValueAction") {
  41916. var param = parameters[parameters.length - 2];
  41917. parameters[parameters.length - 1] = param;
  41918. parameters[parameters.length - 2] = condition;
  41919. }
  41920. // Action or condition(s) and not CombineAction
  41921. var newAction = instanciate(parsedAction.name, parameters);
  41922. if (newAction instanceof BABYLON.Condition && condition !== null) {
  41923. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  41924. if (action)
  41925. action.then(nothing);
  41926. else
  41927. actionManager.registerAction(nothing);
  41928. action = nothing;
  41929. }
  41930. if (combineArray === null) {
  41931. if (newAction instanceof BABYLON.Condition) {
  41932. condition = newAction;
  41933. newAction = action;
  41934. }
  41935. else {
  41936. condition = null;
  41937. if (action)
  41938. action.then(newAction);
  41939. else
  41940. actionManager.registerAction(newAction);
  41941. }
  41942. }
  41943. else {
  41944. combineArray.push(newAction);
  41945. }
  41946. for (var i = 0; i < parsedAction.children.length; i++)
  41947. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  41948. };
  41949. // triggers
  41950. for (var i = 0; i < parsedActions.children.length; i++) {
  41951. var triggerParams;
  41952. var trigger = parsedActions.children[i];
  41953. if (trigger.properties.length > 0) {
  41954. var param = trigger.properties[0].value;
  41955. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  41956. if (value._meshId) {
  41957. value.mesh = scene.getMeshByID(value._meshId);
  41958. }
  41959. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  41960. }
  41961. else
  41962. triggerParams = ActionManager[trigger.name];
  41963. for (var j = 0; j < trigger.children.length; j++) {
  41964. if (!trigger.detached)
  41965. traverse(trigger.children[j], triggerParams, null, null);
  41966. }
  41967. }
  41968. };
  41969. ActionManager.GetTriggerName = function (trigger) {
  41970. switch (trigger) {
  41971. case 0: return "NothingTrigger";
  41972. case 1: return "OnPickTrigger";
  41973. case 2: return "OnLeftPickTrigger";
  41974. case 3: return "OnRightPickTrigger";
  41975. case 4: return "OnCenterPickTrigger";
  41976. case 5: return "OnPickDownTrigger";
  41977. case 6: return "OnPickUpTrigger";
  41978. case 7: return "OnLongPressTrigger";
  41979. case 8: return "OnPointerOverTrigger";
  41980. case 9: return "OnPointerOutTrigger";
  41981. case 10: return "OnEveryFrameTrigger";
  41982. case 11: return "OnIntersectionEnterTrigger";
  41983. case 12: return "OnIntersectionExitTrigger";
  41984. case 13: return "OnKeyDownTrigger";
  41985. case 14: return "OnKeyUpTrigger";
  41986. case 15: return "OnPickOutTrigger";
  41987. default: return "";
  41988. }
  41989. };
  41990. // Statics
  41991. ActionManager._NothingTrigger = 0;
  41992. ActionManager._OnPickTrigger = 1;
  41993. ActionManager._OnLeftPickTrigger = 2;
  41994. ActionManager._OnRightPickTrigger = 3;
  41995. ActionManager._OnCenterPickTrigger = 4;
  41996. ActionManager._OnPickDownTrigger = 5;
  41997. ActionManager._OnDoublePickTrigger = 6;
  41998. ActionManager._OnPickUpTrigger = 7;
  41999. ActionManager._OnLongPressTrigger = 8;
  42000. ActionManager._OnPointerOverTrigger = 9;
  42001. ActionManager._OnPointerOutTrigger = 10;
  42002. ActionManager._OnEveryFrameTrigger = 11;
  42003. ActionManager._OnIntersectionEnterTrigger = 12;
  42004. ActionManager._OnIntersectionExitTrigger = 13;
  42005. ActionManager._OnKeyDownTrigger = 14;
  42006. ActionManager._OnKeyUpTrigger = 15;
  42007. ActionManager._OnPickOutTrigger = 16;
  42008. ActionManager.Triggers = {};
  42009. return ActionManager;
  42010. }());
  42011. BABYLON.ActionManager = ActionManager;
  42012. })(BABYLON || (BABYLON = {}));
  42013. //# sourceMappingURL=babylon.actionManager.js.map
  42014. var BABYLON;
  42015. (function (BABYLON) {
  42016. var InterpolateValueAction = /** @class */ (function (_super) {
  42017. __extends(InterpolateValueAction, _super);
  42018. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42019. if (duration === void 0) { duration = 1000; }
  42020. var _this = _super.call(this, triggerOptions, condition) || this;
  42021. _this.propertyPath = propertyPath;
  42022. _this.value = value;
  42023. _this.duration = duration;
  42024. _this.stopOtherAnimations = stopOtherAnimations;
  42025. _this.onInterpolationDone = onInterpolationDone;
  42026. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42027. _this._target = _this._effectiveTarget = target;
  42028. return _this;
  42029. }
  42030. InterpolateValueAction.prototype._prepare = function () {
  42031. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42032. this._property = this._getProperty(this.propertyPath);
  42033. };
  42034. InterpolateValueAction.prototype.execute = function () {
  42035. var _this = this;
  42036. var scene = this._actionManager.getScene();
  42037. var keys = [
  42038. {
  42039. frame: 0,
  42040. value: this._effectiveTarget[this._property]
  42041. }, {
  42042. frame: 100,
  42043. value: this.value
  42044. }
  42045. ];
  42046. var dataType;
  42047. if (typeof this.value === "number") {
  42048. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42049. }
  42050. else if (this.value instanceof BABYLON.Color3) {
  42051. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42052. }
  42053. else if (this.value instanceof BABYLON.Vector3) {
  42054. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42055. }
  42056. else if (this.value instanceof BABYLON.Matrix) {
  42057. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42058. }
  42059. else if (this.value instanceof BABYLON.Quaternion) {
  42060. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42061. }
  42062. else {
  42063. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42064. return;
  42065. }
  42066. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42067. animation.setKeys(keys);
  42068. if (this.stopOtherAnimations) {
  42069. scene.stopAnimation(this._effectiveTarget);
  42070. }
  42071. var wrapper = function () {
  42072. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42073. if (_this.onInterpolationDone) {
  42074. _this.onInterpolationDone();
  42075. }
  42076. };
  42077. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42078. };
  42079. InterpolateValueAction.prototype.serialize = function (parent) {
  42080. return _super.prototype._serialize.call(this, {
  42081. name: "InterpolateValueAction",
  42082. properties: [
  42083. BABYLON.Action._GetTargetProperty(this._target),
  42084. { name: "propertyPath", value: this.propertyPath },
  42085. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42086. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42087. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42088. ]
  42089. }, parent);
  42090. };
  42091. return InterpolateValueAction;
  42092. }(BABYLON.Action));
  42093. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42094. })(BABYLON || (BABYLON = {}));
  42095. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42096. var BABYLON;
  42097. (function (BABYLON) {
  42098. var SwitchBooleanAction = /** @class */ (function (_super) {
  42099. __extends(SwitchBooleanAction, _super);
  42100. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42101. var _this = _super.call(this, triggerOptions, condition) || this;
  42102. _this.propertyPath = propertyPath;
  42103. _this._target = _this._effectiveTarget = target;
  42104. return _this;
  42105. }
  42106. SwitchBooleanAction.prototype._prepare = function () {
  42107. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42108. this._property = this._getProperty(this.propertyPath);
  42109. };
  42110. SwitchBooleanAction.prototype.execute = function () {
  42111. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42112. };
  42113. SwitchBooleanAction.prototype.serialize = function (parent) {
  42114. return _super.prototype._serialize.call(this, {
  42115. name: "SwitchBooleanAction",
  42116. properties: [
  42117. BABYLON.Action._GetTargetProperty(this._target),
  42118. { name: "propertyPath", value: this.propertyPath }
  42119. ]
  42120. }, parent);
  42121. };
  42122. return SwitchBooleanAction;
  42123. }(BABYLON.Action));
  42124. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42125. var SetStateAction = /** @class */ (function (_super) {
  42126. __extends(SetStateAction, _super);
  42127. function SetStateAction(triggerOptions, target, value, condition) {
  42128. var _this = _super.call(this, triggerOptions, condition) || this;
  42129. _this.value = value;
  42130. _this._target = target;
  42131. return _this;
  42132. }
  42133. SetStateAction.prototype.execute = function () {
  42134. this._target.state = this.value;
  42135. };
  42136. SetStateAction.prototype.serialize = function (parent) {
  42137. return _super.prototype._serialize.call(this, {
  42138. name: "SetStateAction",
  42139. properties: [
  42140. BABYLON.Action._GetTargetProperty(this._target),
  42141. { name: "value", value: this.value }
  42142. ]
  42143. }, parent);
  42144. };
  42145. return SetStateAction;
  42146. }(BABYLON.Action));
  42147. BABYLON.SetStateAction = SetStateAction;
  42148. var SetValueAction = /** @class */ (function (_super) {
  42149. __extends(SetValueAction, _super);
  42150. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42151. var _this = _super.call(this, triggerOptions, condition) || this;
  42152. _this.propertyPath = propertyPath;
  42153. _this.value = value;
  42154. _this._target = _this._effectiveTarget = target;
  42155. return _this;
  42156. }
  42157. SetValueAction.prototype._prepare = function () {
  42158. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42159. this._property = this._getProperty(this.propertyPath);
  42160. };
  42161. SetValueAction.prototype.execute = function () {
  42162. this._effectiveTarget[this._property] = this.value;
  42163. if (this._target.markAsDirty) {
  42164. this._target.markAsDirty(this._property);
  42165. }
  42166. };
  42167. SetValueAction.prototype.serialize = function (parent) {
  42168. return _super.prototype._serialize.call(this, {
  42169. name: "SetValueAction",
  42170. properties: [
  42171. BABYLON.Action._GetTargetProperty(this._target),
  42172. { name: "propertyPath", value: this.propertyPath },
  42173. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42174. ]
  42175. }, parent);
  42176. };
  42177. return SetValueAction;
  42178. }(BABYLON.Action));
  42179. BABYLON.SetValueAction = SetValueAction;
  42180. var IncrementValueAction = /** @class */ (function (_super) {
  42181. __extends(IncrementValueAction, _super);
  42182. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42183. var _this = _super.call(this, triggerOptions, condition) || this;
  42184. _this.propertyPath = propertyPath;
  42185. _this.value = value;
  42186. _this._target = _this._effectiveTarget = target;
  42187. return _this;
  42188. }
  42189. IncrementValueAction.prototype._prepare = function () {
  42190. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42191. this._property = this._getProperty(this.propertyPath);
  42192. if (typeof this._effectiveTarget[this._property] !== "number") {
  42193. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42194. }
  42195. };
  42196. IncrementValueAction.prototype.execute = function () {
  42197. this._effectiveTarget[this._property] += this.value;
  42198. if (this._target.markAsDirty) {
  42199. this._target.markAsDirty(this._property);
  42200. }
  42201. };
  42202. IncrementValueAction.prototype.serialize = function (parent) {
  42203. return _super.prototype._serialize.call(this, {
  42204. name: "IncrementValueAction",
  42205. properties: [
  42206. BABYLON.Action._GetTargetProperty(this._target),
  42207. { name: "propertyPath", value: this.propertyPath },
  42208. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42209. ]
  42210. }, parent);
  42211. };
  42212. return IncrementValueAction;
  42213. }(BABYLON.Action));
  42214. BABYLON.IncrementValueAction = IncrementValueAction;
  42215. var PlayAnimationAction = /** @class */ (function (_super) {
  42216. __extends(PlayAnimationAction, _super);
  42217. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42218. var _this = _super.call(this, triggerOptions, condition) || this;
  42219. _this.from = from;
  42220. _this.to = to;
  42221. _this.loop = loop;
  42222. _this._target = target;
  42223. return _this;
  42224. }
  42225. PlayAnimationAction.prototype._prepare = function () {
  42226. };
  42227. PlayAnimationAction.prototype.execute = function () {
  42228. var scene = this._actionManager.getScene();
  42229. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42230. };
  42231. PlayAnimationAction.prototype.serialize = function (parent) {
  42232. return _super.prototype._serialize.call(this, {
  42233. name: "PlayAnimationAction",
  42234. properties: [
  42235. BABYLON.Action._GetTargetProperty(this._target),
  42236. { name: "from", value: String(this.from) },
  42237. { name: "to", value: String(this.to) },
  42238. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42239. ]
  42240. }, parent);
  42241. };
  42242. return PlayAnimationAction;
  42243. }(BABYLON.Action));
  42244. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42245. var StopAnimationAction = /** @class */ (function (_super) {
  42246. __extends(StopAnimationAction, _super);
  42247. function StopAnimationAction(triggerOptions, target, condition) {
  42248. var _this = _super.call(this, triggerOptions, condition) || this;
  42249. _this._target = target;
  42250. return _this;
  42251. }
  42252. StopAnimationAction.prototype._prepare = function () {
  42253. };
  42254. StopAnimationAction.prototype.execute = function () {
  42255. var scene = this._actionManager.getScene();
  42256. scene.stopAnimation(this._target);
  42257. };
  42258. StopAnimationAction.prototype.serialize = function (parent) {
  42259. return _super.prototype._serialize.call(this, {
  42260. name: "StopAnimationAction",
  42261. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42262. }, parent);
  42263. };
  42264. return StopAnimationAction;
  42265. }(BABYLON.Action));
  42266. BABYLON.StopAnimationAction = StopAnimationAction;
  42267. var DoNothingAction = /** @class */ (function (_super) {
  42268. __extends(DoNothingAction, _super);
  42269. function DoNothingAction(triggerOptions, condition) {
  42270. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42271. return _super.call(this, triggerOptions, condition) || this;
  42272. }
  42273. DoNothingAction.prototype.execute = function () {
  42274. };
  42275. DoNothingAction.prototype.serialize = function (parent) {
  42276. return _super.prototype._serialize.call(this, {
  42277. name: "DoNothingAction",
  42278. properties: []
  42279. }, parent);
  42280. };
  42281. return DoNothingAction;
  42282. }(BABYLON.Action));
  42283. BABYLON.DoNothingAction = DoNothingAction;
  42284. var CombineAction = /** @class */ (function (_super) {
  42285. __extends(CombineAction, _super);
  42286. function CombineAction(triggerOptions, children, condition) {
  42287. var _this = _super.call(this, triggerOptions, condition) || this;
  42288. _this.children = children;
  42289. return _this;
  42290. }
  42291. CombineAction.prototype._prepare = function () {
  42292. for (var index = 0; index < this.children.length; index++) {
  42293. this.children[index]._actionManager = this._actionManager;
  42294. this.children[index]._prepare();
  42295. }
  42296. };
  42297. CombineAction.prototype.execute = function (evt) {
  42298. for (var index = 0; index < this.children.length; index++) {
  42299. this.children[index].execute(evt);
  42300. }
  42301. };
  42302. CombineAction.prototype.serialize = function (parent) {
  42303. var serializationObject = _super.prototype._serialize.call(this, {
  42304. name: "CombineAction",
  42305. properties: [],
  42306. combine: []
  42307. }, parent);
  42308. for (var i = 0; i < this.children.length; i++) {
  42309. serializationObject.combine.push(this.children[i].serialize(null));
  42310. }
  42311. return serializationObject;
  42312. };
  42313. return CombineAction;
  42314. }(BABYLON.Action));
  42315. BABYLON.CombineAction = CombineAction;
  42316. var ExecuteCodeAction = /** @class */ (function (_super) {
  42317. __extends(ExecuteCodeAction, _super);
  42318. function ExecuteCodeAction(triggerOptions, func, condition) {
  42319. var _this = _super.call(this, triggerOptions, condition) || this;
  42320. _this.func = func;
  42321. return _this;
  42322. }
  42323. ExecuteCodeAction.prototype.execute = function (evt) {
  42324. this.func(evt);
  42325. };
  42326. return ExecuteCodeAction;
  42327. }(BABYLON.Action));
  42328. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42329. var SetParentAction = /** @class */ (function (_super) {
  42330. __extends(SetParentAction, _super);
  42331. function SetParentAction(triggerOptions, target, parent, condition) {
  42332. var _this = _super.call(this, triggerOptions, condition) || this;
  42333. _this._target = target;
  42334. _this._parent = parent;
  42335. return _this;
  42336. }
  42337. SetParentAction.prototype._prepare = function () {
  42338. };
  42339. SetParentAction.prototype.execute = function () {
  42340. if (this._target.parent === this._parent) {
  42341. return;
  42342. }
  42343. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42344. invertParentWorldMatrix.invert();
  42345. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42346. this._target.parent = this._parent;
  42347. };
  42348. SetParentAction.prototype.serialize = function (parent) {
  42349. return _super.prototype._serialize.call(this, {
  42350. name: "SetParentAction",
  42351. properties: [
  42352. BABYLON.Action._GetTargetProperty(this._target),
  42353. BABYLON.Action._GetTargetProperty(this._parent),
  42354. ]
  42355. }, parent);
  42356. };
  42357. return SetParentAction;
  42358. }(BABYLON.Action));
  42359. BABYLON.SetParentAction = SetParentAction;
  42360. var PlaySoundAction = /** @class */ (function (_super) {
  42361. __extends(PlaySoundAction, _super);
  42362. function PlaySoundAction(triggerOptions, sound, condition) {
  42363. var _this = _super.call(this, triggerOptions, condition) || this;
  42364. _this._sound = sound;
  42365. return _this;
  42366. }
  42367. PlaySoundAction.prototype._prepare = function () {
  42368. };
  42369. PlaySoundAction.prototype.execute = function () {
  42370. if (this._sound !== undefined)
  42371. this._sound.play();
  42372. };
  42373. PlaySoundAction.prototype.serialize = function (parent) {
  42374. return _super.prototype._serialize.call(this, {
  42375. name: "PlaySoundAction",
  42376. properties: [{ name: "sound", value: this._sound.name }]
  42377. }, parent);
  42378. };
  42379. return PlaySoundAction;
  42380. }(BABYLON.Action));
  42381. BABYLON.PlaySoundAction = PlaySoundAction;
  42382. var StopSoundAction = /** @class */ (function (_super) {
  42383. __extends(StopSoundAction, _super);
  42384. function StopSoundAction(triggerOptions, sound, condition) {
  42385. var _this = _super.call(this, triggerOptions, condition) || this;
  42386. _this._sound = sound;
  42387. return _this;
  42388. }
  42389. StopSoundAction.prototype._prepare = function () {
  42390. };
  42391. StopSoundAction.prototype.execute = function () {
  42392. if (this._sound !== undefined)
  42393. this._sound.stop();
  42394. };
  42395. StopSoundAction.prototype.serialize = function (parent) {
  42396. return _super.prototype._serialize.call(this, {
  42397. name: "StopSoundAction",
  42398. properties: [{ name: "sound", value: this._sound.name }]
  42399. }, parent);
  42400. };
  42401. return StopSoundAction;
  42402. }(BABYLON.Action));
  42403. BABYLON.StopSoundAction = StopSoundAction;
  42404. })(BABYLON || (BABYLON = {}));
  42405. //# sourceMappingURL=babylon.directActions.js.map
  42406. var BABYLON;
  42407. (function (BABYLON) {
  42408. var SpriteManager = /** @class */ (function () {
  42409. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  42410. if (epsilon === void 0) { epsilon = 0.01; }
  42411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42412. this.name = name;
  42413. this.sprites = new Array();
  42414. this.renderingGroupId = 0;
  42415. this.layerMask = 0x0FFFFFFF;
  42416. this.fogEnabled = true;
  42417. this.isPickable = false;
  42418. /**
  42419. * An event triggered when the manager is disposed.
  42420. * @type {BABYLON.Observable}
  42421. */
  42422. this.onDisposeObservable = new BABYLON.Observable();
  42423. this._vertexBuffers = {};
  42424. this._capacity = capacity;
  42425. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  42426. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42427. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42428. if (cellSize.width && cellSize.height) {
  42429. this.cellWidth = cellSize.width;
  42430. this.cellHeight = cellSize.height;
  42431. }
  42432. else if (cellSize !== undefined) {
  42433. this.cellWidth = cellSize;
  42434. this.cellHeight = cellSize;
  42435. }
  42436. else {
  42437. return;
  42438. }
  42439. this._epsilon = epsilon;
  42440. this._scene = scene;
  42441. this._scene.spriteManagers.push(this);
  42442. var indices = [];
  42443. var index = 0;
  42444. for (var count = 0; count < capacity; count++) {
  42445. indices.push(index);
  42446. indices.push(index + 1);
  42447. indices.push(index + 2);
  42448. indices.push(index);
  42449. indices.push(index + 2);
  42450. indices.push(index + 3);
  42451. index += 4;
  42452. }
  42453. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  42454. // VBO
  42455. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  42456. this._vertexData = new Float32Array(capacity * 16 * 4);
  42457. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  42458. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  42459. var options = this._buffer.createVertexBuffer("options", 4, 4);
  42460. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  42461. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  42462. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42463. this._vertexBuffers["options"] = options;
  42464. this._vertexBuffers["cellInfo"] = cellInfo;
  42465. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42466. // Effects
  42467. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  42468. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  42469. }
  42470. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  42471. set: function (callback) {
  42472. if (this._onDisposeObserver) {
  42473. this.onDisposeObservable.remove(this._onDisposeObserver);
  42474. }
  42475. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42476. },
  42477. enumerable: true,
  42478. configurable: true
  42479. });
  42480. Object.defineProperty(SpriteManager.prototype, "texture", {
  42481. get: function () {
  42482. return this._spriteTexture;
  42483. },
  42484. set: function (value) {
  42485. this._spriteTexture = value;
  42486. },
  42487. enumerable: true,
  42488. configurable: true
  42489. });
  42490. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  42491. var arrayOffset = index * 16;
  42492. if (offsetX === 0)
  42493. offsetX = this._epsilon;
  42494. else if (offsetX === 1)
  42495. offsetX = 1 - this._epsilon;
  42496. if (offsetY === 0)
  42497. offsetY = this._epsilon;
  42498. else if (offsetY === 1)
  42499. offsetY = 1 - this._epsilon;
  42500. this._vertexData[arrayOffset] = sprite.position.x;
  42501. this._vertexData[arrayOffset + 1] = sprite.position.y;
  42502. this._vertexData[arrayOffset + 2] = sprite.position.z;
  42503. this._vertexData[arrayOffset + 3] = sprite.angle;
  42504. this._vertexData[arrayOffset + 4] = sprite.width;
  42505. this._vertexData[arrayOffset + 5] = sprite.height;
  42506. this._vertexData[arrayOffset + 6] = offsetX;
  42507. this._vertexData[arrayOffset + 7] = offsetY;
  42508. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  42509. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  42510. var offset = (sprite.cellIndex / rowSize) >> 0;
  42511. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  42512. this._vertexData[arrayOffset + 11] = offset;
  42513. // Color
  42514. this._vertexData[arrayOffset + 12] = sprite.color.r;
  42515. this._vertexData[arrayOffset + 13] = sprite.color.g;
  42516. this._vertexData[arrayOffset + 14] = sprite.color.b;
  42517. this._vertexData[arrayOffset + 15] = sprite.color.a;
  42518. };
  42519. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  42520. var count = Math.min(this._capacity, this.sprites.length);
  42521. var min = BABYLON.Vector3.Zero();
  42522. var max = BABYLON.Vector3.Zero();
  42523. var distance = Number.MAX_VALUE;
  42524. var currentSprite = null;
  42525. var cameraSpacePosition = BABYLON.Vector3.Zero();
  42526. var cameraView = camera.getViewMatrix();
  42527. for (var index = 0; index < count; index++) {
  42528. var sprite = this.sprites[index];
  42529. if (!sprite) {
  42530. continue;
  42531. }
  42532. if (predicate) {
  42533. if (!predicate(sprite)) {
  42534. continue;
  42535. }
  42536. }
  42537. else if (!sprite.isPickable) {
  42538. continue;
  42539. }
  42540. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  42541. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  42542. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  42543. if (ray.intersectsBoxMinMax(min, max)) {
  42544. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  42545. if (distance > currentDistance) {
  42546. distance = currentDistance;
  42547. currentSprite = sprite;
  42548. if (fastCheck) {
  42549. break;
  42550. }
  42551. }
  42552. }
  42553. }
  42554. if (currentSprite) {
  42555. var result = new BABYLON.PickingInfo();
  42556. result.hit = true;
  42557. result.pickedSprite = currentSprite;
  42558. result.distance = distance;
  42559. return result;
  42560. }
  42561. return null;
  42562. };
  42563. SpriteManager.prototype.render = function () {
  42564. // Check
  42565. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42566. return;
  42567. var engine = this._scene.getEngine();
  42568. var baseSize = this._spriteTexture.getBaseSize();
  42569. // Sprites
  42570. var deltaTime = engine.getDeltaTime();
  42571. var max = Math.min(this._capacity, this.sprites.length);
  42572. var rowSize = baseSize.width / this.cellWidth;
  42573. var offset = 0;
  42574. for (var index = 0; index < max; index++) {
  42575. var sprite = this.sprites[index];
  42576. if (!sprite) {
  42577. continue;
  42578. }
  42579. sprite._animate(deltaTime);
  42580. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42581. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42582. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42583. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42584. }
  42585. this._buffer.update(this._vertexData);
  42586. // Render
  42587. var effect = this._effectBase;
  42588. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42589. effect = this._effectFog;
  42590. }
  42591. engine.enableEffect(effect);
  42592. var viewMatrix = this._scene.getViewMatrix();
  42593. effect.setTexture("diffuseSampler", this._spriteTexture);
  42594. effect.setMatrix("view", viewMatrix);
  42595. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42596. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42597. // Fog
  42598. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42599. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42600. effect.setColor3("vFogColor", this._scene.fogColor);
  42601. }
  42602. // VBOs
  42603. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42604. // Draw order
  42605. engine.setDepthFunctionToLessOrEqual();
  42606. effect.setBool("alphaTest", true);
  42607. engine.setColorWrite(false);
  42608. engine.draw(true, 0, max * 6);
  42609. engine.setColorWrite(true);
  42610. effect.setBool("alphaTest", false);
  42611. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42612. engine.draw(true, 0, max * 6);
  42613. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42614. };
  42615. SpriteManager.prototype.dispose = function () {
  42616. if (this._buffer) {
  42617. this._buffer.dispose();
  42618. this._buffer = null;
  42619. }
  42620. if (this._indexBuffer) {
  42621. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42622. this._indexBuffer = null;
  42623. }
  42624. if (this._spriteTexture) {
  42625. this._spriteTexture.dispose();
  42626. this._spriteTexture = null;
  42627. }
  42628. // Remove from scene
  42629. var index = this._scene.spriteManagers.indexOf(this);
  42630. this._scene.spriteManagers.splice(index, 1);
  42631. // Callback
  42632. this.onDisposeObservable.notifyObservers(this);
  42633. this.onDisposeObservable.clear();
  42634. };
  42635. return SpriteManager;
  42636. }());
  42637. BABYLON.SpriteManager = SpriteManager;
  42638. })(BABYLON || (BABYLON = {}));
  42639. //# sourceMappingURL=babylon.spriteManager.js.map
  42640. var BABYLON;
  42641. (function (BABYLON) {
  42642. var Sprite = /** @class */ (function () {
  42643. function Sprite(name, manager) {
  42644. this.name = name;
  42645. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42646. this.width = 1.0;
  42647. this.height = 1.0;
  42648. this.angle = 0;
  42649. this.cellIndex = 0;
  42650. this.invertU = 0;
  42651. this.invertV = 0;
  42652. this.animations = new Array();
  42653. this.isPickable = false;
  42654. this._animationStarted = false;
  42655. this._loopAnimation = false;
  42656. this._fromIndex = 0;
  42657. this._toIndex = 0;
  42658. this._delay = 0;
  42659. this._direction = 1;
  42660. this._time = 0;
  42661. this._manager = manager;
  42662. this._manager.sprites.push(this);
  42663. this.position = BABYLON.Vector3.Zero();
  42664. }
  42665. Object.defineProperty(Sprite.prototype, "size", {
  42666. get: function () {
  42667. return this.width;
  42668. },
  42669. set: function (value) {
  42670. this.width = value;
  42671. this.height = value;
  42672. },
  42673. enumerable: true,
  42674. configurable: true
  42675. });
  42676. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  42677. this._fromIndex = from;
  42678. this._toIndex = to;
  42679. this._loopAnimation = loop;
  42680. this._delay = delay;
  42681. this._animationStarted = true;
  42682. this._direction = from < to ? 1 : -1;
  42683. this.cellIndex = from;
  42684. this._time = 0;
  42685. this._onAnimationEnd = onAnimationEnd;
  42686. };
  42687. Sprite.prototype.stopAnimation = function () {
  42688. this._animationStarted = false;
  42689. };
  42690. Sprite.prototype._animate = function (deltaTime) {
  42691. if (!this._animationStarted)
  42692. return;
  42693. this._time += deltaTime;
  42694. if (this._time > this._delay) {
  42695. this._time = this._time % this._delay;
  42696. this.cellIndex += this._direction;
  42697. if (this.cellIndex > this._toIndex) {
  42698. if (this._loopAnimation) {
  42699. this.cellIndex = this._fromIndex;
  42700. }
  42701. else {
  42702. this.cellIndex = this._toIndex;
  42703. this._animationStarted = false;
  42704. if (this._onAnimationEnd) {
  42705. this._onAnimationEnd();
  42706. }
  42707. if (this.disposeWhenFinishedAnimating) {
  42708. this.dispose();
  42709. }
  42710. }
  42711. }
  42712. }
  42713. };
  42714. Sprite.prototype.dispose = function () {
  42715. for (var i = 0; i < this._manager.sprites.length; i++) {
  42716. if (this._manager.sprites[i] == this) {
  42717. this._manager.sprites.splice(i, 1);
  42718. }
  42719. }
  42720. };
  42721. return Sprite;
  42722. }());
  42723. BABYLON.Sprite = Sprite;
  42724. })(BABYLON || (BABYLON = {}));
  42725. //# sourceMappingURL=babylon.sprite.js.map
  42726. var BABYLON;
  42727. (function (BABYLON) {
  42728. var IntersectionInfo = /** @class */ (function () {
  42729. function IntersectionInfo(bu, bv, distance) {
  42730. this.bu = bu;
  42731. this.bv = bv;
  42732. this.distance = distance;
  42733. this.faceId = 0;
  42734. this.subMeshId = 0;
  42735. }
  42736. return IntersectionInfo;
  42737. }());
  42738. BABYLON.IntersectionInfo = IntersectionInfo;
  42739. var PickingInfo = /** @class */ (function () {
  42740. function PickingInfo() {
  42741. this.hit = false;
  42742. this.distance = 0;
  42743. this.pickedPoint = null;
  42744. this.pickedMesh = null;
  42745. this.bu = 0;
  42746. this.bv = 0;
  42747. this.faceId = -1;
  42748. this.subMeshId = 0;
  42749. this.pickedSprite = null;
  42750. }
  42751. // Methods
  42752. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  42753. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  42754. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  42755. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42756. return null;
  42757. }
  42758. var indices = this.pickedMesh.getIndices();
  42759. if (!indices) {
  42760. return null;
  42761. }
  42762. var result;
  42763. if (useVerticesNormals) {
  42764. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42765. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  42766. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  42767. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  42768. normal0 = normal0.scale(this.bu);
  42769. normal1 = normal1.scale(this.bv);
  42770. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  42771. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  42772. }
  42773. else {
  42774. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42775. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  42776. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  42777. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  42778. var p1p2 = vertex1.subtract(vertex2);
  42779. var p3p2 = vertex3.subtract(vertex2);
  42780. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  42781. }
  42782. if (useWorldCoordinates) {
  42783. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  42784. }
  42785. return BABYLON.Vector3.Normalize(result);
  42786. };
  42787. PickingInfo.prototype.getTextureCoordinates = function () {
  42788. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42789. return null;
  42790. }
  42791. var indices = this.pickedMesh.getIndices();
  42792. if (!indices) {
  42793. return null;
  42794. }
  42795. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42796. if (!uvs) {
  42797. return null;
  42798. }
  42799. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  42800. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  42801. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  42802. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  42803. uv1 = uv1.scale(this.bu);
  42804. uv2 = uv2.scale(this.bv);
  42805. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  42806. };
  42807. return PickingInfo;
  42808. }());
  42809. BABYLON.PickingInfo = PickingInfo;
  42810. })(BABYLON || (BABYLON = {}));
  42811. //# sourceMappingURL=babylon.pickingInfo.js.map
  42812. var BABYLON;
  42813. (function (BABYLON) {
  42814. var Ray = /** @class */ (function () {
  42815. function Ray(origin, direction, length) {
  42816. if (length === void 0) { length = Number.MAX_VALUE; }
  42817. this.origin = origin;
  42818. this.direction = direction;
  42819. this.length = length;
  42820. }
  42821. // Methods
  42822. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  42823. var d = 0.0;
  42824. var maxValue = Number.MAX_VALUE;
  42825. var inv;
  42826. var min;
  42827. var max;
  42828. var temp;
  42829. if (Math.abs(this.direction.x) < 0.0000001) {
  42830. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  42831. return false;
  42832. }
  42833. }
  42834. else {
  42835. inv = 1.0 / this.direction.x;
  42836. min = (minimum.x - this.origin.x) * inv;
  42837. max = (maximum.x - this.origin.x) * inv;
  42838. if (max === -Infinity) {
  42839. max = Infinity;
  42840. }
  42841. if (min > max) {
  42842. temp = min;
  42843. min = max;
  42844. max = temp;
  42845. }
  42846. d = Math.max(min, d);
  42847. maxValue = Math.min(max, maxValue);
  42848. if (d > maxValue) {
  42849. return false;
  42850. }
  42851. }
  42852. if (Math.abs(this.direction.y) < 0.0000001) {
  42853. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  42854. return false;
  42855. }
  42856. }
  42857. else {
  42858. inv = 1.0 / this.direction.y;
  42859. min = (minimum.y - this.origin.y) * inv;
  42860. max = (maximum.y - this.origin.y) * inv;
  42861. if (max === -Infinity) {
  42862. max = Infinity;
  42863. }
  42864. if (min > max) {
  42865. temp = min;
  42866. min = max;
  42867. max = temp;
  42868. }
  42869. d = Math.max(min, d);
  42870. maxValue = Math.min(max, maxValue);
  42871. if (d > maxValue) {
  42872. return false;
  42873. }
  42874. }
  42875. if (Math.abs(this.direction.z) < 0.0000001) {
  42876. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  42877. return false;
  42878. }
  42879. }
  42880. else {
  42881. inv = 1.0 / this.direction.z;
  42882. min = (minimum.z - this.origin.z) * inv;
  42883. max = (maximum.z - this.origin.z) * inv;
  42884. if (max === -Infinity) {
  42885. max = Infinity;
  42886. }
  42887. if (min > max) {
  42888. temp = min;
  42889. min = max;
  42890. max = temp;
  42891. }
  42892. d = Math.max(min, d);
  42893. maxValue = Math.min(max, maxValue);
  42894. if (d > maxValue) {
  42895. return false;
  42896. }
  42897. }
  42898. return true;
  42899. };
  42900. Ray.prototype.intersectsBox = function (box) {
  42901. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  42902. };
  42903. Ray.prototype.intersectsSphere = function (sphere) {
  42904. var x = sphere.center.x - this.origin.x;
  42905. var y = sphere.center.y - this.origin.y;
  42906. var z = sphere.center.z - this.origin.z;
  42907. var pyth = (x * x) + (y * y) + (z * z);
  42908. var rr = sphere.radius * sphere.radius;
  42909. if (pyth <= rr) {
  42910. return true;
  42911. }
  42912. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  42913. if (dot < 0.0) {
  42914. return false;
  42915. }
  42916. var temp = pyth - (dot * dot);
  42917. return temp <= rr;
  42918. };
  42919. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  42920. if (!this._edge1) {
  42921. this._edge1 = BABYLON.Vector3.Zero();
  42922. this._edge2 = BABYLON.Vector3.Zero();
  42923. this._pvec = BABYLON.Vector3.Zero();
  42924. this._tvec = BABYLON.Vector3.Zero();
  42925. this._qvec = BABYLON.Vector3.Zero();
  42926. }
  42927. vertex1.subtractToRef(vertex0, this._edge1);
  42928. vertex2.subtractToRef(vertex0, this._edge2);
  42929. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  42930. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  42931. if (det === 0) {
  42932. return null;
  42933. }
  42934. var invdet = 1 / det;
  42935. this.origin.subtractToRef(vertex0, this._tvec);
  42936. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  42937. if (bu < 0 || bu > 1.0) {
  42938. return null;
  42939. }
  42940. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  42941. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  42942. if (bv < 0 || bu + bv > 1.0) {
  42943. return null;
  42944. }
  42945. //check if the distance is longer than the predefined length.
  42946. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  42947. if (distance > this.length) {
  42948. return null;
  42949. }
  42950. return new BABYLON.IntersectionInfo(bu, bv, distance);
  42951. };
  42952. Ray.prototype.intersectsPlane = function (plane) {
  42953. var distance;
  42954. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  42955. if (Math.abs(result1) < 9.99999997475243E-07) {
  42956. return null;
  42957. }
  42958. else {
  42959. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  42960. distance = (-plane.d - result2) / result1;
  42961. if (distance < 0.0) {
  42962. if (distance < -9.99999997475243E-07) {
  42963. return null;
  42964. }
  42965. else {
  42966. return 0;
  42967. }
  42968. }
  42969. return distance;
  42970. }
  42971. };
  42972. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  42973. var tm = BABYLON.Tmp.Matrix[0];
  42974. mesh.getWorldMatrix().invertToRef(tm);
  42975. if (this._tmpRay) {
  42976. Ray.TransformToRef(this, tm, this._tmpRay);
  42977. }
  42978. else {
  42979. this._tmpRay = Ray.Transform(this, tm);
  42980. }
  42981. return mesh.intersects(this._tmpRay, fastCheck);
  42982. };
  42983. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  42984. if (results) {
  42985. results.length = 0;
  42986. }
  42987. else {
  42988. results = [];
  42989. }
  42990. for (var i = 0; i < meshes.length; i++) {
  42991. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  42992. if (pickInfo.hit) {
  42993. results.push(pickInfo);
  42994. }
  42995. }
  42996. results.sort(this._comparePickingInfo);
  42997. return results;
  42998. };
  42999. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43000. if (pickingInfoA.distance < pickingInfoB.distance) {
  43001. return -1;
  43002. }
  43003. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43004. return 1;
  43005. }
  43006. else {
  43007. return 0;
  43008. }
  43009. };
  43010. /**
  43011. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43012. * @param sega the first point of the segment to test the intersection against
  43013. * @param segb the second point of the segment to test the intersection against
  43014. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43015. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43016. */
  43017. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43018. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43019. var u = segb.subtract(sega);
  43020. var v = rsegb.subtract(this.origin);
  43021. var w = sega.subtract(this.origin);
  43022. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43023. var b = BABYLON.Vector3.Dot(u, v);
  43024. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43025. var d = BABYLON.Vector3.Dot(u, w);
  43026. var e = BABYLON.Vector3.Dot(v, w);
  43027. var D = a * c - b * b; // always >= 0
  43028. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43029. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43030. // compute the line parameters of the two closest points
  43031. if (D < Ray.smallnum) {
  43032. sN = 0.0; // force using point P0 on segment S1
  43033. sD = 1.0; // to prevent possible division by 0.0 later
  43034. tN = e;
  43035. tD = c;
  43036. }
  43037. else {
  43038. sN = (b * e - c * d);
  43039. tN = (a * e - b * d);
  43040. if (sN < 0.0) {
  43041. sN = 0.0;
  43042. tN = e;
  43043. tD = c;
  43044. }
  43045. else if (sN > sD) {
  43046. sN = sD;
  43047. tN = e + b;
  43048. tD = c;
  43049. }
  43050. }
  43051. if (tN < 0.0) {
  43052. tN = 0.0;
  43053. // recompute sc for this edge
  43054. if (-d < 0.0) {
  43055. sN = 0.0;
  43056. }
  43057. else if (-d > a)
  43058. sN = sD;
  43059. else {
  43060. sN = -d;
  43061. sD = a;
  43062. }
  43063. }
  43064. else if (tN > tD) {
  43065. tN = tD;
  43066. // recompute sc for this edge
  43067. if ((-d + b) < 0.0) {
  43068. sN = 0;
  43069. }
  43070. else if ((-d + b) > a) {
  43071. sN = sD;
  43072. }
  43073. else {
  43074. sN = (-d + b);
  43075. sD = a;
  43076. }
  43077. }
  43078. // finally do the division to get sc and tc
  43079. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43080. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43081. // get the difference of the two closest points
  43082. var qtc = v.multiplyByFloats(tc, tc, tc);
  43083. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43084. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43085. if (isIntersected) {
  43086. return qtc.length();
  43087. }
  43088. return -1;
  43089. };
  43090. // Statics
  43091. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43092. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  43093. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  43094. var direction = end.subtract(start);
  43095. direction.normalize();
  43096. return new Ray(start, direction);
  43097. };
  43098. /**
  43099. * 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
  43100. * transformed to the given world matrix.
  43101. * @param origin The origin point
  43102. * @param end The end point
  43103. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43104. */
  43105. Ray.CreateNewFromTo = function (origin, end, world) {
  43106. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43107. var direction = end.subtract(origin);
  43108. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43109. direction.normalize();
  43110. return Ray.Transform(new Ray(origin, direction, length), world);
  43111. };
  43112. Ray.Transform = function (ray, matrix) {
  43113. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43114. Ray.TransformToRef(ray, matrix, result);
  43115. return result;
  43116. };
  43117. Ray.TransformToRef = function (ray, matrix, result) {
  43118. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43119. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43120. result.length = ray.length;
  43121. var dir = result.direction;
  43122. var len = dir.length();
  43123. if (!(len === 0 || len === 1)) {
  43124. var num = 1.0 / len;
  43125. dir.x *= num;
  43126. dir.y *= num;
  43127. dir.z *= num;
  43128. result.length *= len;
  43129. }
  43130. };
  43131. Ray.smallnum = 0.00000001;
  43132. Ray.rayl = 10e8;
  43133. return Ray;
  43134. }());
  43135. BABYLON.Ray = Ray;
  43136. })(BABYLON || (BABYLON = {}));
  43137. //# sourceMappingURL=babylon.ray.js.map
  43138. var BABYLON;
  43139. (function (BABYLON) {
  43140. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43141. if (boxMin.x > sphereCenter.x + sphereRadius)
  43142. return false;
  43143. if (sphereCenter.x - sphereRadius > boxMax.x)
  43144. return false;
  43145. if (boxMin.y > sphereCenter.y + sphereRadius)
  43146. return false;
  43147. if (sphereCenter.y - sphereRadius > boxMax.y)
  43148. return false;
  43149. if (boxMin.z > sphereCenter.z + sphereRadius)
  43150. return false;
  43151. if (sphereCenter.z - sphereRadius > boxMax.z)
  43152. return false;
  43153. return true;
  43154. };
  43155. var getLowestRoot = (function () {
  43156. var result = { root: 0, found: false };
  43157. return function (a, b, c, maxR) {
  43158. result.root = 0;
  43159. result.found = false;
  43160. var determinant = b * b - 4.0 * a * c;
  43161. if (determinant < 0)
  43162. return result;
  43163. var sqrtD = Math.sqrt(determinant);
  43164. var r1 = (-b - sqrtD) / (2.0 * a);
  43165. var r2 = (-b + sqrtD) / (2.0 * a);
  43166. if (r1 > r2) {
  43167. var temp = r2;
  43168. r2 = r1;
  43169. r1 = temp;
  43170. }
  43171. if (r1 > 0 && r1 < maxR) {
  43172. result.root = r1;
  43173. result.found = true;
  43174. return result;
  43175. }
  43176. if (r2 > 0 && r2 < maxR) {
  43177. result.root = r2;
  43178. result.found = true;
  43179. return result;
  43180. }
  43181. return result;
  43182. };
  43183. })();
  43184. var Collider = /** @class */ (function () {
  43185. function Collider() {
  43186. this.radius = BABYLON.Vector3.One();
  43187. this.retry = 0;
  43188. this.basePointWorld = BABYLON.Vector3.Zero();
  43189. this.velocityWorld = BABYLON.Vector3.Zero();
  43190. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43191. this._collisionPoint = BABYLON.Vector3.Zero();
  43192. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43193. this._tempVector = BABYLON.Vector3.Zero();
  43194. this._tempVector2 = BABYLON.Vector3.Zero();
  43195. this._tempVector3 = BABYLON.Vector3.Zero();
  43196. this._tempVector4 = BABYLON.Vector3.Zero();
  43197. this._edge = BABYLON.Vector3.Zero();
  43198. this._baseToVertex = BABYLON.Vector3.Zero();
  43199. this._destinationPoint = BABYLON.Vector3.Zero();
  43200. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43201. this._displacementVector = BABYLON.Vector3.Zero();
  43202. this._collisionMask = -1;
  43203. }
  43204. Object.defineProperty(Collider.prototype, "collisionMask", {
  43205. get: function () {
  43206. return this._collisionMask;
  43207. },
  43208. set: function (mask) {
  43209. this._collisionMask = !isNaN(mask) ? mask : -1;
  43210. },
  43211. enumerable: true,
  43212. configurable: true
  43213. });
  43214. // Methods
  43215. Collider.prototype._initialize = function (source, dir, e) {
  43216. this.velocity = dir;
  43217. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43218. this.basePoint = source;
  43219. source.multiplyToRef(this.radius, this.basePointWorld);
  43220. dir.multiplyToRef(this.radius, this.velocityWorld);
  43221. this.velocityWorldLength = this.velocityWorld.length();
  43222. this.epsilon = e;
  43223. this.collisionFound = false;
  43224. };
  43225. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43226. pa.subtractToRef(point, this._tempVector);
  43227. pb.subtractToRef(point, this._tempVector2);
  43228. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43229. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43230. if (d < 0)
  43231. return false;
  43232. pc.subtractToRef(point, this._tempVector3);
  43233. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43234. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43235. if (d < 0)
  43236. return false;
  43237. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43238. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43239. return d >= 0;
  43240. };
  43241. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43242. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43243. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43244. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43245. return false;
  43246. }
  43247. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43248. return false;
  43249. return true;
  43250. };
  43251. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43252. var t0;
  43253. var embeddedInPlane = false;
  43254. //defensive programming, actually not needed.
  43255. if (!trianglePlaneArray) {
  43256. trianglePlaneArray = [];
  43257. }
  43258. if (!trianglePlaneArray[faceIndex]) {
  43259. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43260. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43261. }
  43262. var trianglePlane = trianglePlaneArray[faceIndex];
  43263. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43264. return;
  43265. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43266. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43267. if (normalDotVelocity == 0) {
  43268. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43269. return;
  43270. embeddedInPlane = true;
  43271. t0 = 0;
  43272. }
  43273. else {
  43274. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43275. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43276. if (t0 > t1) {
  43277. var temp = t1;
  43278. t1 = t0;
  43279. t0 = temp;
  43280. }
  43281. if (t0 > 1.0 || t1 < 0.0)
  43282. return;
  43283. if (t0 < 0)
  43284. t0 = 0;
  43285. if (t0 > 1.0)
  43286. t0 = 1.0;
  43287. }
  43288. this._collisionPoint.copyFromFloats(0, 0, 0);
  43289. var found = false;
  43290. var t = 1.0;
  43291. if (!embeddedInPlane) {
  43292. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43293. this.velocity.scaleToRef(t0, this._tempVector);
  43294. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43295. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43296. found = true;
  43297. t = t0;
  43298. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43299. }
  43300. }
  43301. if (!found) {
  43302. var velocitySquaredLength = this.velocity.lengthSquared();
  43303. var a = velocitySquaredLength;
  43304. this.basePoint.subtractToRef(p1, this._tempVector);
  43305. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43306. var c = this._tempVector.lengthSquared() - 1.0;
  43307. var lowestRoot = getLowestRoot(a, b, c, t);
  43308. if (lowestRoot.found) {
  43309. t = lowestRoot.root;
  43310. found = true;
  43311. this._collisionPoint.copyFrom(p1);
  43312. }
  43313. this.basePoint.subtractToRef(p2, this._tempVector);
  43314. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43315. c = this._tempVector.lengthSquared() - 1.0;
  43316. lowestRoot = getLowestRoot(a, b, c, t);
  43317. if (lowestRoot.found) {
  43318. t = lowestRoot.root;
  43319. found = true;
  43320. this._collisionPoint.copyFrom(p2);
  43321. }
  43322. this.basePoint.subtractToRef(p3, this._tempVector);
  43323. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43324. c = this._tempVector.lengthSquared() - 1.0;
  43325. lowestRoot = getLowestRoot(a, b, c, t);
  43326. if (lowestRoot.found) {
  43327. t = lowestRoot.root;
  43328. found = true;
  43329. this._collisionPoint.copyFrom(p3);
  43330. }
  43331. p2.subtractToRef(p1, this._edge);
  43332. p1.subtractToRef(this.basePoint, this._baseToVertex);
  43333. var edgeSquaredLength = this._edge.lengthSquared();
  43334. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43335. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43336. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43337. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43338. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43339. lowestRoot = getLowestRoot(a, b, c, t);
  43340. if (lowestRoot.found) {
  43341. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43342. if (f >= 0.0 && f <= 1.0) {
  43343. t = lowestRoot.root;
  43344. found = true;
  43345. this._edge.scaleInPlace(f);
  43346. p1.addToRef(this._edge, this._collisionPoint);
  43347. }
  43348. }
  43349. p3.subtractToRef(p2, this._edge);
  43350. p2.subtractToRef(this.basePoint, this._baseToVertex);
  43351. edgeSquaredLength = this._edge.lengthSquared();
  43352. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43353. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43354. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43355. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43356. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43357. lowestRoot = getLowestRoot(a, b, c, t);
  43358. if (lowestRoot.found) {
  43359. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43360. if (f >= 0.0 && f <= 1.0) {
  43361. t = lowestRoot.root;
  43362. found = true;
  43363. this._edge.scaleInPlace(f);
  43364. p2.addToRef(this._edge, this._collisionPoint);
  43365. }
  43366. }
  43367. p1.subtractToRef(p3, this._edge);
  43368. p3.subtractToRef(this.basePoint, this._baseToVertex);
  43369. edgeSquaredLength = this._edge.lengthSquared();
  43370. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43371. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43372. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43373. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43374. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43375. lowestRoot = getLowestRoot(a, b, c, t);
  43376. if (lowestRoot.found) {
  43377. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43378. if (f >= 0.0 && f <= 1.0) {
  43379. t = lowestRoot.root;
  43380. found = true;
  43381. this._edge.scaleInPlace(f);
  43382. p3.addToRef(this._edge, this._collisionPoint);
  43383. }
  43384. }
  43385. }
  43386. if (found) {
  43387. var distToCollision = t * this.velocity.length();
  43388. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  43389. if (!this.intersectionPoint) {
  43390. this.intersectionPoint = this._collisionPoint.clone();
  43391. }
  43392. else {
  43393. this.intersectionPoint.copyFrom(this._collisionPoint);
  43394. }
  43395. this.nearestDistance = distToCollision;
  43396. this.collisionFound = true;
  43397. }
  43398. }
  43399. };
  43400. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  43401. for (var i = indexStart; i < indexEnd; i += 3) {
  43402. var p1 = pts[indices[i] - decal];
  43403. var p2 = pts[indices[i + 1] - decal];
  43404. var p3 = pts[indices[i + 2] - decal];
  43405. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  43406. }
  43407. };
  43408. Collider.prototype._getResponse = function (pos, vel) {
  43409. pos.addToRef(vel, this._destinationPoint);
  43410. vel.scaleInPlace((this.nearestDistance / vel.length()));
  43411. this.basePoint.addToRef(vel, pos);
  43412. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  43413. this._slidePlaneNormal.normalize();
  43414. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  43415. pos.addInPlace(this._displacementVector);
  43416. this.intersectionPoint.addInPlace(this._displacementVector);
  43417. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  43418. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  43419. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  43420. };
  43421. return Collider;
  43422. }());
  43423. BABYLON.Collider = Collider;
  43424. })(BABYLON || (BABYLON = {}));
  43425. //# sourceMappingURL=babylon.collider.js.map
  43426. var BABYLON;
  43427. (function (BABYLON) {
  43428. //WebWorker code will be inserted to this variable.
  43429. BABYLON.CollisionWorker = "";
  43430. var WorkerTaskType;
  43431. (function (WorkerTaskType) {
  43432. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  43433. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  43434. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  43435. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  43436. var WorkerReplyType;
  43437. (function (WorkerReplyType) {
  43438. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  43439. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  43440. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  43441. var CollisionCoordinatorWorker = /** @class */ (function () {
  43442. function CollisionCoordinatorWorker() {
  43443. var _this = this;
  43444. this._scaledPosition = BABYLON.Vector3.Zero();
  43445. this._scaledVelocity = BABYLON.Vector3.Zero();
  43446. this.onMeshUpdated = function (mesh) {
  43447. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  43448. };
  43449. this.onGeometryUpdated = function (geometry) {
  43450. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  43451. };
  43452. this._afterRender = function () {
  43453. if (!_this._init)
  43454. return;
  43455. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  43456. return;
  43457. }
  43458. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  43459. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  43460. if (_this._runningUpdated > 4) {
  43461. return;
  43462. }
  43463. ++_this._runningUpdated;
  43464. var payload = {
  43465. updatedMeshes: _this._addUpdateMeshesList,
  43466. updatedGeometries: _this._addUpdateGeometriesList,
  43467. removedGeometries: _this._toRemoveGeometryArray,
  43468. removedMeshes: _this._toRemoveMeshesArray
  43469. };
  43470. var message = {
  43471. payload: payload,
  43472. taskType: WorkerTaskType.UPDATE
  43473. };
  43474. var serializable = [];
  43475. for (var id in payload.updatedGeometries) {
  43476. if (payload.updatedGeometries.hasOwnProperty(id)) {
  43477. //prepare transferables
  43478. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  43479. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  43480. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  43481. }
  43482. }
  43483. _this._worker.postMessage(message, serializable);
  43484. _this._addUpdateMeshesList = {};
  43485. _this._addUpdateGeometriesList = {};
  43486. _this._toRemoveGeometryArray = [];
  43487. _this._toRemoveMeshesArray = [];
  43488. };
  43489. this._onMessageFromWorker = function (e) {
  43490. var returnData = e.data;
  43491. if (returnData.error != WorkerReplyType.SUCCESS) {
  43492. //TODO what errors can be returned from the worker?
  43493. BABYLON.Tools.Warn("error returned from worker!");
  43494. return;
  43495. }
  43496. switch (returnData.taskType) {
  43497. case WorkerTaskType.INIT:
  43498. _this._init = true;
  43499. //Update the worked with ALL of the scene's current state
  43500. _this._scene.meshes.forEach(function (mesh) {
  43501. _this.onMeshAdded(mesh);
  43502. });
  43503. _this._scene.getGeometries().forEach(function (geometry) {
  43504. _this.onGeometryAdded(geometry);
  43505. });
  43506. break;
  43507. case WorkerTaskType.UPDATE:
  43508. _this._runningUpdated--;
  43509. break;
  43510. case WorkerTaskType.COLLIDE:
  43511. _this._runningCollisionTask = false;
  43512. var returnPayload = returnData.payload;
  43513. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  43514. return;
  43515. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  43516. if (callback) {
  43517. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  43518. if (mesh) {
  43519. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  43520. }
  43521. }
  43522. //cleanup
  43523. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  43524. break;
  43525. }
  43526. };
  43527. this._collisionsCallbackArray = [];
  43528. this._init = false;
  43529. this._runningUpdated = 0;
  43530. this._runningCollisionTask = false;
  43531. this._addUpdateMeshesList = {};
  43532. this._addUpdateGeometriesList = {};
  43533. this._toRemoveGeometryArray = [];
  43534. this._toRemoveMeshesArray = [];
  43535. }
  43536. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43537. if (!this._init)
  43538. return;
  43539. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  43540. return;
  43541. position.divideToRef(collider.radius, this._scaledPosition);
  43542. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43543. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  43544. var payload = {
  43545. collider: {
  43546. position: this._scaledPosition.asArray(),
  43547. velocity: this._scaledVelocity.asArray(),
  43548. radius: collider.radius.asArray()
  43549. },
  43550. collisionId: collisionIndex,
  43551. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43552. maximumRetry: maximumRetry
  43553. };
  43554. var message = {
  43555. payload: payload,
  43556. taskType: WorkerTaskType.COLLIDE
  43557. };
  43558. this._worker.postMessage(message);
  43559. };
  43560. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43561. this._scene = scene;
  43562. this._scene.registerAfterRender(this._afterRender);
  43563. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43564. this._worker = new Worker(workerUrl);
  43565. this._worker.onmessage = this._onMessageFromWorker;
  43566. var message = {
  43567. payload: {},
  43568. taskType: WorkerTaskType.INIT
  43569. };
  43570. this._worker.postMessage(message);
  43571. };
  43572. CollisionCoordinatorWorker.prototype.destroy = function () {
  43573. this._scene.unregisterAfterRender(this._afterRender);
  43574. this._worker.terminate();
  43575. };
  43576. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43577. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43578. this.onMeshUpdated(mesh);
  43579. };
  43580. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43581. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43582. };
  43583. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43584. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43585. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43586. this.onGeometryUpdated(geometry);
  43587. };
  43588. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43589. this._toRemoveGeometryArray.push(geometry.id);
  43590. };
  43591. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43592. var submeshes = [];
  43593. if (mesh.subMeshes) {
  43594. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43595. var boundingInfo = sm.getBoundingInfo();
  43596. return {
  43597. position: idx,
  43598. verticesStart: sm.verticesStart,
  43599. verticesCount: sm.verticesCount,
  43600. indexStart: sm.indexStart,
  43601. indexCount: sm.indexCount,
  43602. hasMaterial: !!sm.getMaterial(),
  43603. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43604. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43605. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43606. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  43607. };
  43608. });
  43609. }
  43610. var geometryId = null;
  43611. if (mesh instanceof BABYLON.Mesh) {
  43612. var geometry = mesh.geometry;
  43613. geometryId = geometry ? geometry.id : null;
  43614. }
  43615. else if (mesh instanceof BABYLON.InstancedMesh) {
  43616. var geometry = mesh.sourceMesh.geometry;
  43617. geometryId = geometry ? geometry.id : null;
  43618. }
  43619. var boundingInfo = mesh.getBoundingInfo();
  43620. return {
  43621. uniqueId: mesh.uniqueId,
  43622. id: mesh.id,
  43623. name: mesh.name,
  43624. geometryId: geometryId,
  43625. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43626. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43627. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43628. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  43629. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43630. subMeshes: submeshes,
  43631. checkCollisions: mesh.checkCollisions
  43632. };
  43633. };
  43634. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43635. return {
  43636. id: geometry.id,
  43637. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43638. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43639. indices: new Uint32Array(geometry.getIndices() || []),
  43640. };
  43641. };
  43642. return CollisionCoordinatorWorker;
  43643. }());
  43644. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43645. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43646. function CollisionCoordinatorLegacy() {
  43647. this._scaledPosition = BABYLON.Vector3.Zero();
  43648. this._scaledVelocity = BABYLON.Vector3.Zero();
  43649. this._finalPosition = BABYLON.Vector3.Zero();
  43650. }
  43651. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43652. position.divideToRef(collider.radius, this._scaledPosition);
  43653. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43654. collider.collidedMesh = null;
  43655. collider.retry = 0;
  43656. collider.initialVelocity = this._scaledVelocity;
  43657. collider.initialPosition = this._scaledPosition;
  43658. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  43659. this._finalPosition.multiplyInPlace(collider.radius);
  43660. //run the callback
  43661. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  43662. };
  43663. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  43664. this._scene = scene;
  43665. };
  43666. CollisionCoordinatorLegacy.prototype.destroy = function () {
  43667. //Legacy need no destruction method.
  43668. };
  43669. //No update in legacy mode
  43670. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  43671. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  43672. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  43673. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  43674. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  43675. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  43676. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  43677. if (excludedMesh === void 0) { excludedMesh = null; }
  43678. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  43679. if (collider.retry >= maximumRetry) {
  43680. finalPosition.copyFrom(position);
  43681. return;
  43682. }
  43683. // Check if this is a mesh else camera or -1
  43684. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  43685. collider._initialize(position, velocity, closeDistance);
  43686. // Check all meshes
  43687. for (var index = 0; index < this._scene.meshes.length; index++) {
  43688. var mesh = this._scene.meshes[index];
  43689. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  43690. mesh._checkCollision(collider);
  43691. }
  43692. }
  43693. if (!collider.collisionFound) {
  43694. position.addToRef(velocity, finalPosition);
  43695. return;
  43696. }
  43697. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  43698. collider._getResponse(position, velocity);
  43699. }
  43700. if (velocity.length() <= closeDistance) {
  43701. finalPosition.copyFrom(position);
  43702. return;
  43703. }
  43704. collider.retry++;
  43705. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  43706. };
  43707. return CollisionCoordinatorLegacy;
  43708. }());
  43709. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  43710. })(BABYLON || (BABYLON = {}));
  43711. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  43712. var BABYLON;
  43713. (function (BABYLON) {
  43714. var Particle = /** @class */ (function () {
  43715. function Particle(particleSystem) {
  43716. this.particleSystem = particleSystem;
  43717. this.position = BABYLON.Vector3.Zero();
  43718. this.direction = BABYLON.Vector3.Zero();
  43719. this.color = new BABYLON.Color4(0, 0, 0, 0);
  43720. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  43721. this.lifeTime = 1.0;
  43722. this.age = 0;
  43723. this.size = 0;
  43724. this.angle = 0;
  43725. this.angularSpeed = 0;
  43726. this._currentFrameCounter = 0;
  43727. this.cellIndex = 0;
  43728. if (!this.particleSystem.isAnimationSheetEnabled) {
  43729. return;
  43730. }
  43731. this.cellIndex = this.particleSystem.startSpriteCellID;
  43732. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  43733. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  43734. }
  43735. else {
  43736. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  43737. }
  43738. }
  43739. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  43740. // (ageOffset / scaledUpdateSpeed) / available cells
  43741. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  43742. this._currentFrameCounter += scaledUpdateSpeed;
  43743. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  43744. this._currentFrameCounter = 0;
  43745. this.cellIndex++;
  43746. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43747. this.cellIndex = this.particleSystem.endSpriteCellID;
  43748. }
  43749. }
  43750. };
  43751. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  43752. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  43753. this.cellIndex++;
  43754. this._currentFrameCounter = 0;
  43755. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43756. if (this.particleSystem.spriteCellLoop) {
  43757. this.cellIndex = this.particleSystem.startSpriteCellID;
  43758. }
  43759. else {
  43760. this.cellIndex = this.particleSystem.endSpriteCellID;
  43761. }
  43762. }
  43763. }
  43764. else {
  43765. this._currentFrameCounter++;
  43766. }
  43767. };
  43768. Particle.prototype.copyTo = function (other) {
  43769. other.position.copyFrom(this.position);
  43770. other.direction.copyFrom(this.direction);
  43771. other.color.copyFrom(this.color);
  43772. other.colorStep.copyFrom(this.colorStep);
  43773. other.lifeTime = this.lifeTime;
  43774. other.age = this.age;
  43775. other.size = this.size;
  43776. other.angle = this.angle;
  43777. other.angularSpeed = this.angularSpeed;
  43778. other.particleSystem = this.particleSystem;
  43779. other.cellIndex = this.cellIndex;
  43780. };
  43781. return Particle;
  43782. }());
  43783. BABYLON.Particle = Particle;
  43784. })(BABYLON || (BABYLON = {}));
  43785. //# sourceMappingURL=babylon.particle.js.map
  43786. var BABYLON;
  43787. (function (BABYLON) {
  43788. var randomNumber = function (min, max) {
  43789. if (min === max) {
  43790. return (min);
  43791. }
  43792. var random = Math.random();
  43793. return ((random * (max - min)) + min);
  43794. };
  43795. var ParticleSystem = /** @class */ (function () {
  43796. // end of sheet animation
  43797. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  43798. if (customEffect === void 0) { customEffect = null; }
  43799. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  43800. if (epsilon === void 0) { epsilon = 0.01; }
  43801. var _this = this;
  43802. this.name = name;
  43803. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  43804. // Members
  43805. this.animations = [];
  43806. this.renderingGroupId = 0;
  43807. this.emitter = null;
  43808. this.emitRate = 10;
  43809. this.manualEmitCount = -1;
  43810. this.updateSpeed = 0.01;
  43811. this.targetStopDuration = 0;
  43812. this.disposeOnStop = false;
  43813. this.minEmitPower = 1;
  43814. this.maxEmitPower = 1;
  43815. this.minLifeTime = 1;
  43816. this.maxLifeTime = 1;
  43817. this.minSize = 1;
  43818. this.maxSize = 1;
  43819. this.minAngularSpeed = 0;
  43820. this.maxAngularSpeed = 0;
  43821. this.layerMask = 0x0FFFFFFF;
  43822. this.customShader = null;
  43823. this.preventAutoStart = false;
  43824. /**
  43825. * An event triggered when the system is disposed.
  43826. * @type {BABYLON.Observable}
  43827. */
  43828. this.onDisposeObservable = new BABYLON.Observable();
  43829. this.onAnimationEnd = null;
  43830. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  43831. this.forceDepthWrite = false;
  43832. this.gravity = BABYLON.Vector3.Zero();
  43833. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  43834. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  43835. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  43836. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43837. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43838. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43839. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  43840. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43841. this.particles = new Array();
  43842. this._stockParticles = new Array();
  43843. this._newPartsExcess = 0;
  43844. this._vertexBuffers = {};
  43845. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  43846. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  43847. this._scaledDirection = BABYLON.Vector3.Zero();
  43848. this._scaledGravity = BABYLON.Vector3.Zero();
  43849. this._currentRenderId = -1;
  43850. this._started = false;
  43851. this._stopped = false;
  43852. this._actualFrame = 0;
  43853. // sheet animation
  43854. this.startSpriteCellID = 0;
  43855. this.endSpriteCellID = 0;
  43856. this.spriteCellLoop = true;
  43857. this.spriteCellChangeSpeed = 0;
  43858. this.spriteCellWidth = 0;
  43859. this.spriteCellHeight = 0;
  43860. this._vertexBufferSize = 11;
  43861. this.appendParticleVertexes = null;
  43862. this.id = name;
  43863. this._capacity = capacity;
  43864. this._epsilon = epsilon;
  43865. if (_isAnimationSheetEnabled) {
  43866. this._vertexBufferSize = 12;
  43867. }
  43868. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43869. this._customEffect = customEffect;
  43870. scene.particleSystems.push(this);
  43871. this._createIndexBuffer();
  43872. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  43873. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  43874. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  43875. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  43876. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  43877. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  43878. if (this._isAnimationSheetEnabled) {
  43879. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  43880. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  43881. }
  43882. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43883. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43884. this._vertexBuffers["options"] = options;
  43885. // Default behaviors
  43886. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  43887. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  43888. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  43889. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  43890. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  43891. };
  43892. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  43893. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  43894. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  43895. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  43896. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  43897. };
  43898. this.updateFunction = function (particles) {
  43899. for (var index = 0; index < particles.length; index++) {
  43900. var particle = particles[index];
  43901. particle.age += _this._scaledUpdateSpeed;
  43902. if (particle.age >= particle.lifeTime) {
  43903. _this.recycleParticle(particle);
  43904. index--;
  43905. continue;
  43906. }
  43907. else {
  43908. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  43909. particle.color.addInPlace(_this._scaledColorStep);
  43910. if (particle.color.a < 0)
  43911. particle.color.a = 0;
  43912. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  43913. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  43914. particle.position.addInPlace(_this._scaledDirection);
  43915. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  43916. particle.direction.addInPlace(_this._scaledGravity);
  43917. if (_this._isAnimationSheetEnabled) {
  43918. particle.updateCellIndex(_this._scaledUpdateSpeed);
  43919. }
  43920. }
  43921. }
  43922. };
  43923. }
  43924. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  43925. set: function (callback) {
  43926. if (this._onDisposeObserver) {
  43927. this.onDisposeObservable.remove(this._onDisposeObserver);
  43928. }
  43929. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43930. },
  43931. enumerable: true,
  43932. configurable: true
  43933. });
  43934. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  43935. get: function () {
  43936. return this._isAnimationSheetEnabled;
  43937. },
  43938. enumerable: true,
  43939. configurable: true
  43940. });
  43941. ParticleSystem.prototype._createIndexBuffer = function () {
  43942. var indices = [];
  43943. var index = 0;
  43944. for (var count = 0; count < this._capacity; count++) {
  43945. indices.push(index);
  43946. indices.push(index + 1);
  43947. indices.push(index + 2);
  43948. indices.push(index);
  43949. indices.push(index + 2);
  43950. indices.push(index + 3);
  43951. index += 4;
  43952. }
  43953. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  43954. };
  43955. ParticleSystem.prototype.recycleParticle = function (particle) {
  43956. var lastParticle = this.particles.pop();
  43957. if (lastParticle !== particle) {
  43958. lastParticle.copyTo(particle);
  43959. this._stockParticles.push(lastParticle);
  43960. }
  43961. };
  43962. ParticleSystem.prototype.getCapacity = function () {
  43963. return this._capacity;
  43964. };
  43965. ParticleSystem.prototype.isAlive = function () {
  43966. return this._alive;
  43967. };
  43968. ParticleSystem.prototype.isStarted = function () {
  43969. return this._started;
  43970. };
  43971. ParticleSystem.prototype.start = function () {
  43972. this._started = true;
  43973. this._stopped = false;
  43974. this._actualFrame = 0;
  43975. };
  43976. ParticleSystem.prototype.stop = function () {
  43977. this._stopped = true;
  43978. };
  43979. // animation sheet
  43980. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  43981. var offset = index * this._vertexBufferSize;
  43982. this._vertexData[offset] = particle.position.x;
  43983. this._vertexData[offset + 1] = particle.position.y;
  43984. this._vertexData[offset + 2] = particle.position.z;
  43985. this._vertexData[offset + 3] = particle.color.r;
  43986. this._vertexData[offset + 4] = particle.color.g;
  43987. this._vertexData[offset + 5] = particle.color.b;
  43988. this._vertexData[offset + 6] = particle.color.a;
  43989. this._vertexData[offset + 7] = particle.angle;
  43990. this._vertexData[offset + 8] = particle.size;
  43991. this._vertexData[offset + 9] = offsetX;
  43992. this._vertexData[offset + 10] = offsetY;
  43993. };
  43994. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  43995. if (offsetX === 0)
  43996. offsetX = this._epsilon;
  43997. else if (offsetX === 1)
  43998. offsetX = 1 - this._epsilon;
  43999. if (offsetY === 0)
  44000. offsetY = this._epsilon;
  44001. else if (offsetY === 1)
  44002. offsetY = 1 - this._epsilon;
  44003. var offset = index * this._vertexBufferSize;
  44004. this._vertexData[offset] = particle.position.x;
  44005. this._vertexData[offset + 1] = particle.position.y;
  44006. this._vertexData[offset + 2] = particle.position.z;
  44007. this._vertexData[offset + 3] = particle.color.r;
  44008. this._vertexData[offset + 4] = particle.color.g;
  44009. this._vertexData[offset + 5] = particle.color.b;
  44010. this._vertexData[offset + 6] = particle.color.a;
  44011. this._vertexData[offset + 7] = particle.angle;
  44012. this._vertexData[offset + 8] = particle.size;
  44013. this._vertexData[offset + 9] = offsetX;
  44014. this._vertexData[offset + 10] = offsetY;
  44015. this._vertexData[offset + 11] = particle.cellIndex;
  44016. };
  44017. ParticleSystem.prototype._update = function (newParticles) {
  44018. // Update current
  44019. this._alive = this.particles.length > 0;
  44020. this.updateFunction(this.particles);
  44021. // Add new ones
  44022. var worldMatrix;
  44023. if (this.emitter.position) {
  44024. var emitterMesh = this.emitter;
  44025. worldMatrix = emitterMesh.getWorldMatrix();
  44026. }
  44027. else {
  44028. var emitterPosition = this.emitter;
  44029. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44030. }
  44031. var particle;
  44032. for (var index = 0; index < newParticles; index++) {
  44033. if (this.particles.length === this._capacity) {
  44034. break;
  44035. }
  44036. if (this._stockParticles.length !== 0) {
  44037. particle = this._stockParticles.pop();
  44038. particle.age = 0;
  44039. particle.cellIndex = this.startSpriteCellID;
  44040. }
  44041. else {
  44042. particle = new BABYLON.Particle(this);
  44043. }
  44044. this.particles.push(particle);
  44045. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44046. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44047. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44048. particle.size = randomNumber(this.minSize, this.maxSize);
  44049. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44050. this.startPositionFunction(worldMatrix, particle.position, particle);
  44051. var step = randomNumber(0, 1.0);
  44052. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44053. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44054. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44055. }
  44056. };
  44057. ParticleSystem.prototype._getEffect = function () {
  44058. if (this._customEffect) {
  44059. return this._customEffect;
  44060. }
  44061. ;
  44062. var defines = [];
  44063. if (this._scene.clipPlane) {
  44064. defines.push("#define CLIPPLANE");
  44065. }
  44066. if (this._isAnimationSheetEnabled) {
  44067. defines.push("#define ANIMATESHEET");
  44068. }
  44069. // Effect
  44070. var join = defines.join("\n");
  44071. if (this._cachedDefines !== join) {
  44072. this._cachedDefines = join;
  44073. var attributesNamesOrOptions;
  44074. var effectCreationOption;
  44075. if (this._isAnimationSheetEnabled) {
  44076. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44077. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44078. }
  44079. else {
  44080. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44081. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44082. }
  44083. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44084. }
  44085. return this._effect;
  44086. };
  44087. ParticleSystem.prototype.animate = function () {
  44088. if (!this._started)
  44089. return;
  44090. var effect = this._getEffect();
  44091. // Check
  44092. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44093. return;
  44094. if (this._currentRenderId === this._scene.getRenderId()) {
  44095. return;
  44096. }
  44097. this._currentRenderId = this._scene.getRenderId();
  44098. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44099. // determine the number of particles we need to create
  44100. var newParticles;
  44101. if (this.manualEmitCount > -1) {
  44102. newParticles = this.manualEmitCount;
  44103. this._newPartsExcess = 0;
  44104. this.manualEmitCount = 0;
  44105. }
  44106. else {
  44107. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44108. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44109. }
  44110. if (this._newPartsExcess > 1.0) {
  44111. newParticles += this._newPartsExcess >> 0;
  44112. this._newPartsExcess -= this._newPartsExcess >> 0;
  44113. }
  44114. this._alive = false;
  44115. if (!this._stopped) {
  44116. this._actualFrame += this._scaledUpdateSpeed;
  44117. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44118. this.stop();
  44119. }
  44120. else {
  44121. newParticles = 0;
  44122. }
  44123. this._update(newParticles);
  44124. // Stopped?
  44125. if (this._stopped) {
  44126. if (!this._alive) {
  44127. this._started = false;
  44128. if (this.onAnimationEnd) {
  44129. this.onAnimationEnd();
  44130. }
  44131. if (this.disposeOnStop) {
  44132. this._scene._toBeDisposed.push(this);
  44133. }
  44134. }
  44135. }
  44136. // Animation sheet
  44137. if (this._isAnimationSheetEnabled) {
  44138. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44139. }
  44140. else {
  44141. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44142. }
  44143. // Update VBO
  44144. var offset = 0;
  44145. for (var index = 0; index < this.particles.length; index++) {
  44146. var particle = this.particles[index];
  44147. this.appendParticleVertexes(offset, particle);
  44148. offset += 4;
  44149. }
  44150. if (this._vertexBuffer) {
  44151. this._vertexBuffer.update(this._vertexData);
  44152. }
  44153. };
  44154. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44155. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44156. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44157. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44158. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44159. };
  44160. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44161. this._appendParticleVertex(offset++, particle, 0, 0);
  44162. this._appendParticleVertex(offset++, particle, 1, 0);
  44163. this._appendParticleVertex(offset++, particle, 1, 1);
  44164. this._appendParticleVertex(offset++, particle, 0, 1);
  44165. };
  44166. ParticleSystem.prototype.rebuild = function () {
  44167. this._createIndexBuffer();
  44168. if (this._vertexBuffer) {
  44169. this._vertexBuffer._rebuild();
  44170. }
  44171. };
  44172. ParticleSystem.prototype.render = function () {
  44173. var effect = this._getEffect();
  44174. // Check
  44175. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44176. return 0;
  44177. var engine = this._scene.getEngine();
  44178. // Render
  44179. engine.enableEffect(effect);
  44180. engine.setState(false);
  44181. var viewMatrix = this._scene.getViewMatrix();
  44182. effect.setTexture("diffuseSampler", this.particleTexture);
  44183. effect.setMatrix("view", viewMatrix);
  44184. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44185. if (this._isAnimationSheetEnabled) {
  44186. var baseSize = this.particleTexture.getBaseSize();
  44187. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44188. }
  44189. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44190. if (this._scene.clipPlane) {
  44191. var clipPlane = this._scene.clipPlane;
  44192. var invView = viewMatrix.clone();
  44193. invView.invert();
  44194. effect.setMatrix("invView", invView);
  44195. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44196. }
  44197. // VBOs
  44198. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44199. // Draw order
  44200. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44201. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44202. }
  44203. else {
  44204. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44205. }
  44206. if (this.forceDepthWrite) {
  44207. engine.setDepthWrite(true);
  44208. }
  44209. engine.draw(true, 0, this.particles.length * 6);
  44210. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44211. return this.particles.length;
  44212. };
  44213. ParticleSystem.prototype.dispose = function () {
  44214. if (this._vertexBuffer) {
  44215. this._vertexBuffer.dispose();
  44216. this._vertexBuffer = null;
  44217. }
  44218. if (this._indexBuffer) {
  44219. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44220. this._indexBuffer = null;
  44221. }
  44222. if (this.particleTexture) {
  44223. this.particleTexture.dispose();
  44224. this.particleTexture = null;
  44225. }
  44226. // Remove from scene
  44227. var index = this._scene.particleSystems.indexOf(this);
  44228. if (index > -1) {
  44229. this._scene.particleSystems.splice(index, 1);
  44230. }
  44231. // Callback
  44232. this.onDisposeObservable.notifyObservers(this);
  44233. this.onDisposeObservable.clear();
  44234. };
  44235. // Clone
  44236. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44237. var custom = null;
  44238. var program = null;
  44239. if (this.customShader != null) {
  44240. program = this.customShader;
  44241. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44242. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44243. }
  44244. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44245. result.customShader = program;
  44246. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44247. if (newEmitter === undefined) {
  44248. newEmitter = this.emitter;
  44249. }
  44250. result.emitter = newEmitter;
  44251. if (this.particleTexture) {
  44252. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44253. }
  44254. if (!this.preventAutoStart) {
  44255. result.start();
  44256. }
  44257. return result;
  44258. };
  44259. ParticleSystem.prototype.serialize = function () {
  44260. var serializationObject = {};
  44261. serializationObject.name = this.name;
  44262. serializationObject.id = this.id;
  44263. // Emitter
  44264. if (this.emitter.position) {
  44265. var emitterMesh = this.emitter;
  44266. serializationObject.emitterId = emitterMesh.id;
  44267. }
  44268. else {
  44269. var emitterPosition = this.emitter;
  44270. serializationObject.emitter = emitterPosition.asArray();
  44271. }
  44272. serializationObject.capacity = this.getCapacity();
  44273. if (this.particleTexture) {
  44274. serializationObject.textureName = this.particleTexture.name;
  44275. }
  44276. // Animations
  44277. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44278. // Particle system
  44279. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44280. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44281. serializationObject.minSize = this.minSize;
  44282. serializationObject.maxSize = this.maxSize;
  44283. serializationObject.minEmitPower = this.minEmitPower;
  44284. serializationObject.maxEmitPower = this.maxEmitPower;
  44285. serializationObject.minLifeTime = this.minLifeTime;
  44286. serializationObject.maxLifeTime = this.maxLifeTime;
  44287. serializationObject.emitRate = this.emitRate;
  44288. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44289. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44290. serializationObject.gravity = this.gravity.asArray();
  44291. serializationObject.direction1 = this.direction1.asArray();
  44292. serializationObject.direction2 = this.direction2.asArray();
  44293. serializationObject.color1 = this.color1.asArray();
  44294. serializationObject.color2 = this.color2.asArray();
  44295. serializationObject.colorDead = this.colorDead.asArray();
  44296. serializationObject.updateSpeed = this.updateSpeed;
  44297. serializationObject.targetStopDuration = this.targetStopDuration;
  44298. serializationObject.textureMask = this.textureMask.asArray();
  44299. serializationObject.blendMode = this.blendMode;
  44300. serializationObject.customShader = this.customShader;
  44301. serializationObject.preventAutoStart = this.preventAutoStart;
  44302. return serializationObject;
  44303. };
  44304. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44305. var name = parsedParticleSystem.name;
  44306. var custom = null;
  44307. var program = null;
  44308. if (parsedParticleSystem.customShader) {
  44309. program = parsedParticleSystem.customShader;
  44310. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44311. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44312. }
  44313. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44314. particleSystem.customShader = program;
  44315. if (parsedParticleSystem.id) {
  44316. particleSystem.id = parsedParticleSystem.id;
  44317. }
  44318. // Auto start
  44319. if (parsedParticleSystem.preventAutoStart) {
  44320. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44321. }
  44322. // Texture
  44323. if (parsedParticleSystem.textureName) {
  44324. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  44325. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  44326. }
  44327. // Emitter
  44328. if (parsedParticleSystem.emitterId) {
  44329. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  44330. }
  44331. else {
  44332. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  44333. }
  44334. // Animations
  44335. if (parsedParticleSystem.animations) {
  44336. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  44337. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  44338. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44339. }
  44340. }
  44341. if (parsedParticleSystem.autoAnimate) {
  44342. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  44343. }
  44344. // Particle system
  44345. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  44346. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  44347. particleSystem.minSize = parsedParticleSystem.minSize;
  44348. particleSystem.maxSize = parsedParticleSystem.maxSize;
  44349. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  44350. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  44351. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  44352. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  44353. particleSystem.emitRate = parsedParticleSystem.emitRate;
  44354. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  44355. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  44356. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  44357. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  44358. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  44359. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  44360. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  44361. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  44362. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  44363. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  44364. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  44365. particleSystem.blendMode = parsedParticleSystem.blendMode;
  44366. if (!particleSystem.preventAutoStart) {
  44367. particleSystem.start();
  44368. }
  44369. return particleSystem;
  44370. };
  44371. // Statics
  44372. ParticleSystem.BLENDMODE_ONEONE = 0;
  44373. ParticleSystem.BLENDMODE_STANDARD = 1;
  44374. return ParticleSystem;
  44375. }());
  44376. BABYLON.ParticleSystem = ParticleSystem;
  44377. })(BABYLON || (BABYLON = {}));
  44378. //# sourceMappingURL=babylon.particleSystem.js.map
  44379. var BABYLON;
  44380. (function (BABYLON) {
  44381. var SolidParticle = /** @class */ (function () {
  44382. /**
  44383. * Creates a Solid Particle object.
  44384. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  44385. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  44386. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  44387. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  44388. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  44389. * `shapeId` (integer) is the model shape identifier in the SPS.
  44390. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  44391. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  44392. */
  44393. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  44394. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  44395. this.idx = 0; // particle global index
  44396. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  44397. this.position = BABYLON.Vector3.Zero(); // position
  44398. this.rotation = BABYLON.Vector3.Zero(); // rotation
  44399. this.scaling = BABYLON.Vector3.One(); // scaling
  44400. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  44401. this.velocity = BABYLON.Vector3.Zero(); // velocity
  44402. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  44403. this.alive = true; // alive
  44404. this.isVisible = true; // visibility
  44405. this._pos = 0; // index of this particle in the global "positions" array
  44406. this._ind = 0; // index of this particle in the global "indices" array
  44407. this.shapeId = 0; // model shape id
  44408. this.idxInShape = 0; // index of the particle in its shape id
  44409. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  44410. this.idx = particleIndex;
  44411. this._pos = positionIndex;
  44412. this._ind = indiceIndex;
  44413. this._model = model;
  44414. this.shapeId = shapeId;
  44415. this.idxInShape = idxInShape;
  44416. this._sps = sps;
  44417. if (modelBoundingInfo) {
  44418. this._modelBoundingInfo = modelBoundingInfo;
  44419. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  44420. }
  44421. }
  44422. Object.defineProperty(SolidParticle.prototype, "scale", {
  44423. /**
  44424. * legacy support, changed scale to scaling
  44425. */
  44426. get: function () {
  44427. return this.scaling;
  44428. },
  44429. set: function (scale) {
  44430. this.scaling = scale;
  44431. },
  44432. enumerable: true,
  44433. configurable: true
  44434. });
  44435. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  44436. /**
  44437. * legacy support, changed quaternion to rotationQuaternion
  44438. */
  44439. get: function () {
  44440. return this.rotationQuaternion;
  44441. },
  44442. set: function (q) {
  44443. this.rotationQuaternion = q;
  44444. },
  44445. enumerable: true,
  44446. configurable: true
  44447. });
  44448. /**
  44449. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  44450. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  44451. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  44452. */
  44453. SolidParticle.prototype.intersectsMesh = function (target) {
  44454. if (!this._boundingInfo || !target._boundingInfo) {
  44455. return false;
  44456. }
  44457. if (this._sps._bSphereOnly) {
  44458. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  44459. }
  44460. return this._boundingInfo.intersects(target._boundingInfo, false);
  44461. };
  44462. return SolidParticle;
  44463. }());
  44464. BABYLON.SolidParticle = SolidParticle;
  44465. var ModelShape = /** @class */ (function () {
  44466. /**
  44467. * 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.
  44468. * SPS internal tool, don't use it manually.
  44469. */
  44470. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  44471. this._indicesLength = 0; // length of the shape in the model indices array
  44472. this.shapeID = id;
  44473. this._shape = shape;
  44474. this._indicesLength = indicesLength;
  44475. this._shapeUV = shapeUV;
  44476. this._positionFunction = posFunction;
  44477. this._vertexFunction = vtxFunction;
  44478. }
  44479. return ModelShape;
  44480. }());
  44481. BABYLON.ModelShape = ModelShape;
  44482. var DepthSortedParticle = /** @class */ (function () {
  44483. function DepthSortedParticle() {
  44484. this.ind = 0; // index of the particle in the "indices" array
  44485. this.indicesLength = 0; // length of the particle shape in the "indices" array
  44486. this.sqDistance = 0.0; // squared distance from the particle to the camera
  44487. }
  44488. return DepthSortedParticle;
  44489. }());
  44490. BABYLON.DepthSortedParticle = DepthSortedParticle;
  44491. })(BABYLON || (BABYLON = {}));
  44492. //# sourceMappingURL=babylon.solidParticle.js.map
  44493. var BABYLON;
  44494. (function (BABYLON) {
  44495. /**
  44496. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  44497. */
  44498. var SolidParticleSystem = /** @class */ (function () {
  44499. /**
  44500. * Creates a SPS (Solid Particle System) object.
  44501. * `name` (String) is the SPS name, this will be the underlying mesh name.
  44502. * `scene` (Scene) is the scene in which the SPS is added.
  44503. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  44504. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  44505. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  44506. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  44507. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  44508. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  44509. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  44510. */
  44511. function SolidParticleSystem(name, scene, options) {
  44512. // public members
  44513. /**
  44514. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  44515. * Example : var p = SPS.particles[i];
  44516. */
  44517. this.particles = new Array();
  44518. /**
  44519. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  44520. */
  44521. this.nbParticles = 0;
  44522. /**
  44523. * If the particles must ever face the camera (default false). Useful for planar particles.
  44524. */
  44525. this.billboard = false;
  44526. /**
  44527. * Recompute normals when adding a shape
  44528. */
  44529. this.recomputeNormals = true;
  44530. /**
  44531. * This a counter ofr your own usage. It's not set by any SPS functions.
  44532. */
  44533. this.counter = 0;
  44534. /**
  44535. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  44536. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  44537. */
  44538. this.vars = {};
  44539. this._positions = new Array();
  44540. this._indices = new Array();
  44541. this._normals = new Array();
  44542. this._colors = new Array();
  44543. this._uvs = new Array();
  44544. this._index = 0; // indices index
  44545. this._updatable = true;
  44546. this._pickable = false;
  44547. this._isVisibilityBoxLocked = false;
  44548. this._alwaysVisible = false;
  44549. this._depthSort = false;
  44550. this._shapeCounter = 0;
  44551. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  44552. this._color = new BABYLON.Color4(0, 0, 0, 0);
  44553. this._computeParticleColor = true;
  44554. this._computeParticleTexture = true;
  44555. this._computeParticleRotation = true;
  44556. this._computeParticleVertex = false;
  44557. this._computeBoundingBox = false;
  44558. this._depthSortParticles = true;
  44559. this._cam_axisZ = BABYLON.Vector3.Zero();
  44560. this._cam_axisY = BABYLON.Vector3.Zero();
  44561. this._cam_axisX = BABYLON.Vector3.Zero();
  44562. this._axisZ = BABYLON.Axis.Z;
  44563. this._camDir = BABYLON.Vector3.Zero();
  44564. this._camInvertedPosition = BABYLON.Vector3.Zero();
  44565. this._rotMatrix = new BABYLON.Matrix();
  44566. this._invertMatrix = new BABYLON.Matrix();
  44567. this._rotated = BABYLON.Vector3.Zero();
  44568. this._quaternion = new BABYLON.Quaternion();
  44569. this._vertex = BABYLON.Vector3.Zero();
  44570. this._normal = BABYLON.Vector3.Zero();
  44571. this._yaw = 0.0;
  44572. this._pitch = 0.0;
  44573. this._roll = 0.0;
  44574. this._halfroll = 0.0;
  44575. this._halfpitch = 0.0;
  44576. this._halfyaw = 0.0;
  44577. this._sinRoll = 0.0;
  44578. this._cosRoll = 0.0;
  44579. this._sinPitch = 0.0;
  44580. this._cosPitch = 0.0;
  44581. this._sinYaw = 0.0;
  44582. this._cosYaw = 0.0;
  44583. this._mustUnrotateFixedNormals = false;
  44584. this._minimum = BABYLON.Tmp.Vector3[0];
  44585. this._maximum = BABYLON.Tmp.Vector3[1];
  44586. this._minBbox = BABYLON.Tmp.Vector3[4];
  44587. this._maxBbox = BABYLON.Tmp.Vector3[5];
  44588. this._particlesIntersect = false;
  44589. this._depthSortFunction = function (p1, p2) {
  44590. return (p2.sqDistance - p1.sqDistance);
  44591. };
  44592. this._needs32Bits = false;
  44593. this._bSphereOnly = false;
  44594. this._bSphereRadiusFactor = 1.0;
  44595. this.name = name;
  44596. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44597. this._camera = scene.activeCamera;
  44598. this._pickable = options ? options.isPickable : false;
  44599. this._depthSort = options ? options.enableDepthSort : false;
  44600. this._particlesIntersect = options ? options.particleIntersection : false;
  44601. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  44602. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  44603. if (options && options.updatable) {
  44604. this._updatable = options.updatable;
  44605. }
  44606. else {
  44607. this._updatable = true;
  44608. }
  44609. if (this._pickable) {
  44610. this.pickedParticles = [];
  44611. }
  44612. if (this._depthSort) {
  44613. this.depthSortedParticles = [];
  44614. }
  44615. }
  44616. /**
  44617. * Builds the SPS underlying mesh. Returns a standard Mesh.
  44618. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  44619. */
  44620. SolidParticleSystem.prototype.buildMesh = function () {
  44621. if (this.nbParticles === 0) {
  44622. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  44623. this.addShape(triangle, 1);
  44624. triangle.dispose();
  44625. }
  44626. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  44627. this._positions32 = new Float32Array(this._positions);
  44628. this._uvs32 = new Float32Array(this._uvs);
  44629. this._colors32 = new Float32Array(this._colors);
  44630. if (this.recomputeNormals) {
  44631. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  44632. }
  44633. this._normals32 = new Float32Array(this._normals);
  44634. this._fixedNormal32 = new Float32Array(this._normals);
  44635. if (this._mustUnrotateFixedNormals) {
  44636. this._unrotateFixedNormals();
  44637. }
  44638. var vertexData = new BABYLON.VertexData();
  44639. vertexData.indices = this._indices32;
  44640. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  44641. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  44642. if (this._uvs32) {
  44643. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  44644. ;
  44645. }
  44646. if (this._colors32) {
  44647. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  44648. }
  44649. var mesh = new BABYLON.Mesh(this.name, this._scene);
  44650. vertexData.applyToMesh(mesh, this._updatable);
  44651. this.mesh = mesh;
  44652. this.mesh.isPickable = this._pickable;
  44653. // free memory
  44654. if (!this._depthSort) {
  44655. this._indices = null;
  44656. }
  44657. this._positions = null;
  44658. this._normals = null;
  44659. this._uvs = null;
  44660. this._colors = null;
  44661. if (!this._updatable) {
  44662. this.particles.length = 0;
  44663. }
  44664. return mesh;
  44665. };
  44666. /**
  44667. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  44668. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  44669. * Thus the particles generated from `digest()` have their property `position` set yet.
  44670. * `mesh` ( Mesh ) is the mesh to be digested
  44671. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  44672. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  44673. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  44674. */
  44675. SolidParticleSystem.prototype.digest = function (mesh, options) {
  44676. var size = (options && options.facetNb) || 1;
  44677. var number = (options && options.number) || 0;
  44678. var delta = (options && options.delta) || 0;
  44679. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44680. var meshInd = mesh.getIndices();
  44681. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44682. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44683. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44684. var f = 0; // facet counter
  44685. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  44686. // compute size from number
  44687. if (number) {
  44688. number = (number > totalFacets) ? totalFacets : number;
  44689. size = Math.round(totalFacets / number);
  44690. delta = 0;
  44691. }
  44692. else {
  44693. size = (size > totalFacets) ? totalFacets : size;
  44694. }
  44695. var facetPos = []; // submesh positions
  44696. var facetInd = []; // submesh indices
  44697. var facetUV = []; // submesh UV
  44698. var facetCol = []; // submesh colors
  44699. var barycenter = BABYLON.Tmp.Vector3[0];
  44700. var sizeO = size;
  44701. while (f < totalFacets) {
  44702. size = sizeO + Math.floor((1 + delta) * Math.random());
  44703. if (f > totalFacets - size) {
  44704. size = totalFacets - f;
  44705. }
  44706. // reset temp arrays
  44707. facetPos.length = 0;
  44708. facetInd.length = 0;
  44709. facetUV.length = 0;
  44710. facetCol.length = 0;
  44711. // iterate over "size" facets
  44712. var fi = 0;
  44713. for (var j = f * 3; j < (f + size) * 3; j++) {
  44714. facetInd.push(fi);
  44715. var i = meshInd[j];
  44716. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  44717. if (meshUV) {
  44718. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  44719. }
  44720. if (meshCol) {
  44721. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  44722. }
  44723. fi++;
  44724. }
  44725. // create a model shape for each single particle
  44726. var idx = this.nbParticles;
  44727. var shape = this._posToShape(facetPos);
  44728. var shapeUV = this._uvsToShapeUV(facetUV);
  44729. // compute the barycenter of the shape
  44730. var v;
  44731. for (v = 0; v < shape.length; v++) {
  44732. barycenter.addInPlace(shape[v]);
  44733. }
  44734. barycenter.scaleInPlace(1 / shape.length);
  44735. // shift the shape from its barycenter to the origin
  44736. for (v = 0; v < shape.length; v++) {
  44737. shape[v].subtractInPlace(barycenter);
  44738. }
  44739. var bInfo;
  44740. if (this._particlesIntersect) {
  44741. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  44742. }
  44743. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  44744. // add the particle in the SPS
  44745. var currentPos = this._positions.length;
  44746. var currentInd = this._indices.length;
  44747. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  44748. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  44749. // initialize the particle position
  44750. this.particles[this.nbParticles].position.addInPlace(barycenter);
  44751. this._index += shape.length;
  44752. idx++;
  44753. this.nbParticles++;
  44754. this._shapeCounter++;
  44755. f += size;
  44756. }
  44757. return this;
  44758. };
  44759. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  44760. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  44761. var index = 0;
  44762. var idx = 0;
  44763. for (var p = 0; p < this.particles.length; p++) {
  44764. this._particle = this.particles[p];
  44765. this._shape = this._particle._model._shape;
  44766. if (this._particle.rotationQuaternion) {
  44767. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44768. }
  44769. else {
  44770. this._yaw = this._particle.rotation.y;
  44771. this._pitch = this._particle.rotation.x;
  44772. this._roll = this._particle.rotation.z;
  44773. this._quaternionRotationYPR();
  44774. }
  44775. this._quaternionToRotationMatrix();
  44776. this._rotMatrix.invertToRef(this._invertMatrix);
  44777. for (var pt = 0; pt < this._shape.length; pt++) {
  44778. idx = index + pt * 3;
  44779. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  44780. this._fixedNormal32[idx] = this._normal.x;
  44781. this._fixedNormal32[idx + 1] = this._normal.y;
  44782. this._fixedNormal32[idx + 2] = this._normal.z;
  44783. }
  44784. index = idx + 3;
  44785. }
  44786. };
  44787. //reset copy
  44788. SolidParticleSystem.prototype._resetCopy = function () {
  44789. this._copy.position.x = 0;
  44790. this._copy.position.y = 0;
  44791. this._copy.position.z = 0;
  44792. this._copy.rotation.x = 0;
  44793. this._copy.rotation.y = 0;
  44794. this._copy.rotation.z = 0;
  44795. this._copy.rotationQuaternion = null;
  44796. this._copy.scaling.x = 1.0;
  44797. this._copy.scaling.y = 1.0;
  44798. this._copy.scaling.z = 1.0;
  44799. this._copy.uvs.x = 0;
  44800. this._copy.uvs.y = 0;
  44801. this._copy.uvs.z = 1.0;
  44802. this._copy.uvs.w = 1.0;
  44803. this._copy.color = null;
  44804. };
  44805. // _meshBuilder : inserts the shape model in the global SPS mesh
  44806. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  44807. var i;
  44808. var u = 0;
  44809. var c = 0;
  44810. var n = 0;
  44811. this._resetCopy();
  44812. if (options && options.positionFunction) {
  44813. options.positionFunction(this._copy, idx, idxInShape);
  44814. this._mustUnrotateFixedNormals = true;
  44815. }
  44816. if (this._copy.rotationQuaternion) {
  44817. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44818. }
  44819. else {
  44820. this._yaw = this._copy.rotation.y;
  44821. this._pitch = this._copy.rotation.x;
  44822. this._roll = this._copy.rotation.z;
  44823. this._quaternionRotationYPR();
  44824. }
  44825. this._quaternionToRotationMatrix();
  44826. for (i = 0; i < shape.length; i++) {
  44827. this._vertex.x = shape[i].x;
  44828. this._vertex.y = shape[i].y;
  44829. this._vertex.z = shape[i].z;
  44830. if (options && options.vertexFunction) {
  44831. options.vertexFunction(this._copy, this._vertex, i);
  44832. }
  44833. this._vertex.x *= this._copy.scaling.x;
  44834. this._vertex.y *= this._copy.scaling.y;
  44835. this._vertex.z *= this._copy.scaling.z;
  44836. this._vertex.x += this._copy.pivot.x;
  44837. this._vertex.y += this._copy.pivot.y;
  44838. this._vertex.z += this._copy.pivot.z;
  44839. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44840. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  44841. if (meshUV) {
  44842. 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);
  44843. u += 2;
  44844. }
  44845. if (this._copy.color) {
  44846. this._color = this._copy.color;
  44847. }
  44848. else if (meshCol && meshCol[c] !== undefined) {
  44849. this._color.r = meshCol[c];
  44850. this._color.g = meshCol[c + 1];
  44851. this._color.b = meshCol[c + 2];
  44852. this._color.a = meshCol[c + 3];
  44853. }
  44854. else {
  44855. this._color.r = 1.0;
  44856. this._color.g = 1.0;
  44857. this._color.b = 1.0;
  44858. this._color.a = 1.0;
  44859. }
  44860. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  44861. c += 4;
  44862. if (!this.recomputeNormals && meshNor) {
  44863. this._normal.x = meshNor[n];
  44864. this._normal.y = meshNor[n + 1];
  44865. this._normal.z = meshNor[n + 2];
  44866. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  44867. normals.push(this._normal.x, this._normal.y, this._normal.z);
  44868. n += 3;
  44869. }
  44870. }
  44871. for (i = 0; i < meshInd.length; i++) {
  44872. var current_ind = p + meshInd[i];
  44873. indices.push(current_ind);
  44874. if (current_ind > 65535) {
  44875. this._needs32Bits = true;
  44876. }
  44877. }
  44878. if (this._pickable) {
  44879. var nbfaces = meshInd.length / 3;
  44880. for (i = 0; i < nbfaces; i++) {
  44881. this.pickedParticles.push({ idx: idx, faceId: i });
  44882. }
  44883. }
  44884. if (this._depthSort) {
  44885. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  44886. }
  44887. return this._copy;
  44888. };
  44889. // returns a shape array from positions array
  44890. SolidParticleSystem.prototype._posToShape = function (positions) {
  44891. var shape = [];
  44892. for (var i = 0; i < positions.length; i += 3) {
  44893. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  44894. }
  44895. return shape;
  44896. };
  44897. // returns a shapeUV array from a Vector4 uvs
  44898. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  44899. var shapeUV = [];
  44900. if (uvs) {
  44901. for (var i = 0; i < uvs.length; i++)
  44902. shapeUV.push(uvs[i]);
  44903. }
  44904. return shapeUV;
  44905. };
  44906. // adds a new particle object in the particles array
  44907. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  44908. if (bInfo === void 0) { bInfo = null; }
  44909. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  44910. this.particles.push(sp);
  44911. return sp;
  44912. };
  44913. /**
  44914. * Adds some particles to the SPS from the model shape. Returns the shape id.
  44915. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  44916. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  44917. * `nb` (positive integer) the number of particles to be created from this model
  44918. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  44919. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  44920. */
  44921. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  44922. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44923. var meshInd = mesh.getIndices();
  44924. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44925. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44926. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44927. var bbInfo;
  44928. if (this._particlesIntersect) {
  44929. bbInfo = mesh.getBoundingInfo();
  44930. }
  44931. var shape = this._posToShape(meshPos);
  44932. var shapeUV = this._uvsToShapeUV(meshUV);
  44933. var posfunc = options ? options.positionFunction : null;
  44934. var vtxfunc = options ? options.vertexFunction : null;
  44935. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  44936. // particles
  44937. var sp;
  44938. var currentCopy;
  44939. var idx = this.nbParticles;
  44940. for (var i = 0; i < nb; i++) {
  44941. var currentPos = this._positions.length;
  44942. var currentInd = this._indices.length;
  44943. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  44944. if (this._updatable) {
  44945. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  44946. sp.position.copyFrom(currentCopy.position);
  44947. sp.rotation.copyFrom(currentCopy.rotation);
  44948. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  44949. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  44950. }
  44951. if (currentCopy.color && sp.color) {
  44952. sp.color.copyFrom(currentCopy.color);
  44953. }
  44954. sp.scaling.copyFrom(currentCopy.scaling);
  44955. sp.uvs.copyFrom(currentCopy.uvs);
  44956. }
  44957. this._index += shape.length;
  44958. idx++;
  44959. }
  44960. this.nbParticles += nb;
  44961. this._shapeCounter++;
  44962. return this._shapeCounter - 1;
  44963. };
  44964. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  44965. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  44966. this._resetCopy();
  44967. if (particle._model._positionFunction) {
  44968. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  44969. }
  44970. if (this._copy.rotationQuaternion) {
  44971. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44972. }
  44973. else {
  44974. this._yaw = this._copy.rotation.y;
  44975. this._pitch = this._copy.rotation.x;
  44976. this._roll = this._copy.rotation.z;
  44977. this._quaternionRotationYPR();
  44978. }
  44979. this._quaternionToRotationMatrix();
  44980. this._shape = particle._model._shape;
  44981. for (var pt = 0; pt < this._shape.length; pt++) {
  44982. this._vertex.x = this._shape[pt].x;
  44983. this._vertex.y = this._shape[pt].y;
  44984. this._vertex.z = this._shape[pt].z;
  44985. if (particle._model._vertexFunction) {
  44986. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  44987. }
  44988. this._vertex.x *= this._copy.scaling.x;
  44989. this._vertex.y *= this._copy.scaling.y;
  44990. this._vertex.z *= this._copy.scaling.z;
  44991. this._vertex.x += this._copy.pivot.x;
  44992. this._vertex.y += this._copy.pivot.y;
  44993. this._vertex.z += this._copy.pivot.z;
  44994. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44995. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  44996. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  44997. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  44998. }
  44999. particle.position.x = 0.0;
  45000. particle.position.y = 0.0;
  45001. particle.position.z = 0.0;
  45002. particle.rotation.x = 0.0;
  45003. particle.rotation.y = 0.0;
  45004. particle.rotation.z = 0.0;
  45005. particle.rotationQuaternion = null;
  45006. particle.scaling.x = 1.0;
  45007. particle.scaling.y = 1.0;
  45008. particle.scaling.z = 1.0;
  45009. };
  45010. /**
  45011. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45012. * Returns the SPS.
  45013. */
  45014. SolidParticleSystem.prototype.rebuildMesh = function () {
  45015. for (var p = 0; p < this.particles.length; p++) {
  45016. this._rebuildParticle(this.particles[p]);
  45017. }
  45018. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45019. return this;
  45020. };
  45021. /**
  45022. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45023. * This method calls `updateParticle()` for each particle of the SPS.
  45024. * For an animated SPS, it is usually called within the render loop.
  45025. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45026. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45027. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45028. * Returns the SPS.
  45029. */
  45030. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45031. if (start === void 0) { start = 0; }
  45032. if (end === void 0) { end = this.nbParticles - 1; }
  45033. if (update === void 0) { update = true; }
  45034. if (!this._updatable) {
  45035. return this;
  45036. }
  45037. // custom beforeUpdate
  45038. this.beforeUpdateParticles(start, end, update);
  45039. this._cam_axisX.x = 1.0;
  45040. this._cam_axisX.y = 0.0;
  45041. this._cam_axisX.z = 0.0;
  45042. this._cam_axisY.x = 0.0;
  45043. this._cam_axisY.y = 1.0;
  45044. this._cam_axisY.z = 0.0;
  45045. this._cam_axisZ.x = 0.0;
  45046. this._cam_axisZ.y = 0.0;
  45047. this._cam_axisZ.z = 1.0;
  45048. // cases when the World Matrix is to be computed first
  45049. if (this.billboard || this._depthSort) {
  45050. this.mesh.computeWorldMatrix(true);
  45051. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45052. }
  45053. // if the particles will always face the camera
  45054. if (this.billboard) {
  45055. // compute the camera position and un-rotate it by the current mesh rotation
  45056. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45057. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45058. this._cam_axisZ.normalize();
  45059. // same for camera up vector extracted from the cam view matrix
  45060. var view = this._camera.getViewMatrix(true);
  45061. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45062. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45063. this._cam_axisY.normalize();
  45064. this._cam_axisX.normalize();
  45065. }
  45066. // if depthSort, compute the camera global position in the mesh local system
  45067. if (this._depthSort) {
  45068. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45069. }
  45070. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45071. var idx = 0; // current position index in the global array positions32
  45072. var index = 0; // position start index in the global array positions32 of the current particle
  45073. var colidx = 0; // current color index in the global array colors32
  45074. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45075. var uvidx = 0; // current uv index in the global array uvs32
  45076. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45077. var pt = 0; // current index in the particle model shape
  45078. if (this.mesh.isFacetDataEnabled) {
  45079. this._computeBoundingBox = true;
  45080. }
  45081. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45082. if (this._computeBoundingBox) {
  45083. if (start == 0 && end == this.nbParticles - 1) {
  45084. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45085. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45086. }
  45087. else {
  45088. if (this.mesh._boundingInfo) {
  45089. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45090. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45091. }
  45092. }
  45093. }
  45094. // particle loop
  45095. index = this.particles[start]._pos;
  45096. var vpos = (index / 3) | 0;
  45097. colorIndex = vpos * 4;
  45098. uvIndex = vpos * 2;
  45099. for (var p = start; p <= end; p++) {
  45100. this._particle = this.particles[p];
  45101. this._shape = this._particle._model._shape;
  45102. this._shapeUV = this._particle._model._shapeUV;
  45103. // call to custom user function to update the particle properties
  45104. this.updateParticle(this._particle);
  45105. // camera-particle distance for depth sorting
  45106. if (this._depthSort && this._depthSortParticles) {
  45107. var dsp = this.depthSortedParticles[p];
  45108. dsp.ind = this._particle._ind;
  45109. dsp.indicesLength = this._particle._model._indicesLength;
  45110. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45111. }
  45112. // skip the computations for inactive or already invisible particles
  45113. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45114. // increment indexes for the next particle
  45115. pt = this._shape.length;
  45116. index += pt * 3;
  45117. colorIndex += pt * 4;
  45118. uvIndex += pt * 2;
  45119. continue;
  45120. }
  45121. if (this._particle.isVisible) {
  45122. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45123. // particle rotation matrix
  45124. if (this.billboard) {
  45125. this._particle.rotation.x = 0.0;
  45126. this._particle.rotation.y = 0.0;
  45127. }
  45128. if (this._computeParticleRotation || this.billboard) {
  45129. if (this._particle.rotationQuaternion) {
  45130. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45131. }
  45132. else {
  45133. this._yaw = this._particle.rotation.y;
  45134. this._pitch = this._particle.rotation.x;
  45135. this._roll = this._particle.rotation.z;
  45136. this._quaternionRotationYPR();
  45137. }
  45138. this._quaternionToRotationMatrix();
  45139. }
  45140. // particle vertex loop
  45141. for (pt = 0; pt < this._shape.length; pt++) {
  45142. idx = index + pt * 3;
  45143. colidx = colorIndex + pt * 4;
  45144. uvidx = uvIndex + pt * 2;
  45145. this._vertex.x = this._shape[pt].x;
  45146. this._vertex.y = this._shape[pt].y;
  45147. this._vertex.z = this._shape[pt].z;
  45148. if (this._computeParticleVertex) {
  45149. this.updateParticleVertex(this._particle, this._vertex, pt);
  45150. }
  45151. // positions
  45152. this._vertex.x *= this._particle.scaling.x;
  45153. this._vertex.y *= this._particle.scaling.y;
  45154. this._vertex.z *= this._particle.scaling.z;
  45155. this._vertex.x += this._particle.pivot.x;
  45156. this._vertex.y += this._particle.pivot.y;
  45157. this._vertex.z += this._particle.pivot.z;
  45158. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45159. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45160. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45161. 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;
  45162. 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;
  45163. 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;
  45164. if (this._computeBoundingBox) {
  45165. if (this._positions32[idx] < this._minimum.x) {
  45166. this._minimum.x = this._positions32[idx];
  45167. }
  45168. if (this._positions32[idx] > this._maximum.x) {
  45169. this._maximum.x = this._positions32[idx];
  45170. }
  45171. if (this._positions32[idx + 1] < this._minimum.y) {
  45172. this._minimum.y = this._positions32[idx + 1];
  45173. }
  45174. if (this._positions32[idx + 1] > this._maximum.y) {
  45175. this._maximum.y = this._positions32[idx + 1];
  45176. }
  45177. if (this._positions32[idx + 2] < this._minimum.z) {
  45178. this._minimum.z = this._positions32[idx + 2];
  45179. }
  45180. if (this._positions32[idx + 2] > this._maximum.z) {
  45181. this._maximum.z = this._positions32[idx + 2];
  45182. }
  45183. }
  45184. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45185. if (!this._computeParticleVertex) {
  45186. this._normal.x = this._fixedNormal32[idx];
  45187. this._normal.y = this._fixedNormal32[idx + 1];
  45188. this._normal.z = this._fixedNormal32[idx + 2];
  45189. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45190. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45191. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45192. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45193. 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;
  45194. 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;
  45195. }
  45196. if (this._computeParticleColor && this._particle.color) {
  45197. this._colors32[colidx] = this._particle.color.r;
  45198. this._colors32[colidx + 1] = this._particle.color.g;
  45199. this._colors32[colidx + 2] = this._particle.color.b;
  45200. this._colors32[colidx + 3] = this._particle.color.a;
  45201. }
  45202. if (this._computeParticleTexture) {
  45203. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45204. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45205. }
  45206. }
  45207. }
  45208. else {
  45209. this._particle._stillInvisible = true; // mark the particle as invisible
  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._positions32[idx] = 0.0;
  45215. this._positions32[idx + 1] = 0.0;
  45216. this._positions32[idx + 2] = 0.0;
  45217. this._normals32[idx] = 0.0;
  45218. this._normals32[idx + 1] = 0.0;
  45219. this._normals32[idx + 2] = 0.0;
  45220. if (this._computeParticleColor && this._particle.color) {
  45221. this._colors32[colidx] = this._particle.color.r;
  45222. this._colors32[colidx + 1] = this._particle.color.g;
  45223. this._colors32[colidx + 2] = this._particle.color.b;
  45224. this._colors32[colidx + 3] = this._particle.color.a;
  45225. }
  45226. if (this._computeParticleTexture) {
  45227. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45228. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45229. }
  45230. }
  45231. }
  45232. // if the particle intersections must be computed : update the bbInfo
  45233. if (this._particlesIntersect) {
  45234. var bInfo = this._particle._boundingInfo;
  45235. var bBox = bInfo.boundingBox;
  45236. var bSphere = bInfo.boundingSphere;
  45237. if (!this._bSphereOnly) {
  45238. // place, scale and rotate the particle bbox within the SPS local system, then update it
  45239. for (var b = 0; b < bBox.vectors.length; b++) {
  45240. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  45241. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  45242. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  45243. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45244. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45245. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45246. 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;
  45247. 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;
  45248. 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;
  45249. }
  45250. bBox._update(this.mesh._worldMatrix);
  45251. }
  45252. // place and scale the particle bouding sphere in the SPS local system, then update it
  45253. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  45254. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  45255. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  45256. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  45257. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  45258. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  45259. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  45260. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  45261. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  45262. 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));
  45263. bSphere._update(this.mesh._worldMatrix);
  45264. }
  45265. // increment indexes for the next particle
  45266. index = idx + 3;
  45267. colorIndex = colidx + 4;
  45268. uvIndex = uvidx + 2;
  45269. }
  45270. // if the VBO must be updated
  45271. if (update) {
  45272. if (this._computeParticleColor) {
  45273. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  45274. }
  45275. if (this._computeParticleTexture) {
  45276. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  45277. }
  45278. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45279. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  45280. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  45281. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  45282. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  45283. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  45284. for (var i = 0; i < this._normals32.length; i++) {
  45285. this._fixedNormal32[i] = this._normals32[i];
  45286. }
  45287. }
  45288. if (!this.mesh.areNormalsFrozen) {
  45289. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  45290. }
  45291. }
  45292. if (this._depthSort && this._depthSortParticles) {
  45293. this.depthSortedParticles.sort(this._depthSortFunction);
  45294. var dspl = this.depthSortedParticles.length;
  45295. var sorted = 0;
  45296. var lind = 0;
  45297. var sind = 0;
  45298. var sid = 0;
  45299. for (sorted = 0; sorted < dspl; sorted++) {
  45300. lind = this.depthSortedParticles[sorted].indicesLength;
  45301. sind = this.depthSortedParticles[sorted].ind;
  45302. for (var i = 0; i < lind; i++) {
  45303. this._indices32[sid] = this._indices[sind + i];
  45304. sid++;
  45305. }
  45306. }
  45307. this.mesh.updateIndices(this._indices32);
  45308. }
  45309. }
  45310. if (this._computeBoundingBox) {
  45311. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  45312. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  45313. }
  45314. this.afterUpdateParticles(start, end, update);
  45315. return this;
  45316. };
  45317. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  45318. this._halfroll = this._roll * 0.5;
  45319. this._halfpitch = this._pitch * 0.5;
  45320. this._halfyaw = this._yaw * 0.5;
  45321. this._sinRoll = Math.sin(this._halfroll);
  45322. this._cosRoll = Math.cos(this._halfroll);
  45323. this._sinPitch = Math.sin(this._halfpitch);
  45324. this._cosPitch = Math.cos(this._halfpitch);
  45325. this._sinYaw = Math.sin(this._halfyaw);
  45326. this._cosYaw = Math.cos(this._halfyaw);
  45327. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  45328. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  45329. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  45330. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  45331. };
  45332. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  45333. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  45334. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  45335. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  45336. this._rotMatrix.m[3] = 0;
  45337. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  45338. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  45339. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  45340. this._rotMatrix.m[7] = 0;
  45341. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  45342. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  45343. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  45344. this._rotMatrix.m[11] = 0;
  45345. this._rotMatrix.m[12] = 0;
  45346. this._rotMatrix.m[13] = 0;
  45347. this._rotMatrix.m[14] = 0;
  45348. this._rotMatrix.m[15] = 1.0;
  45349. };
  45350. /**
  45351. * Disposes the SPS.
  45352. * Returns nothing.
  45353. */
  45354. SolidParticleSystem.prototype.dispose = function () {
  45355. this.mesh.dispose();
  45356. this.vars = null;
  45357. // drop references to internal big arrays for the GC
  45358. this._positions = null;
  45359. this._indices = null;
  45360. this._normals = null;
  45361. this._uvs = null;
  45362. this._colors = null;
  45363. this._indices32 = null;
  45364. this._positions32 = null;
  45365. this._normals32 = null;
  45366. this._fixedNormal32 = null;
  45367. this._uvs32 = null;
  45368. this._colors32 = null;
  45369. this.pickedParticles = null;
  45370. };
  45371. /**
  45372. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  45373. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45374. * Returns the SPS.
  45375. */
  45376. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  45377. if (!this._isVisibilityBoxLocked) {
  45378. this.mesh.refreshBoundingInfo();
  45379. }
  45380. return this;
  45381. };
  45382. /**
  45383. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  45384. * @param size the size (float) of the visibility box
  45385. * note : this doesn't lock the SPS mesh bounding box.
  45386. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45387. */
  45388. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  45389. var vis = size / 2;
  45390. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  45391. };
  45392. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  45393. // getter and setter
  45394. get: function () {
  45395. return this._alwaysVisible;
  45396. },
  45397. /**
  45398. * Sets the SPS as always visible or not
  45399. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45400. */
  45401. set: function (val) {
  45402. this._alwaysVisible = val;
  45403. this.mesh.alwaysSelectAsActiveMesh = val;
  45404. },
  45405. enumerable: true,
  45406. configurable: true
  45407. });
  45408. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  45409. get: function () {
  45410. return this._isVisibilityBoxLocked;
  45411. },
  45412. /**
  45413. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  45414. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45415. */
  45416. set: function (val) {
  45417. this._isVisibilityBoxLocked = val;
  45418. var boundingInfo = this.mesh.getBoundingInfo();
  45419. if (boundingInfo) {
  45420. boundingInfo.isLocked = val;
  45421. }
  45422. },
  45423. enumerable: true,
  45424. configurable: true
  45425. });
  45426. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  45427. // getters
  45428. get: function () {
  45429. return this._computeParticleRotation;
  45430. },
  45431. // Optimizer setters
  45432. /**
  45433. * Tells to `setParticles()` to compute the particle rotations or not.
  45434. * Default value : true. The SPS is faster when it's set to false.
  45435. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  45436. */
  45437. set: function (val) {
  45438. this._computeParticleRotation = val;
  45439. },
  45440. enumerable: true,
  45441. configurable: true
  45442. });
  45443. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  45444. get: function () {
  45445. return this._computeParticleColor;
  45446. },
  45447. /**
  45448. * Tells to `setParticles()` to compute the particle colors or not.
  45449. * Default value : true. The SPS is faster when it's set to false.
  45450. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  45451. */
  45452. set: function (val) {
  45453. this._computeParticleColor = val;
  45454. },
  45455. enumerable: true,
  45456. configurable: true
  45457. });
  45458. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  45459. get: function () {
  45460. return this._computeParticleTexture;
  45461. },
  45462. /**
  45463. * Tells to `setParticles()` to compute the particle textures or not.
  45464. * Default value : true. The SPS is faster when it's set to false.
  45465. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  45466. */
  45467. set: function (val) {
  45468. this._computeParticleTexture = val;
  45469. },
  45470. enumerable: true,
  45471. configurable: true
  45472. });
  45473. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  45474. get: function () {
  45475. return this._computeParticleVertex;
  45476. },
  45477. /**
  45478. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  45479. * Default value : false. The SPS is faster when it's set to false.
  45480. * Note : the particle custom vertex positions aren't stored values.
  45481. */
  45482. set: function (val) {
  45483. this._computeParticleVertex = val;
  45484. },
  45485. enumerable: true,
  45486. configurable: true
  45487. });
  45488. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  45489. get: function () {
  45490. return this._computeBoundingBox;
  45491. },
  45492. /**
  45493. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  45494. */
  45495. set: function (val) {
  45496. this._computeBoundingBox = val;
  45497. },
  45498. enumerable: true,
  45499. configurable: true
  45500. });
  45501. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  45502. get: function () {
  45503. return this._depthSortParticles;
  45504. },
  45505. /**
  45506. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  45507. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  45508. * Default : `true`
  45509. */
  45510. set: function (val) {
  45511. this._depthSortParticles = val;
  45512. },
  45513. enumerable: true,
  45514. configurable: true
  45515. });
  45516. // =======================================================================
  45517. // Particle behavior logic
  45518. // these following methods may be overwritten by the user to fit his needs
  45519. /**
  45520. * This function does nothing. It may be overwritten to set all the particle first values.
  45521. * The SPS doesn't call this function, you may have to call it by your own.
  45522. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45523. */
  45524. SolidParticleSystem.prototype.initParticles = function () {
  45525. };
  45526. /**
  45527. * This function does nothing. It may be overwritten to recycle a particle.
  45528. * The SPS doesn't call this function, you may have to call it by your own.
  45529. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45530. */
  45531. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  45532. return particle;
  45533. };
  45534. /**
  45535. * Updates a particle : this function should be overwritten by the user.
  45536. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  45537. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45538. * ex : just set a particle position or velocity and recycle conditions
  45539. */
  45540. SolidParticleSystem.prototype.updateParticle = function (particle) {
  45541. return particle;
  45542. };
  45543. /**
  45544. * Updates a vertex of a particle : it can be overwritten by the user.
  45545. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  45546. * @param particle the current particle
  45547. * @param vertex the current index of the current particle
  45548. * @param pt the index of the current vertex in the particle shape
  45549. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  45550. * ex : just set a vertex particle position
  45551. */
  45552. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  45553. return vertex;
  45554. };
  45555. /**
  45556. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  45557. * This does nothing and may be overwritten by the user.
  45558. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45559. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45560. * @param update the boolean update value actually passed to setParticles()
  45561. */
  45562. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  45563. };
  45564. /**
  45565. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  45566. * This will be passed three parameters.
  45567. * This does nothing and may be overwritten by the user.
  45568. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45569. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45570. * @param update the boolean update value actually passed to setParticles()
  45571. */
  45572. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  45573. };
  45574. return SolidParticleSystem;
  45575. }());
  45576. BABYLON.SolidParticleSystem = SolidParticleSystem;
  45577. })(BABYLON || (BABYLON = {}));
  45578. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  45579. var BABYLON;
  45580. (function (BABYLON) {
  45581. var GroundMesh = /** @class */ (function (_super) {
  45582. __extends(GroundMesh, _super);
  45583. function GroundMesh(name, scene) {
  45584. var _this = _super.call(this, name, scene) || this;
  45585. _this.generateOctree = false;
  45586. return _this;
  45587. }
  45588. GroundMesh.prototype.getClassName = function () {
  45589. return "GroundMesh";
  45590. };
  45591. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  45592. get: function () {
  45593. return Math.min(this._subdivisionsX, this._subdivisionsY);
  45594. },
  45595. enumerable: true,
  45596. configurable: true
  45597. });
  45598. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  45599. get: function () {
  45600. return this._subdivisionsX;
  45601. },
  45602. enumerable: true,
  45603. configurable: true
  45604. });
  45605. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  45606. get: function () {
  45607. return this._subdivisionsY;
  45608. },
  45609. enumerable: true,
  45610. configurable: true
  45611. });
  45612. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  45613. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  45614. this._subdivisionsX = chunksCount;
  45615. this._subdivisionsY = chunksCount;
  45616. this.subdivide(chunksCount);
  45617. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  45618. };
  45619. /**
  45620. * Returns a height (y) value in the Worl system :
  45621. * the ground altitude at the coordinates (x, z) expressed in the World system.
  45622. * Returns the ground y position if (x, z) are outside the ground surface.
  45623. */
  45624. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  45625. var world = this.getWorldMatrix();
  45626. var invMat = BABYLON.Tmp.Matrix[5];
  45627. world.invertToRef(invMat);
  45628. var tmpVect = BABYLON.Tmp.Vector3[8];
  45629. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  45630. x = tmpVect.x;
  45631. z = tmpVect.z;
  45632. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45633. return this.position.y;
  45634. }
  45635. if (!this._heightQuads || this._heightQuads.length == 0) {
  45636. this._initHeightQuads();
  45637. this._computeHeightQuads();
  45638. }
  45639. var facet = this._getFacetAt(x, z);
  45640. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  45641. // return y in the World system
  45642. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  45643. return tmpVect.y;
  45644. };
  45645. /**
  45646. * Returns a normalized vector (Vector3) orthogonal to the ground
  45647. * at the ground coordinates (x, z) expressed in the World system.
  45648. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  45649. */
  45650. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  45651. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  45652. this.getNormalAtCoordinatesToRef(x, z, normal);
  45653. return normal;
  45654. };
  45655. /**
  45656. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  45657. * at the ground coordinates (x, z) expressed in the World system.
  45658. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  45659. * Returns the GroundMesh.
  45660. */
  45661. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  45662. var world = this.getWorldMatrix();
  45663. var tmpMat = BABYLON.Tmp.Matrix[5];
  45664. world.invertToRef(tmpMat);
  45665. var tmpVect = BABYLON.Tmp.Vector3[8];
  45666. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  45667. x = tmpVect.x;
  45668. z = tmpVect.z;
  45669. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45670. return this;
  45671. }
  45672. if (!this._heightQuads || this._heightQuads.length == 0) {
  45673. this._initHeightQuads();
  45674. this._computeHeightQuads();
  45675. }
  45676. var facet = this._getFacetAt(x, z);
  45677. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  45678. return this;
  45679. };
  45680. /**
  45681. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  45682. * if the ground has been updated.
  45683. * This can be used in the render loop.
  45684. * Returns the GroundMesh.
  45685. */
  45686. GroundMesh.prototype.updateCoordinateHeights = function () {
  45687. if (!this._heightQuads || this._heightQuads.length == 0) {
  45688. this._initHeightQuads();
  45689. }
  45690. this._computeHeightQuads();
  45691. return this;
  45692. };
  45693. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  45694. GroundMesh.prototype._getFacetAt = function (x, z) {
  45695. // retrieve col and row from x, z coordinates in the ground local system
  45696. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  45697. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  45698. var quad = this._heightQuads[row * this._subdivisionsX + col];
  45699. var facet;
  45700. if (z < quad.slope.x * x + quad.slope.y) {
  45701. facet = quad.facet1;
  45702. }
  45703. else {
  45704. facet = quad.facet2;
  45705. }
  45706. return facet;
  45707. };
  45708. // Creates and populates the heightMap array with "facet" elements :
  45709. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  45710. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45711. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45712. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45713. // Returns the GroundMesh.
  45714. GroundMesh.prototype._initHeightQuads = function () {
  45715. var subdivisionsX = this._subdivisionsX;
  45716. var subdivisionsY = this._subdivisionsY;
  45717. this._heightQuads = new Array();
  45718. for (var row = 0; row < subdivisionsY; row++) {
  45719. for (var col = 0; col < subdivisionsX; col++) {
  45720. 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) };
  45721. this._heightQuads[row * subdivisionsX + col] = quad;
  45722. }
  45723. }
  45724. return this;
  45725. };
  45726. // Compute each quad element values and update the the heightMap array :
  45727. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45728. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45729. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45730. // Returns the GroundMesh.
  45731. GroundMesh.prototype._computeHeightQuads = function () {
  45732. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45733. if (!positions) {
  45734. return this;
  45735. }
  45736. var v1 = BABYLON.Tmp.Vector3[3];
  45737. var v2 = BABYLON.Tmp.Vector3[2];
  45738. var v3 = BABYLON.Tmp.Vector3[1];
  45739. var v4 = BABYLON.Tmp.Vector3[0];
  45740. var v1v2 = BABYLON.Tmp.Vector3[4];
  45741. var v1v3 = BABYLON.Tmp.Vector3[5];
  45742. var v1v4 = BABYLON.Tmp.Vector3[6];
  45743. var norm1 = BABYLON.Tmp.Vector3[7];
  45744. var norm2 = BABYLON.Tmp.Vector3[8];
  45745. var i = 0;
  45746. var j = 0;
  45747. var k = 0;
  45748. var cd = 0; // 2D slope coefficient : z = cd * x + h
  45749. var h = 0;
  45750. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  45751. var d2 = 0;
  45752. var subdivisionsX = this._subdivisionsX;
  45753. var subdivisionsY = this._subdivisionsY;
  45754. for (var row = 0; row < subdivisionsY; row++) {
  45755. for (var col = 0; col < subdivisionsX; col++) {
  45756. i = col * 3;
  45757. j = row * (subdivisionsX + 1) * 3;
  45758. k = (row + 1) * (subdivisionsX + 1) * 3;
  45759. v1.x = positions[j + i];
  45760. v1.y = positions[j + i + 1];
  45761. v1.z = positions[j + i + 2];
  45762. v2.x = positions[j + i + 3];
  45763. v2.y = positions[j + i + 4];
  45764. v2.z = positions[j + i + 5];
  45765. v3.x = positions[k + i];
  45766. v3.y = positions[k + i + 1];
  45767. v3.z = positions[k + i + 2];
  45768. v4.x = positions[k + i + 3];
  45769. v4.y = positions[k + i + 4];
  45770. v4.z = positions[k + i + 5];
  45771. // 2D slope V1V4
  45772. cd = (v4.z - v1.z) / (v4.x - v1.x);
  45773. h = v1.z - cd * v1.x; // v1 belongs to the slope
  45774. // facet equations :
  45775. // we compute each facet normal vector
  45776. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  45777. // we compute the value d by applying the equation to v1 which belongs to the plane
  45778. // then we store the facet equation in a Vector4
  45779. v2.subtractToRef(v1, v1v2);
  45780. v3.subtractToRef(v1, v1v3);
  45781. v4.subtractToRef(v1, v1v4);
  45782. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  45783. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  45784. norm1.normalize();
  45785. norm2.normalize();
  45786. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  45787. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  45788. var quad = this._heightQuads[row * subdivisionsX + col];
  45789. quad.slope.copyFromFloats(cd, h);
  45790. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  45791. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  45792. }
  45793. }
  45794. return this;
  45795. };
  45796. GroundMesh.prototype.serialize = function (serializationObject) {
  45797. _super.prototype.serialize.call(this, serializationObject);
  45798. serializationObject.subdivisionsX = this._subdivisionsX;
  45799. serializationObject.subdivisionsY = this._subdivisionsY;
  45800. serializationObject.minX = this._minX;
  45801. serializationObject.maxX = this._maxX;
  45802. serializationObject.minZ = this._minZ;
  45803. serializationObject.maxZ = this._maxZ;
  45804. serializationObject.width = this._width;
  45805. serializationObject.height = this._height;
  45806. };
  45807. GroundMesh.Parse = function (parsedMesh, scene) {
  45808. var result = new GroundMesh(parsedMesh.name, scene);
  45809. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  45810. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  45811. result._minX = parsedMesh.minX;
  45812. result._maxX = parsedMesh.maxX;
  45813. result._minZ = parsedMesh.minZ;
  45814. result._maxZ = parsedMesh.maxZ;
  45815. result._width = parsedMesh.width;
  45816. result._height = parsedMesh.height;
  45817. return result;
  45818. };
  45819. return GroundMesh;
  45820. }(BABYLON.Mesh));
  45821. BABYLON.GroundMesh = GroundMesh;
  45822. })(BABYLON || (BABYLON = {}));
  45823. //# sourceMappingURL=babylon.groundMesh.js.map
  45824. var BABYLON;
  45825. (function (BABYLON) {
  45826. /**
  45827. * Creates an instance based on a source mesh.
  45828. */
  45829. var InstancedMesh = /** @class */ (function (_super) {
  45830. __extends(InstancedMesh, _super);
  45831. function InstancedMesh(name, source) {
  45832. var _this = _super.call(this, name, source.getScene()) || this;
  45833. source.instances.push(_this);
  45834. _this._sourceMesh = source;
  45835. _this.position.copyFrom(source.position);
  45836. _this.rotation.copyFrom(source.rotation);
  45837. _this.scaling.copyFrom(source.scaling);
  45838. if (source.rotationQuaternion) {
  45839. _this.rotationQuaternion = source.rotationQuaternion.clone();
  45840. }
  45841. _this.infiniteDistance = source.infiniteDistance;
  45842. _this.setPivotMatrix(source.getPivotMatrix());
  45843. _this.refreshBoundingInfo();
  45844. _this._syncSubMeshes();
  45845. return _this;
  45846. }
  45847. /**
  45848. * Returns the string "InstancedMesh".
  45849. */
  45850. InstancedMesh.prototype.getClassName = function () {
  45851. return "InstancedMesh";
  45852. };
  45853. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  45854. // Methods
  45855. get: function () {
  45856. return this._sourceMesh.receiveShadows;
  45857. },
  45858. enumerable: true,
  45859. configurable: true
  45860. });
  45861. Object.defineProperty(InstancedMesh.prototype, "material", {
  45862. get: function () {
  45863. return this._sourceMesh.material;
  45864. },
  45865. enumerable: true,
  45866. configurable: true
  45867. });
  45868. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  45869. get: function () {
  45870. return this._sourceMesh.visibility;
  45871. },
  45872. enumerable: true,
  45873. configurable: true
  45874. });
  45875. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  45876. get: function () {
  45877. return this._sourceMesh.skeleton;
  45878. },
  45879. enumerable: true,
  45880. configurable: true
  45881. });
  45882. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  45883. get: function () {
  45884. return this._sourceMesh.renderingGroupId;
  45885. },
  45886. enumerable: true,
  45887. configurable: true
  45888. });
  45889. /**
  45890. * Returns the total number of vertices (integer).
  45891. */
  45892. InstancedMesh.prototype.getTotalVertices = function () {
  45893. return this._sourceMesh.getTotalVertices();
  45894. };
  45895. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  45896. get: function () {
  45897. return this._sourceMesh;
  45898. },
  45899. enumerable: true,
  45900. configurable: true
  45901. });
  45902. /**
  45903. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  45904. */
  45905. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  45906. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  45907. };
  45908. /**
  45909. * Sets the vertex data of the mesh geometry for the requested `kind`.
  45910. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  45911. * The `data` are either a numeric array either a Float32Array.
  45912. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  45913. * 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).
  45914. * Note that a new underlying VertexBuffer object is created each call.
  45915. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  45916. *
  45917. * Possible `kind` values :
  45918. * - BABYLON.VertexBuffer.PositionKind
  45919. * - BABYLON.VertexBuffer.UVKind
  45920. * - BABYLON.VertexBuffer.UV2Kind
  45921. * - BABYLON.VertexBuffer.UV3Kind
  45922. * - BABYLON.VertexBuffer.UV4Kind
  45923. * - BABYLON.VertexBuffer.UV5Kind
  45924. * - BABYLON.VertexBuffer.UV6Kind
  45925. * - BABYLON.VertexBuffer.ColorKind
  45926. * - BABYLON.VertexBuffer.MatricesIndicesKind
  45927. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  45928. * - BABYLON.VertexBuffer.MatricesWeightsKind
  45929. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  45930. *
  45931. * Returns the Mesh.
  45932. */
  45933. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  45934. if (this.sourceMesh) {
  45935. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  45936. }
  45937. return this.sourceMesh;
  45938. };
  45939. /**
  45940. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  45941. * If the mesh has no geometry, it is simply returned as it is.
  45942. * The `data` are either a numeric array either a Float32Array.
  45943. * No new underlying VertexBuffer object is created.
  45944. * 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.
  45945. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  45946. *
  45947. * Possible `kind` values :
  45948. * - BABYLON.VertexBuffer.PositionKind
  45949. * - BABYLON.VertexBuffer.UVKind
  45950. * - BABYLON.VertexBuffer.UV2Kind
  45951. * - BABYLON.VertexBuffer.UV3Kind
  45952. * - BABYLON.VertexBuffer.UV4Kind
  45953. * - BABYLON.VertexBuffer.UV5Kind
  45954. * - BABYLON.VertexBuffer.UV6Kind
  45955. * - BABYLON.VertexBuffer.ColorKind
  45956. * - BABYLON.VertexBuffer.MatricesIndicesKind
  45957. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  45958. * - BABYLON.VertexBuffer.MatricesWeightsKind
  45959. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  45960. *
  45961. * Returns the Mesh.
  45962. */
  45963. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  45964. if (this.sourceMesh) {
  45965. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  45966. }
  45967. return this.sourceMesh;
  45968. };
  45969. /**
  45970. * Sets the mesh indices.
  45971. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  45972. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  45973. * This method creates a new index buffer each call.
  45974. * Returns the Mesh.
  45975. */
  45976. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  45977. if (totalVertices === void 0) { totalVertices = null; }
  45978. if (this.sourceMesh) {
  45979. this.sourceMesh.setIndices(indices, totalVertices);
  45980. }
  45981. return this.sourceMesh;
  45982. };
  45983. /**
  45984. * Boolean : True if the mesh owns the requested kind of data.
  45985. */
  45986. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  45987. return this._sourceMesh.isVerticesDataPresent(kind);
  45988. };
  45989. /**
  45990. * Returns an array of indices (IndicesArray).
  45991. */
  45992. InstancedMesh.prototype.getIndices = function () {
  45993. return this._sourceMesh.getIndices();
  45994. };
  45995. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  45996. get: function () {
  45997. return this._sourceMesh._positions;
  45998. },
  45999. enumerable: true,
  46000. configurable: true
  46001. });
  46002. /**
  46003. * Sets a new updated BoundingInfo to the mesh.
  46004. * Returns the mesh.
  46005. */
  46006. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46007. var meshBB = this._sourceMesh.getBoundingInfo();
  46008. if (meshBB) {
  46009. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46010. }
  46011. this._updateBoundingInfo();
  46012. return this;
  46013. };
  46014. InstancedMesh.prototype._preActivate = function () {
  46015. if (this._currentLOD) {
  46016. this._currentLOD._preActivate();
  46017. }
  46018. return this;
  46019. };
  46020. InstancedMesh.prototype._activate = function (renderId) {
  46021. if (this._currentLOD) {
  46022. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46023. }
  46024. return this;
  46025. };
  46026. /**
  46027. * Returns the current associated LOD AbstractMesh.
  46028. */
  46029. InstancedMesh.prototype.getLOD = function (camera) {
  46030. if (!camera) {
  46031. return this;
  46032. }
  46033. var boundingInfo = this.getBoundingInfo();
  46034. if (!boundingInfo) {
  46035. return this;
  46036. }
  46037. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46038. if (this._currentLOD === this.sourceMesh) {
  46039. return this;
  46040. }
  46041. return this._currentLOD;
  46042. };
  46043. InstancedMesh.prototype._syncSubMeshes = function () {
  46044. this.releaseSubMeshes();
  46045. if (this._sourceMesh.subMeshes) {
  46046. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46047. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46048. }
  46049. }
  46050. return this;
  46051. };
  46052. InstancedMesh.prototype._generatePointsArray = function () {
  46053. return this._sourceMesh._generatePointsArray();
  46054. };
  46055. /**
  46056. * Creates a new InstancedMesh from the current mesh.
  46057. * - name (string) : the cloned mesh name
  46058. * - newParent (optional Node) : the optional Node to parent the clone to.
  46059. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46060. *
  46061. * Returns the clone.
  46062. */
  46063. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46064. var result = this._sourceMesh.createInstance(name);
  46065. // Deep copy
  46066. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46067. // Bounding info
  46068. this.refreshBoundingInfo();
  46069. // Parent
  46070. if (newParent) {
  46071. result.parent = newParent;
  46072. }
  46073. if (!doNotCloneChildren) {
  46074. // Children
  46075. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46076. var mesh = this.getScene().meshes[index];
  46077. if (mesh.parent === this) {
  46078. mesh.clone(mesh.name, result);
  46079. }
  46080. }
  46081. }
  46082. result.computeWorldMatrix(true);
  46083. return result;
  46084. };
  46085. /**
  46086. * Disposes the InstancedMesh.
  46087. * Returns nothing.
  46088. */
  46089. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46090. // Remove from mesh
  46091. var index = this._sourceMesh.instances.indexOf(this);
  46092. this._sourceMesh.instances.splice(index, 1);
  46093. _super.prototype.dispose.call(this, doNotRecurse);
  46094. };
  46095. return InstancedMesh;
  46096. }(BABYLON.AbstractMesh));
  46097. BABYLON.InstancedMesh = InstancedMesh;
  46098. })(BABYLON || (BABYLON = {}));
  46099. //# sourceMappingURL=babylon.instancedMesh.js.map
  46100. var BABYLON;
  46101. (function (BABYLON) {
  46102. var LinesMesh = /** @class */ (function (_super) {
  46103. __extends(LinesMesh, _super);
  46104. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  46105. if (scene === void 0) { scene = null; }
  46106. if (parent === void 0) { parent = null; }
  46107. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46108. _this.useVertexColor = useVertexColor;
  46109. _this.color = new BABYLON.Color3(1, 1, 1);
  46110. _this.alpha = 1;
  46111. if (source) {
  46112. _this.color = source.color.clone();
  46113. _this.alpha = source.alpha;
  46114. _this.useVertexColor = source.useVertexColor;
  46115. }
  46116. _this._intersectionThreshold = 0.1;
  46117. var options = {
  46118. attributes: [BABYLON.VertexBuffer.PositionKind],
  46119. uniforms: ["world", "viewProjection"],
  46120. needAlphaBlending: false,
  46121. };
  46122. if (!useVertexColor) {
  46123. options.uniforms.push("color");
  46124. options.needAlphaBlending = true;
  46125. }
  46126. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46127. return _this;
  46128. }
  46129. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46130. /**
  46131. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46132. * This margin is expressed in world space coordinates, so its value may vary.
  46133. * Default value is 0.1
  46134. * @returns the intersection Threshold value.
  46135. */
  46136. get: function () {
  46137. return this._intersectionThreshold;
  46138. },
  46139. /**
  46140. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46141. * This margin is expressed in world space coordinates, so its value may vary.
  46142. * @param value the new threshold to apply
  46143. */
  46144. set: function (value) {
  46145. if (this._intersectionThreshold === value) {
  46146. return;
  46147. }
  46148. this._intersectionThreshold = value;
  46149. if (this.geometry) {
  46150. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46151. }
  46152. },
  46153. enumerable: true,
  46154. configurable: true
  46155. });
  46156. /**
  46157. * Returns the string "LineMesh"
  46158. */
  46159. LinesMesh.prototype.getClassName = function () {
  46160. return "LinesMesh";
  46161. };
  46162. Object.defineProperty(LinesMesh.prototype, "material", {
  46163. get: function () {
  46164. return this._colorShader;
  46165. },
  46166. enumerable: true,
  46167. configurable: true
  46168. });
  46169. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46170. get: function () {
  46171. return false;
  46172. },
  46173. enumerable: true,
  46174. configurable: true
  46175. });
  46176. LinesMesh.prototype.createInstance = function (name) {
  46177. throw new Error("LinesMeshes do not support createInstance.");
  46178. };
  46179. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46180. if (!this._geometry) {
  46181. return this;
  46182. }
  46183. // VBOs
  46184. this._geometry._bind(this._colorShader.getEffect());
  46185. // Color
  46186. if (!this.useVertexColor) {
  46187. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46188. }
  46189. return this;
  46190. };
  46191. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46192. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46193. return this;
  46194. }
  46195. var engine = this.getScene().getEngine();
  46196. // Draw order
  46197. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46198. return this;
  46199. };
  46200. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46201. this._colorShader.dispose();
  46202. _super.prototype.dispose.call(this, doNotRecurse);
  46203. };
  46204. /**
  46205. * Returns a new LineMesh object cloned from the current one.
  46206. */
  46207. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46208. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  46209. };
  46210. return LinesMesh;
  46211. }(BABYLON.Mesh));
  46212. BABYLON.LinesMesh = LinesMesh;
  46213. })(BABYLON || (BABYLON = {}));
  46214. //# sourceMappingURL=babylon.linesMesh.js.map
  46215. var BABYLON;
  46216. (function (BABYLON) {
  46217. var ShaderMaterial = /** @class */ (function (_super) {
  46218. __extends(ShaderMaterial, _super);
  46219. function ShaderMaterial(name, scene, shaderPath, options) {
  46220. var _this = _super.call(this, name, scene) || this;
  46221. _this._textures = {};
  46222. _this._textureArrays = {};
  46223. _this._floats = {};
  46224. _this._floatsArrays = {};
  46225. _this._colors3 = {};
  46226. _this._colors3Arrays = {};
  46227. _this._colors4 = {};
  46228. _this._vectors2 = {};
  46229. _this._vectors3 = {};
  46230. _this._vectors4 = {};
  46231. _this._matrices = {};
  46232. _this._matrices3x3 = {};
  46233. _this._matrices2x2 = {};
  46234. _this._vectors3Arrays = {};
  46235. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46236. _this._shaderPath = shaderPath;
  46237. options.needAlphaBlending = options.needAlphaBlending || false;
  46238. options.needAlphaTesting = options.needAlphaTesting || false;
  46239. options.attributes = options.attributes || ["position", "normal", "uv"];
  46240. options.uniforms = options.uniforms || ["worldViewProjection"];
  46241. options.uniformBuffers = options.uniformBuffers || [];
  46242. options.samplers = options.samplers || [];
  46243. options.defines = options.defines || [];
  46244. _this._options = options;
  46245. return _this;
  46246. }
  46247. ShaderMaterial.prototype.getClassName = function () {
  46248. return "ShaderMaterial";
  46249. };
  46250. ShaderMaterial.prototype.needAlphaBlending = function () {
  46251. return this._options.needAlphaBlending;
  46252. };
  46253. ShaderMaterial.prototype.needAlphaTesting = function () {
  46254. return this._options.needAlphaTesting;
  46255. };
  46256. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46257. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46258. this._options.uniforms.push(uniformName);
  46259. }
  46260. };
  46261. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46262. if (this._options.samplers.indexOf(name) === -1) {
  46263. this._options.samplers.push(name);
  46264. }
  46265. this._textures[name] = texture;
  46266. return this;
  46267. };
  46268. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46269. if (this._options.samplers.indexOf(name) === -1) {
  46270. this._options.samplers.push(name);
  46271. }
  46272. this._checkUniform(name);
  46273. this._textureArrays[name] = textures;
  46274. return this;
  46275. };
  46276. ShaderMaterial.prototype.setFloat = function (name, value) {
  46277. this._checkUniform(name);
  46278. this._floats[name] = value;
  46279. return this;
  46280. };
  46281. ShaderMaterial.prototype.setFloats = function (name, value) {
  46282. this._checkUniform(name);
  46283. this._floatsArrays[name] = value;
  46284. return this;
  46285. };
  46286. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46287. this._checkUniform(name);
  46288. this._colors3[name] = value;
  46289. return this;
  46290. };
  46291. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  46292. this._checkUniform(name);
  46293. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  46294. color.toArray(arr, arr.length);
  46295. return arr;
  46296. }, []);
  46297. return this;
  46298. };
  46299. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46300. this._checkUniform(name);
  46301. this._colors4[name] = value;
  46302. return this;
  46303. };
  46304. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46305. this._checkUniform(name);
  46306. this._vectors2[name] = value;
  46307. return this;
  46308. };
  46309. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46310. this._checkUniform(name);
  46311. this._vectors3[name] = value;
  46312. return this;
  46313. };
  46314. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46315. this._checkUniform(name);
  46316. this._vectors4[name] = value;
  46317. return this;
  46318. };
  46319. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46320. this._checkUniform(name);
  46321. this._matrices[name] = value;
  46322. return this;
  46323. };
  46324. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46325. this._checkUniform(name);
  46326. this._matrices3x3[name] = value;
  46327. return this;
  46328. };
  46329. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46330. this._checkUniform(name);
  46331. this._matrices2x2[name] = value;
  46332. return this;
  46333. };
  46334. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46335. this._checkUniform(name);
  46336. this._vectors3Arrays[name] = value;
  46337. return this;
  46338. };
  46339. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46340. if (!mesh) {
  46341. return true;
  46342. }
  46343. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46344. return false;
  46345. }
  46346. return false;
  46347. };
  46348. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46349. var scene = this.getScene();
  46350. var engine = scene.getEngine();
  46351. if (!this.checkReadyOnEveryCall) {
  46352. if (this._renderId === scene.getRenderId()) {
  46353. if (this._checkCache(scene, mesh, useInstances)) {
  46354. return true;
  46355. }
  46356. }
  46357. }
  46358. // Instances
  46359. var defines = [];
  46360. var attribs = [];
  46361. var fallbacks = new BABYLON.EffectFallbacks();
  46362. if (useInstances) {
  46363. defines.push("#define INSTANCES");
  46364. }
  46365. for (var index = 0; index < this._options.defines.length; index++) {
  46366. defines.push(this._options.defines[index]);
  46367. }
  46368. for (var index = 0; index < this._options.attributes.length; index++) {
  46369. attribs.push(this._options.attributes[index]);
  46370. }
  46371. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  46372. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46373. defines.push("#define VERTEXCOLOR");
  46374. }
  46375. // Bones
  46376. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  46377. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46378. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46379. if (mesh.numBoneInfluencers > 4) {
  46380. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46381. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46382. }
  46383. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46384. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46385. fallbacks.addCPUSkinningFallback(0, mesh);
  46386. if (this._options.uniforms.indexOf("mBones") === -1) {
  46387. this._options.uniforms.push("mBones");
  46388. }
  46389. }
  46390. else {
  46391. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46392. }
  46393. // Textures
  46394. for (var name in this._textures) {
  46395. if (!this._textures[name].isReady()) {
  46396. return false;
  46397. }
  46398. }
  46399. // Alpha test
  46400. if (engine.getAlphaTesting()) {
  46401. defines.push("#define ALPHATEST");
  46402. }
  46403. var previousEffect = this._effect;
  46404. var join = defines.join("\n");
  46405. this._effect = engine.createEffect(this._shaderPath, {
  46406. attributes: attribs,
  46407. uniformsNames: this._options.uniforms,
  46408. uniformBuffersNames: this._options.uniformBuffers,
  46409. samplers: this._options.samplers,
  46410. defines: join,
  46411. fallbacks: fallbacks,
  46412. onCompiled: this.onCompiled,
  46413. onError: this.onError
  46414. }, engine);
  46415. if (!this._effect.isReady()) {
  46416. return false;
  46417. }
  46418. if (previousEffect !== this._effect) {
  46419. scene.resetCachedMaterial();
  46420. }
  46421. this._renderId = scene.getRenderId();
  46422. return true;
  46423. };
  46424. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46425. var scene = this.getScene();
  46426. if (!this._effect) {
  46427. return;
  46428. }
  46429. if (this._options.uniforms.indexOf("world") !== -1) {
  46430. this._effect.setMatrix("world", world);
  46431. }
  46432. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46433. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46434. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46435. }
  46436. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46437. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46438. }
  46439. };
  46440. ShaderMaterial.prototype.bind = function (world, mesh) {
  46441. // Std values
  46442. this.bindOnlyWorldMatrix(world);
  46443. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  46444. if (this._options.uniforms.indexOf("view") !== -1) {
  46445. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46446. }
  46447. if (this._options.uniforms.indexOf("projection") !== -1) {
  46448. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46449. }
  46450. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46451. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46452. }
  46453. // Bones
  46454. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46455. var name;
  46456. // Texture
  46457. for (name in this._textures) {
  46458. this._effect.setTexture(name, this._textures[name]);
  46459. }
  46460. // Texture arrays
  46461. for (name in this._textureArrays) {
  46462. this._effect.setTextureArray(name, this._textureArrays[name]);
  46463. }
  46464. // Float
  46465. for (name in this._floats) {
  46466. this._effect.setFloat(name, this._floats[name]);
  46467. }
  46468. // Float s
  46469. for (name in this._floatsArrays) {
  46470. this._effect.setArray(name, this._floatsArrays[name]);
  46471. }
  46472. // Color3
  46473. for (name in this._colors3) {
  46474. this._effect.setColor3(name, this._colors3[name]);
  46475. }
  46476. for (name in this._colors3Arrays) {
  46477. this._effect.setArray3(name, this._colors3Arrays[name]);
  46478. }
  46479. // Color4
  46480. for (name in this._colors4) {
  46481. var color = this._colors4[name];
  46482. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46483. }
  46484. // Vector2
  46485. for (name in this._vectors2) {
  46486. this._effect.setVector2(name, this._vectors2[name]);
  46487. }
  46488. // Vector3
  46489. for (name in this._vectors3) {
  46490. this._effect.setVector3(name, this._vectors3[name]);
  46491. }
  46492. // Vector4
  46493. for (name in this._vectors4) {
  46494. this._effect.setVector4(name, this._vectors4[name]);
  46495. }
  46496. // Matrix
  46497. for (name in this._matrices) {
  46498. this._effect.setMatrix(name, this._matrices[name]);
  46499. }
  46500. // Matrix 3x3
  46501. for (name in this._matrices3x3) {
  46502. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46503. }
  46504. // Matrix 2x2
  46505. for (name in this._matrices2x2) {
  46506. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46507. }
  46508. // Vector3Array
  46509. for (name in this._vectors3Arrays) {
  46510. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46511. }
  46512. }
  46513. this._afterBind(mesh);
  46514. };
  46515. ShaderMaterial.prototype.getActiveTextures = function () {
  46516. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46517. for (var name in this._textures) {
  46518. activeTextures.push(this._textures[name]);
  46519. }
  46520. for (var name in this._textureArrays) {
  46521. var array = this._textureArrays[name];
  46522. for (var index = 0; index < array.length; index++) {
  46523. activeTextures.push(array[index]);
  46524. }
  46525. }
  46526. return activeTextures;
  46527. };
  46528. ShaderMaterial.prototype.hasTexture = function (texture) {
  46529. if (_super.prototype.hasTexture.call(this, texture)) {
  46530. return true;
  46531. }
  46532. for (var name in this._textures) {
  46533. if (this._textures[name] === texture) {
  46534. return true;
  46535. }
  46536. }
  46537. for (var name in this._textureArrays) {
  46538. var array = this._textureArrays[name];
  46539. for (var index = 0; index < array.length; index++) {
  46540. if (array[index] === texture) {
  46541. return true;
  46542. }
  46543. }
  46544. }
  46545. return false;
  46546. };
  46547. ShaderMaterial.prototype.clone = function (name) {
  46548. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46549. return newShaderMaterial;
  46550. };
  46551. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46552. if (forceDisposeTextures) {
  46553. var name;
  46554. for (name in this._textures) {
  46555. this._textures[name].dispose();
  46556. }
  46557. for (name in this._textureArrays) {
  46558. var array = this._textureArrays[name];
  46559. for (var index = 0; index < array.length; index++) {
  46560. array[index].dispose();
  46561. }
  46562. }
  46563. }
  46564. this._textures = {};
  46565. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46566. };
  46567. ShaderMaterial.prototype.serialize = function () {
  46568. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46569. serializationObject.customType = "BABYLON.ShaderMaterial";
  46570. serializationObject.options = this._options;
  46571. serializationObject.shaderPath = this._shaderPath;
  46572. var name;
  46573. // Texture
  46574. serializationObject.textures = {};
  46575. for (name in this._textures) {
  46576. serializationObject.textures[name] = this._textures[name].serialize();
  46577. }
  46578. // Texture arrays
  46579. serializationObject.textureArrays = {};
  46580. for (name in this._textureArrays) {
  46581. serializationObject.textureArrays[name] = [];
  46582. var array = this._textureArrays[name];
  46583. for (var index = 0; index < array.length; index++) {
  46584. serializationObject.textureArrays[name].push(array[index].serialize());
  46585. }
  46586. }
  46587. // Float
  46588. serializationObject.floats = {};
  46589. for (name in this._floats) {
  46590. serializationObject.floats[name] = this._floats[name];
  46591. }
  46592. // Float s
  46593. serializationObject.FloatArrays = {};
  46594. for (name in this._floatsArrays) {
  46595. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  46596. }
  46597. // Color3
  46598. serializationObject.colors3 = {};
  46599. for (name in this._colors3) {
  46600. serializationObject.colors3[name] = this._colors3[name].asArray();
  46601. }
  46602. // Color3 array
  46603. serializationObject.colors3Arrays = {};
  46604. for (name in this._colors3Arrays) {
  46605. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  46606. }
  46607. // Color4
  46608. serializationObject.colors4 = {};
  46609. for (name in this._colors4) {
  46610. serializationObject.colors4[name] = this._colors4[name].asArray();
  46611. }
  46612. // Vector2
  46613. serializationObject.vectors2 = {};
  46614. for (name in this._vectors2) {
  46615. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46616. }
  46617. // Vector3
  46618. serializationObject.vectors3 = {};
  46619. for (name in this._vectors3) {
  46620. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46621. }
  46622. // Vector4
  46623. serializationObject.vectors4 = {};
  46624. for (name in this._vectors4) {
  46625. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46626. }
  46627. // Matrix
  46628. serializationObject.matrices = {};
  46629. for (name in this._matrices) {
  46630. serializationObject.matrices[name] = this._matrices[name].asArray();
  46631. }
  46632. // Matrix 3x3
  46633. serializationObject.matrices3x3 = {};
  46634. for (name in this._matrices3x3) {
  46635. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46636. }
  46637. // Matrix 2x2
  46638. serializationObject.matrices2x2 = {};
  46639. for (name in this._matrices2x2) {
  46640. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46641. }
  46642. // Vector3Array
  46643. serializationObject.vectors3Arrays = {};
  46644. for (name in this._vectors3Arrays) {
  46645. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46646. }
  46647. return serializationObject;
  46648. };
  46649. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46650. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46651. var name;
  46652. // Texture
  46653. for (name in source.textures) {
  46654. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46655. }
  46656. // Texture arrays
  46657. for (name in source.textureArrays) {
  46658. var array = source.textureArrays[name];
  46659. var textureArray = new Array();
  46660. for (var index = 0; index < array.length; index++) {
  46661. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46662. }
  46663. material.setTextureArray(name, textureArray);
  46664. }
  46665. // Float
  46666. for (name in source.floats) {
  46667. material.setFloat(name, source.floats[name]);
  46668. }
  46669. // Float s
  46670. for (name in source.floatsArrays) {
  46671. material.setFloats(name, source.floatsArrays[name]);
  46672. }
  46673. // Color3
  46674. for (name in source.colors3) {
  46675. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46676. }
  46677. // Color3 arrays
  46678. for (name in source.colors3Arrays) {
  46679. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  46680. if (i % 3 === 0) {
  46681. arr.push([num]);
  46682. }
  46683. else {
  46684. arr[arr.length - 1].push(num);
  46685. }
  46686. return arr;
  46687. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  46688. material.setColor3Array(name, colors);
  46689. }
  46690. // Color4
  46691. for (name in source.colors4) {
  46692. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46693. }
  46694. // Vector2
  46695. for (name in source.vectors2) {
  46696. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46697. }
  46698. // Vector3
  46699. for (name in source.vectors3) {
  46700. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46701. }
  46702. // Vector4
  46703. for (name in source.vectors4) {
  46704. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46705. }
  46706. // Matrix
  46707. for (name in source.matrices) {
  46708. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46709. }
  46710. // Matrix 3x3
  46711. for (name in source.matrices3x3) {
  46712. material.setMatrix3x3(name, source.matrices3x3[name]);
  46713. }
  46714. // Matrix 2x2
  46715. for (name in source.matrices2x2) {
  46716. material.setMatrix2x2(name, source.matrices2x2[name]);
  46717. }
  46718. // Vector3Array
  46719. for (name in source.vectors3Arrays) {
  46720. material.setArray3(name, source.vectors3Arrays[name]);
  46721. }
  46722. return material;
  46723. };
  46724. return ShaderMaterial;
  46725. }(BABYLON.Material));
  46726. BABYLON.ShaderMaterial = ShaderMaterial;
  46727. })(BABYLON || (BABYLON = {}));
  46728. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46729. var BABYLON;
  46730. (function (BABYLON) {
  46731. var MeshBuilder = /** @class */ (function () {
  46732. function MeshBuilder() {
  46733. }
  46734. MeshBuilder.updateSideOrientation = function (orientation) {
  46735. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  46736. return BABYLON.Mesh.DOUBLESIDE;
  46737. }
  46738. if (orientation === undefined || orientation === null) {
  46739. return BABYLON.Mesh.FRONTSIDE;
  46740. }
  46741. return orientation;
  46742. };
  46743. /**
  46744. * Creates a box mesh.
  46745. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  46746. * The parameter `size` sets the size (float) of each box side (default 1).
  46747. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  46748. * 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).
  46749. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46750. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46751. * 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).
  46752. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46753. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46754. */
  46755. MeshBuilder.CreateBox = function (name, options, scene) {
  46756. if (scene === void 0) { scene = null; }
  46757. var box = new BABYLON.Mesh(name, scene);
  46758. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46759. box._originalBuilderSideOrientation = options.sideOrientation;
  46760. var vertexData = BABYLON.VertexData.CreateBox(options);
  46761. vertexData.applyToMesh(box, options.updatable);
  46762. return box;
  46763. };
  46764. /**
  46765. * Creates a sphere mesh.
  46766. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  46767. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  46768. * 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`).
  46769. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  46770. * 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
  46771. * 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).
  46772. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46773. * 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).
  46774. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46775. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46776. */
  46777. MeshBuilder.CreateSphere = function (name, options, scene) {
  46778. var sphere = new BABYLON.Mesh(name, scene);
  46779. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46780. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46781. var vertexData = BABYLON.VertexData.CreateSphere(options);
  46782. vertexData.applyToMesh(sphere, options.updatable);
  46783. return sphere;
  46784. };
  46785. /**
  46786. * Creates a plane polygonal mesh. By default, this is a disc.
  46787. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  46788. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  46789. * 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.
  46790. * 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
  46791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46792. * 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).
  46793. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46794. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46795. */
  46796. MeshBuilder.CreateDisc = function (name, options, scene) {
  46797. if (scene === void 0) { scene = null; }
  46798. var disc = new BABYLON.Mesh(name, scene);
  46799. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46800. disc._originalBuilderSideOrientation = options.sideOrientation;
  46801. var vertexData = BABYLON.VertexData.CreateDisc(options);
  46802. vertexData.applyToMesh(disc, options.updatable);
  46803. return disc;
  46804. };
  46805. /**
  46806. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  46807. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  46808. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  46809. * 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`).
  46810. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  46811. * 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.
  46812. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46813. * 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).
  46814. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46815. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46816. */
  46817. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  46818. var sphere = new BABYLON.Mesh(name, scene);
  46819. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46820. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46821. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  46822. vertexData.applyToMesh(sphere, options.updatable);
  46823. return sphere;
  46824. };
  46825. ;
  46826. /**
  46827. * Creates a ribbon mesh.
  46828. * 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.
  46829. *
  46830. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  46831. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  46832. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  46833. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  46834. * 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.
  46835. * 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.
  46836. * 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
  46837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46838. * 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).
  46839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46840. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46841. * 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.
  46842. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  46843. * 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
  46844. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  46845. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  46846. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46847. */
  46848. MeshBuilder.CreateRibbon = function (name, options, scene) {
  46849. if (scene === void 0) { scene = null; }
  46850. var pathArray = options.pathArray;
  46851. var closeArray = options.closeArray;
  46852. var closePath = options.closePath;
  46853. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46854. var instance = options.instance;
  46855. var updatable = options.updatable;
  46856. if (instance) {
  46857. // positionFunction : ribbon case
  46858. // only pathArray and sideOrientation parameters are taken into account for positions update
  46859. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  46860. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  46861. var positionFunction = function (positions) {
  46862. var minlg = pathArray[0].length;
  46863. var i = 0;
  46864. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  46865. for (var si = 1; si <= ns; si++) {
  46866. for (var p = 0; p < pathArray.length; p++) {
  46867. var path = pathArray[p];
  46868. var l = path.length;
  46869. minlg = (minlg < l) ? minlg : l;
  46870. var j = 0;
  46871. while (j < minlg) {
  46872. positions[i] = path[j].x;
  46873. positions[i + 1] = path[j].y;
  46874. positions[i + 2] = path[j].z;
  46875. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  46876. BABYLON.Tmp.Vector3[0].x = path[j].x;
  46877. }
  46878. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  46879. BABYLON.Tmp.Vector3[1].x = path[j].x;
  46880. }
  46881. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  46882. BABYLON.Tmp.Vector3[0].y = path[j].y;
  46883. }
  46884. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  46885. BABYLON.Tmp.Vector3[1].y = path[j].y;
  46886. }
  46887. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  46888. BABYLON.Tmp.Vector3[0].z = path[j].z;
  46889. }
  46890. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  46891. BABYLON.Tmp.Vector3[1].z = path[j].z;
  46892. }
  46893. j++;
  46894. i += 3;
  46895. }
  46896. if (instance._closePath) {
  46897. positions[i] = path[0].x;
  46898. positions[i + 1] = path[0].y;
  46899. positions[i + 2] = path[0].z;
  46900. i += 3;
  46901. }
  46902. }
  46903. }
  46904. };
  46905. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46906. positionFunction(positions);
  46907. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  46908. instance._boundingInfo.update(instance._worldMatrix);
  46909. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  46910. if (options.colors) {
  46911. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46912. for (var c = 0; c < options.colors.length; c++) {
  46913. colors[c * 4] = options.colors[c].r;
  46914. colors[c * 4 + 1] = options.colors[c].g;
  46915. colors[c * 4 + 2] = options.colors[c].b;
  46916. colors[c * 4 + 3] = options.colors[c].a;
  46917. }
  46918. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  46919. }
  46920. if (options.uvs) {
  46921. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46922. for (var i = 0; i < options.uvs.length; i++) {
  46923. uvs[i * 2] = options.uvs[i].x;
  46924. uvs[i * 2 + 1] = options.uvs[i].y;
  46925. }
  46926. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  46927. }
  46928. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  46929. var indices = instance.getIndices();
  46930. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46931. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  46932. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  46933. if (instance._closePath) {
  46934. var indexFirst = 0;
  46935. var indexLast = 0;
  46936. for (var p = 0; p < pathArray.length; p++) {
  46937. indexFirst = instance._idx[p] * 3;
  46938. if (p + 1 < pathArray.length) {
  46939. indexLast = (instance._idx[p + 1] - 1) * 3;
  46940. }
  46941. else {
  46942. indexLast = normals.length - 3;
  46943. }
  46944. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  46945. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  46946. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  46947. normals[indexLast] = normals[indexFirst];
  46948. normals[indexLast + 1] = normals[indexFirst + 1];
  46949. normals[indexLast + 2] = normals[indexFirst + 2];
  46950. }
  46951. }
  46952. if (!(instance.areNormalsFrozen)) {
  46953. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  46954. }
  46955. }
  46956. return instance;
  46957. }
  46958. else {
  46959. var ribbon = new BABYLON.Mesh(name, scene);
  46960. ribbon._originalBuilderSideOrientation = sideOrientation;
  46961. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  46962. if (closePath) {
  46963. ribbon._idx = vertexData._idx;
  46964. }
  46965. ribbon._closePath = closePath;
  46966. ribbon._closeArray = closeArray;
  46967. vertexData.applyToMesh(ribbon, updatable);
  46968. return ribbon;
  46969. }
  46970. };
  46971. /**
  46972. * Creates a cylinder or a cone mesh.
  46973. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  46974. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  46975. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  46976. * 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.
  46977. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  46978. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  46979. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  46980. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  46981. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  46982. * 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).
  46983. * 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
  46984. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  46985. * 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
  46986. * 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.
  46987. * If `enclose` is false, a ring surface is one element.
  46988. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  46989. * 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
  46990. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46991. * 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).
  46992. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46993. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46994. */
  46995. MeshBuilder.CreateCylinder = function (name, options, scene) {
  46996. var cylinder = new BABYLON.Mesh(name, scene);
  46997. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46998. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  46999. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47000. vertexData.applyToMesh(cylinder, options.updatable);
  47001. return cylinder;
  47002. };
  47003. /**
  47004. * Creates a torus mesh.
  47005. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47006. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47007. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47008. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47009. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47010. * 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).
  47011. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47012. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47013. */
  47014. MeshBuilder.CreateTorus = function (name, options, scene) {
  47015. var torus = new BABYLON.Mesh(name, scene);
  47016. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47017. torus._originalBuilderSideOrientation = options.sideOrientation;
  47018. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47019. vertexData.applyToMesh(torus, options.updatable);
  47020. return torus;
  47021. };
  47022. /**
  47023. * Creates a torus knot mesh.
  47024. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47025. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47026. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47027. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47028. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47029. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47030. * 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).
  47031. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47033. */
  47034. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47035. var torusKnot = new BABYLON.Mesh(name, scene);
  47036. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47037. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47038. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47039. vertexData.applyToMesh(torusKnot, options.updatable);
  47040. return torusKnot;
  47041. };
  47042. /**
  47043. * Creates a line system mesh.
  47044. * A line system is a pool of many lines gathered in a single mesh.
  47045. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47046. * 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.
  47047. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47048. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47049. * 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
  47050. * 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
  47051. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47053. */
  47054. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47055. var instance = options.instance;
  47056. var lines = options.lines;
  47057. if (instance) {
  47058. var positionFunction = function (positions) {
  47059. var i = 0;
  47060. for (var l = 0; l < lines.length; l++) {
  47061. var points = lines[l];
  47062. for (var p = 0; p < points.length; p++) {
  47063. positions[i] = points[p].x;
  47064. positions[i + 1] = points[p].y;
  47065. positions[i + 2] = points[p].z;
  47066. i += 3;
  47067. }
  47068. }
  47069. };
  47070. instance.updateMeshPositions(positionFunction, false);
  47071. return instance;
  47072. }
  47073. // line system creation
  47074. var lineSystem = new BABYLON.LinesMesh(name, scene);
  47075. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47076. vertexData.applyToMesh(lineSystem, options.updatable);
  47077. return lineSystem;
  47078. };
  47079. /**
  47080. * Creates a line mesh.
  47081. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47082. * 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.
  47083. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47084. * The parameter `points` is an array successive Vector3.
  47085. * 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
  47086. * When updating an instance, remember that only point positions can change, not the number of points.
  47087. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47088. */
  47089. MeshBuilder.CreateLines = function (name, options, scene) {
  47090. if (scene === void 0) { scene = null; }
  47091. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  47092. return lines;
  47093. };
  47094. /**
  47095. * Creates a dashed line mesh.
  47096. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47097. * 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.
  47098. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47099. * The parameter `points` is an array successive Vector3.
  47100. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47101. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47102. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47103. * 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
  47104. * When updating an instance, remember that only point positions can change, not the number of points.
  47105. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47106. */
  47107. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47108. if (scene === void 0) { scene = null; }
  47109. var points = options.points;
  47110. var instance = options.instance;
  47111. var gapSize = options.gapSize || 1;
  47112. var dashSize = options.dashSize || 3;
  47113. if (instance) {
  47114. var positionFunction = function (positions) {
  47115. var curvect = BABYLON.Vector3.Zero();
  47116. var nbSeg = positions.length / 6;
  47117. var lg = 0;
  47118. var nb = 0;
  47119. var shft = 0;
  47120. var dashshft = 0;
  47121. var curshft = 0;
  47122. var p = 0;
  47123. var i = 0;
  47124. var j = 0;
  47125. for (i = 0; i < points.length - 1; i++) {
  47126. points[i + 1].subtractToRef(points[i], curvect);
  47127. lg += curvect.length();
  47128. }
  47129. shft = lg / nbSeg;
  47130. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47131. for (i = 0; i < points.length - 1; i++) {
  47132. points[i + 1].subtractToRef(points[i], curvect);
  47133. nb = Math.floor(curvect.length() / shft);
  47134. curvect.normalize();
  47135. j = 0;
  47136. while (j < nb && p < positions.length) {
  47137. curshft = shft * j;
  47138. positions[p] = points[i].x + curshft * curvect.x;
  47139. positions[p + 1] = points[i].y + curshft * curvect.y;
  47140. positions[p + 2] = points[i].z + curshft * curvect.z;
  47141. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47142. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47143. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47144. p += 6;
  47145. j++;
  47146. }
  47147. }
  47148. while (p < positions.length) {
  47149. positions[p] = points[i].x;
  47150. positions[p + 1] = points[i].y;
  47151. positions[p + 2] = points[i].z;
  47152. p += 3;
  47153. }
  47154. };
  47155. instance.updateMeshPositions(positionFunction, false);
  47156. return instance;
  47157. }
  47158. // dashed lines creation
  47159. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47160. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47161. vertexData.applyToMesh(dashedLines, options.updatable);
  47162. dashedLines.dashSize = dashSize;
  47163. dashedLines.gapSize = gapSize;
  47164. return dashedLines;
  47165. };
  47166. /**
  47167. * Creates an extruded shape mesh.
  47168. * 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.
  47169. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47170. *
  47171. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47172. * 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
  47173. * extruded along the Z axis.
  47174. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47175. * 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.
  47176. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47177. * 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
  47178. * 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
  47179. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47180. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47181. * 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).
  47182. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47183. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47184. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47185. */
  47186. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  47187. if (scene === void 0) { scene = null; }
  47188. var path = options.path;
  47189. var shape = options.shape;
  47190. var scale = options.scale || 1;
  47191. var rotation = options.rotation || 0;
  47192. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47193. var updatable = options.updatable;
  47194. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47195. var instance = options.instance || null;
  47196. var invertUV = options.invertUV || false;
  47197. 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);
  47198. };
  47199. /**
  47200. * Creates an custom extruded shape mesh.
  47201. * 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.
  47202. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  47203. *
  47204. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47205. * 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
  47206. * extruded along the Z axis.
  47207. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47208. * 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
  47209. * and the distance of this point from the begining of the path :
  47210. * ```javascript
  47211. * var rotationFunction = function(i, distance) {
  47212. * // do things
  47213. * return rotationValue; }
  47214. * ```
  47215. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  47216. * 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
  47217. * and the distance of this point from the begining of the path :
  47218. * ```javascript
  47219. * var scaleFunction = function(i, distance) {
  47220. * // do things
  47221. * return scaleValue;}
  47222. * ```
  47223. * It must returns a float value that will be the scale value applied to the shape on each path point.
  47224. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  47225. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  47226. * 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
  47227. * 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
  47228. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47229. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47230. * 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).
  47231. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47232. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47234. */
  47235. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  47236. var path = options.path;
  47237. var shape = options.shape;
  47238. var scaleFunction = options.scaleFunction || (function () { return 1; });
  47239. var rotationFunction = options.rotationFunction || (function () { return 0; });
  47240. var ribbonCloseArray = options.ribbonCloseArray || false;
  47241. var ribbonClosePath = options.ribbonClosePath || false;
  47242. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47243. var updatable = options.updatable;
  47244. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47245. var instance = options.instance;
  47246. var invertUV = options.invertUV || false;
  47247. 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);
  47248. };
  47249. /**
  47250. * Creates lathe mesh.
  47251. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  47252. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  47253. *
  47254. * 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
  47255. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  47256. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  47257. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  47258. * 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.
  47259. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  47260. * 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
  47261. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47262. * 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).
  47263. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47264. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47265. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47266. */
  47267. MeshBuilder.CreateLathe = function (name, options, scene) {
  47268. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  47269. var closed = (options.closed === undefined) ? true : options.closed;
  47270. var shape = options.shape;
  47271. var radius = options.radius || 1;
  47272. var tessellation = options.tessellation || 64;
  47273. var updatable = options.updatable;
  47274. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47275. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47276. var pi2 = Math.PI * 2;
  47277. var paths = new Array();
  47278. var invertUV = options.invertUV || false;
  47279. var i = 0;
  47280. var p = 0;
  47281. var step = pi2 / tessellation * arc;
  47282. var rotated;
  47283. var path = new Array();
  47284. ;
  47285. for (i = 0; i <= tessellation; i++) {
  47286. var path = [];
  47287. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  47288. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  47289. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  47290. }
  47291. for (p = 0; p < shape.length; p++) {
  47292. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  47293. path.push(rotated);
  47294. }
  47295. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  47296. 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));
  47297. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  47298. }
  47299. paths.push(path);
  47300. }
  47301. // lathe ribbon
  47302. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47303. return lathe;
  47304. };
  47305. /**
  47306. * Creates a plane mesh.
  47307. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47308. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  47309. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  47310. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  47311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47312. * 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).
  47313. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47315. */
  47316. MeshBuilder.CreatePlane = function (name, options, scene) {
  47317. var plane = new BABYLON.Mesh(name, scene);
  47318. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47319. plane._originalBuilderSideOrientation = options.sideOrientation;
  47320. var vertexData = BABYLON.VertexData.CreatePlane(options);
  47321. vertexData.applyToMesh(plane, options.updatable);
  47322. if (options.sourcePlane) {
  47323. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  47324. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  47325. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  47326. plane.rotate(vectorProduct, product);
  47327. }
  47328. return plane;
  47329. };
  47330. /**
  47331. * Creates a ground mesh.
  47332. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47333. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  47334. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  47335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47336. */
  47337. MeshBuilder.CreateGround = function (name, options, scene) {
  47338. var ground = new BABYLON.GroundMesh(name, scene);
  47339. ground._setReady(false);
  47340. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  47341. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  47342. ground._width = options.width || 1;
  47343. ground._height = options.height || 1;
  47344. ground._maxX = ground._width / 2;
  47345. ground._maxZ = ground._height / 2;
  47346. ground._minX = -ground._maxX;
  47347. ground._minZ = -ground._maxZ;
  47348. var vertexData = BABYLON.VertexData.CreateGround(options);
  47349. vertexData.applyToMesh(ground, options.updatable);
  47350. ground._setReady(true);
  47351. return ground;
  47352. };
  47353. /**
  47354. * Creates a tiled ground mesh.
  47355. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  47356. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  47357. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  47358. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  47359. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  47360. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  47361. * numbers of subdivisions on the ground width and height of each tile.
  47362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47363. */
  47364. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  47365. var tiledGround = new BABYLON.Mesh(name, scene);
  47366. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  47367. vertexData.applyToMesh(tiledGround, options.updatable);
  47368. return tiledGround;
  47369. };
  47370. /**
  47371. * Creates a ground mesh from a height map.
  47372. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  47373. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  47374. * The parameter `url` sets the URL of the height map image resource.
  47375. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  47376. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  47377. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  47378. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  47379. * 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.
  47380. * 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).
  47381. * This function is passed the newly built mesh :
  47382. * ```javascript
  47383. * function(mesh) { // do things
  47384. * return; }
  47385. * ```
  47386. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47387. */
  47388. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  47389. var width = options.width || 10.0;
  47390. var height = options.height || 10.0;
  47391. var subdivisions = options.subdivisions || 1 | 0;
  47392. var minHeight = options.minHeight || 0.0;
  47393. var maxHeight = options.maxHeight || 1.0;
  47394. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  47395. var updatable = options.updatable;
  47396. var onReady = options.onReady;
  47397. var ground = new BABYLON.GroundMesh(name, scene);
  47398. ground._subdivisionsX = subdivisions;
  47399. ground._subdivisionsY = subdivisions;
  47400. ground._width = width;
  47401. ground._height = height;
  47402. ground._maxX = ground._width / 2.0;
  47403. ground._maxZ = ground._height / 2.0;
  47404. ground._minX = -ground._maxX;
  47405. ground._minZ = -ground._maxZ;
  47406. ground._setReady(false);
  47407. var onload = function (img) {
  47408. // Getting height map data
  47409. var canvas = document.createElement("canvas");
  47410. var context = canvas.getContext("2d");
  47411. if (!context) {
  47412. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  47413. }
  47414. var bufferWidth = img.width;
  47415. var bufferHeight = img.height;
  47416. canvas.width = bufferWidth;
  47417. canvas.height = bufferHeight;
  47418. context.drawImage(img, 0, 0);
  47419. // Create VertexData from map data
  47420. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  47421. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  47422. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  47423. width: width, height: height,
  47424. subdivisions: subdivisions,
  47425. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  47426. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  47427. });
  47428. vertexData.applyToMesh(ground, updatable);
  47429. ground._setReady(true);
  47430. //execute ready callback, if set
  47431. if (onReady) {
  47432. onReady(ground);
  47433. }
  47434. };
  47435. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  47436. return ground;
  47437. };
  47438. /**
  47439. * Creates a polygon mesh.
  47440. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  47441. * 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.
  47442. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47443. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47444. * 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).
  47445. * Remember you can only change the shape positions, not their number when updating a polygon.
  47446. */
  47447. MeshBuilder.CreatePolygon = function (name, options, scene) {
  47448. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47449. var shape = options.shape;
  47450. var holes = options.holes || [];
  47451. var depth = options.depth || 0;
  47452. var contours = [];
  47453. var hole = [];
  47454. for (var i = 0; i < shape.length; i++) {
  47455. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  47456. }
  47457. var epsilon = 0.00000001;
  47458. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  47459. contours.pop();
  47460. }
  47461. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  47462. for (var hNb = 0; hNb < holes.length; hNb++) {
  47463. hole = [];
  47464. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  47465. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  47466. }
  47467. polygonTriangulation.addHole(hole);
  47468. }
  47469. var polygon = polygonTriangulation.build(options.updatable, depth);
  47470. polygon._originalBuilderSideOrientation = options.sideOrientation;
  47471. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  47472. vertexData.applyToMesh(polygon, options.updatable);
  47473. return polygon;
  47474. };
  47475. ;
  47476. /**
  47477. * Creates an extruded polygon mesh, with depth in the Y direction.
  47478. * 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).
  47479. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47480. */
  47481. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  47482. return MeshBuilder.CreatePolygon(name, options, scene);
  47483. };
  47484. ;
  47485. /**
  47486. * Creates a tube mesh.
  47487. * 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.
  47488. *
  47489. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  47490. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  47491. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  47492. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  47493. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  47494. * 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.
  47495. * It must return a radius value (positive float) :
  47496. * ```javascript
  47497. * var radiusFunction = function(i, distance) {
  47498. * // do things
  47499. * return radius; }
  47500. * ```
  47501. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  47502. * 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
  47503. * 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
  47504. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47505. * 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).
  47506. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47507. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47508. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47509. */
  47510. MeshBuilder.CreateTube = function (name, options, scene) {
  47511. var path = options.path;
  47512. var instance = options.instance;
  47513. var radius = 1.0;
  47514. if (instance) {
  47515. radius = instance.radius;
  47516. }
  47517. if (options.radius !== undefined) {
  47518. radius = options.radius;
  47519. }
  47520. ;
  47521. var tessellation = options.tessellation || 64 | 0;
  47522. var radiusFunction = options.radiusFunction || null;
  47523. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47524. var invertUV = options.invertUV || false;
  47525. var updatable = options.updatable;
  47526. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47527. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  47528. // tube geometry
  47529. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  47530. var tangents = path3D.getTangents();
  47531. var normals = path3D.getNormals();
  47532. var distances = path3D.getDistances();
  47533. var pi2 = Math.PI * 2;
  47534. var step = pi2 / tessellation * arc;
  47535. var returnRadius = function () { return radius; };
  47536. var radiusFunctionFinal = radiusFunction || returnRadius;
  47537. var circlePath;
  47538. var rad;
  47539. var normal;
  47540. var rotated;
  47541. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47542. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47543. for (var i = 0; i < path.length; i++) {
  47544. rad = radiusFunctionFinal(i, distances[i]); // current radius
  47545. circlePath = Array(); // current circle array
  47546. normal = normals[i]; // current normal
  47547. for (var t = 0; t < tessellation; t++) {
  47548. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  47549. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  47550. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  47551. rotated.scaleInPlace(rad).addInPlace(path[i]);
  47552. circlePath[t] = rotated;
  47553. }
  47554. circlePaths[index] = circlePath;
  47555. index++;
  47556. }
  47557. // cap
  47558. var capPath = function (nbPoints, pathIndex) {
  47559. var pointCap = Array();
  47560. for (var i = 0; i < nbPoints; i++) {
  47561. pointCap.push(path[pathIndex]);
  47562. }
  47563. return pointCap;
  47564. };
  47565. switch (cap) {
  47566. case BABYLON.Mesh.NO_CAP:
  47567. break;
  47568. case BABYLON.Mesh.CAP_START:
  47569. circlePaths[0] = capPath(tessellation, 0);
  47570. circlePaths[1] = circlePaths[2].slice(0);
  47571. break;
  47572. case BABYLON.Mesh.CAP_END:
  47573. circlePaths[index] = circlePaths[index - 1].slice(0);
  47574. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47575. break;
  47576. case BABYLON.Mesh.CAP_ALL:
  47577. circlePaths[0] = capPath(tessellation, 0);
  47578. circlePaths[1] = circlePaths[2].slice(0);
  47579. circlePaths[index] = circlePaths[index - 1].slice(0);
  47580. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47581. break;
  47582. default:
  47583. break;
  47584. }
  47585. return circlePaths;
  47586. };
  47587. var path3D;
  47588. var pathArray;
  47589. if (instance) {
  47590. var arc = options.arc || instance.arc;
  47591. path3D = (instance.path3D).update(path);
  47592. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  47593. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  47594. instance.path3D = path3D;
  47595. instance.pathArray = pathArray;
  47596. instance.arc = arc;
  47597. instance.radius = radius;
  47598. return instance;
  47599. }
  47600. // tube creation
  47601. path3D = new BABYLON.Path3D(path);
  47602. var newPathArray = new Array();
  47603. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47604. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  47605. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47606. tube.pathArray = pathArray;
  47607. tube.path3D = path3D;
  47608. tube.tessellation = tessellation;
  47609. tube.cap = cap;
  47610. tube.arc = options.arc;
  47611. tube.radius = radius;
  47612. return tube;
  47613. };
  47614. /**
  47615. * Creates a polyhedron mesh.
  47616. *
  47617. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  47618. * 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
  47619. * to choose the wanted type.
  47620. * The parameter `size` (positive float, default 1) sets the polygon size.
  47621. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  47622. * 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`.
  47623. * 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
  47624. * 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)`).
  47625. * 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
  47626. * 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.
  47627. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47628. * 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).
  47629. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47630. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47631. */
  47632. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  47633. var polyhedron = new BABYLON.Mesh(name, scene);
  47634. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47635. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  47636. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  47637. vertexData.applyToMesh(polyhedron, options.updatable);
  47638. return polyhedron;
  47639. };
  47640. /**
  47641. * Creates a decal mesh.
  47642. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  47643. * 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.
  47644. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  47645. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  47646. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  47647. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  47648. */
  47649. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  47650. var indices = sourceMesh.getIndices();
  47651. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47652. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47653. var position = options.position || BABYLON.Vector3.Zero();
  47654. var normal = options.normal || BABYLON.Vector3.Up();
  47655. var size = options.size || BABYLON.Vector3.One();
  47656. var angle = options.angle || 0;
  47657. // Getting correct rotation
  47658. if (!normal) {
  47659. var target = new BABYLON.Vector3(0, 0, 1);
  47660. var camera = sourceMesh.getScene().activeCamera;
  47661. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  47662. normal = camera.globalPosition.subtract(cameraWorldTarget);
  47663. }
  47664. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  47665. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  47666. var pitch = Math.atan2(normal.y, len);
  47667. // Matrix
  47668. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  47669. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  47670. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  47671. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  47672. var vertexData = new BABYLON.VertexData();
  47673. vertexData.indices = [];
  47674. vertexData.positions = [];
  47675. vertexData.normals = [];
  47676. vertexData.uvs = [];
  47677. var currentVertexDataIndex = 0;
  47678. var extractDecalVector3 = function (indexId) {
  47679. var result = new BABYLON.PositionNormalVertex();
  47680. if (!indices || !positions || !normals) {
  47681. return result;
  47682. }
  47683. var vertexId = indices[indexId];
  47684. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  47685. // Send vector to decal local world
  47686. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  47687. // Get normal
  47688. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  47689. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  47690. return result;
  47691. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  47692. var clip = function (vertices, axis) {
  47693. if (vertices.length === 0) {
  47694. return vertices;
  47695. }
  47696. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  47697. var clipVertices = function (v0, v1) {
  47698. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  47699. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  47700. };
  47701. var result = new Array();
  47702. for (var index = 0; index < vertices.length; index += 3) {
  47703. var v1Out;
  47704. var v2Out;
  47705. var v3Out;
  47706. var total = 0;
  47707. var nV1 = null;
  47708. var nV2 = null;
  47709. var nV3 = null;
  47710. var nV4 = null;
  47711. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  47712. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  47713. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  47714. v1Out = d1 > 0;
  47715. v2Out = d2 > 0;
  47716. v3Out = d3 > 0;
  47717. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  47718. switch (total) {
  47719. case 0:
  47720. result.push(vertices[index]);
  47721. result.push(vertices[index + 1]);
  47722. result.push(vertices[index + 2]);
  47723. break;
  47724. case 1:
  47725. if (v1Out) {
  47726. nV1 = vertices[index + 1];
  47727. nV2 = vertices[index + 2];
  47728. nV3 = clipVertices(vertices[index], nV1);
  47729. nV4 = clipVertices(vertices[index], nV2);
  47730. }
  47731. if (v2Out) {
  47732. nV1 = vertices[index];
  47733. nV2 = vertices[index + 2];
  47734. nV3 = clipVertices(vertices[index + 1], nV1);
  47735. nV4 = clipVertices(vertices[index + 1], nV2);
  47736. result.push(nV3);
  47737. result.push(nV2.clone());
  47738. result.push(nV1.clone());
  47739. result.push(nV2.clone());
  47740. result.push(nV3.clone());
  47741. result.push(nV4);
  47742. break;
  47743. }
  47744. if (v3Out) {
  47745. nV1 = vertices[index];
  47746. nV2 = vertices[index + 1];
  47747. nV3 = clipVertices(vertices[index + 2], nV1);
  47748. nV4 = clipVertices(vertices[index + 2], nV2);
  47749. }
  47750. if (nV1 && nV2 && nV3 && nV4) {
  47751. result.push(nV1.clone());
  47752. result.push(nV2.clone());
  47753. result.push(nV3);
  47754. result.push(nV4);
  47755. result.push(nV3.clone());
  47756. result.push(nV2.clone());
  47757. }
  47758. break;
  47759. case 2:
  47760. if (!v1Out) {
  47761. nV1 = vertices[index].clone();
  47762. nV2 = clipVertices(nV1, vertices[index + 1]);
  47763. nV3 = clipVertices(nV1, vertices[index + 2]);
  47764. result.push(nV1);
  47765. result.push(nV2);
  47766. result.push(nV3);
  47767. }
  47768. if (!v2Out) {
  47769. nV1 = vertices[index + 1].clone();
  47770. nV2 = clipVertices(nV1, vertices[index + 2]);
  47771. nV3 = clipVertices(nV1, vertices[index]);
  47772. result.push(nV1);
  47773. result.push(nV2);
  47774. result.push(nV3);
  47775. }
  47776. if (!v3Out) {
  47777. nV1 = vertices[index + 2].clone();
  47778. nV2 = clipVertices(nV1, vertices[index]);
  47779. nV3 = clipVertices(nV1, vertices[index + 1]);
  47780. result.push(nV1);
  47781. result.push(nV2);
  47782. result.push(nV3);
  47783. }
  47784. break;
  47785. case 3:
  47786. break;
  47787. }
  47788. }
  47789. return result;
  47790. };
  47791. for (var index = 0; index < indices.length; index += 3) {
  47792. var faceVertices = new Array();
  47793. faceVertices.push(extractDecalVector3(index));
  47794. faceVertices.push(extractDecalVector3(index + 1));
  47795. faceVertices.push(extractDecalVector3(index + 2));
  47796. // Clip
  47797. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  47798. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  47799. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  47800. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  47801. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  47802. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  47803. if (faceVertices.length === 0) {
  47804. continue;
  47805. }
  47806. // Add UVs and get back to world
  47807. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  47808. var vertex = faceVertices[vIndex];
  47809. //TODO check for Int32Array | Uint32Array | Uint16Array
  47810. vertexData.indices.push(currentVertexDataIndex);
  47811. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  47812. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  47813. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  47814. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  47815. currentVertexDataIndex++;
  47816. }
  47817. }
  47818. // Return mesh
  47819. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  47820. vertexData.applyToMesh(decal);
  47821. decal.position = position.clone();
  47822. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  47823. return decal;
  47824. };
  47825. // Privates
  47826. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  47827. // extrusion geometry
  47828. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  47829. var tangents = path3D.getTangents();
  47830. var normals = path3D.getNormals();
  47831. var binormals = path3D.getBinormals();
  47832. var distances = path3D.getDistances();
  47833. var angle = 0;
  47834. var returnScale = function () { return scale !== null ? scale : 1; };
  47835. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  47836. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  47837. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  47838. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47839. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47840. for (var i = 0; i < curve.length; i++) {
  47841. var shapePath = new Array();
  47842. var angleStep = rotate(i, distances[i]);
  47843. var scaleRatio = scl(i, distances[i]);
  47844. for (var p = 0; p < shape.length; p++) {
  47845. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  47846. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  47847. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  47848. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  47849. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  47850. shapePath[p] = rotated;
  47851. }
  47852. shapePaths[index] = shapePath;
  47853. angle += angleStep;
  47854. index++;
  47855. }
  47856. // cap
  47857. var capPath = function (shapePath) {
  47858. var pointCap = Array();
  47859. var barycenter = BABYLON.Vector3.Zero();
  47860. var i;
  47861. for (i = 0; i < shapePath.length; i++) {
  47862. barycenter.addInPlace(shapePath[i]);
  47863. }
  47864. barycenter.scaleInPlace(1.0 / shapePath.length);
  47865. for (i = 0; i < shapePath.length; i++) {
  47866. pointCap.push(barycenter);
  47867. }
  47868. return pointCap;
  47869. };
  47870. switch (cap) {
  47871. case BABYLON.Mesh.NO_CAP:
  47872. break;
  47873. case BABYLON.Mesh.CAP_START:
  47874. shapePaths[0] = capPath(shapePaths[2]);
  47875. shapePaths[1] = shapePaths[2];
  47876. break;
  47877. case BABYLON.Mesh.CAP_END:
  47878. shapePaths[index] = shapePaths[index - 1];
  47879. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  47880. break;
  47881. case BABYLON.Mesh.CAP_ALL:
  47882. shapePaths[0] = capPath(shapePaths[2]);
  47883. shapePaths[1] = shapePaths[2];
  47884. shapePaths[index] = shapePaths[index - 1];
  47885. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  47886. break;
  47887. default:
  47888. break;
  47889. }
  47890. return shapePaths;
  47891. };
  47892. var path3D;
  47893. var pathArray;
  47894. if (instance) {
  47895. path3D = (instance.path3D).update(curve);
  47896. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  47897. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  47898. return instance;
  47899. }
  47900. // extruded shape creation
  47901. path3D = new BABYLON.Path3D(curve);
  47902. var newShapePaths = new Array();
  47903. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47904. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  47905. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  47906. extrudedGeneric.pathArray = pathArray;
  47907. extrudedGeneric.path3D = path3D;
  47908. extrudedGeneric.cap = cap;
  47909. return extrudedGeneric;
  47910. };
  47911. return MeshBuilder;
  47912. }());
  47913. BABYLON.MeshBuilder = MeshBuilder;
  47914. })(BABYLON || (BABYLON = {}));
  47915. //# sourceMappingURL=babylon.meshBuilder.js.map
  47916. var BABYLON;
  47917. (function (BABYLON) {
  47918. var AudioEngine = /** @class */ (function () {
  47919. function AudioEngine() {
  47920. this._audioContext = null;
  47921. this._audioContextInitialized = false;
  47922. this.canUseWebAudio = false;
  47923. this.WarnedWebAudioUnsupported = false;
  47924. this.unlocked = false;
  47925. this.isMP3supported = false;
  47926. this.isOGGsupported = false;
  47927. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  47928. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  47929. this.canUseWebAudio = true;
  47930. }
  47931. var audioElem = document.createElement('audio');
  47932. try {
  47933. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  47934. this.isMP3supported = true;
  47935. }
  47936. }
  47937. catch (e) {
  47938. // protect error during capability check.
  47939. }
  47940. try {
  47941. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  47942. this.isOGGsupported = true;
  47943. }
  47944. }
  47945. catch (e) {
  47946. // protect error during capability check.
  47947. }
  47948. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  47949. this._unlockiOSaudio();
  47950. }
  47951. else {
  47952. this.unlocked = true;
  47953. }
  47954. }
  47955. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  47956. get: function () {
  47957. if (!this._audioContextInitialized) {
  47958. this._initializeAudioContext();
  47959. }
  47960. return this._audioContext;
  47961. },
  47962. enumerable: true,
  47963. configurable: true
  47964. });
  47965. AudioEngine.prototype._unlockiOSaudio = function () {
  47966. var _this = this;
  47967. var unlockaudio = function () {
  47968. if (!_this.audioContext) {
  47969. return;
  47970. }
  47971. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  47972. var source = _this.audioContext.createBufferSource();
  47973. source.buffer = buffer;
  47974. source.connect(_this.audioContext.destination);
  47975. source.start(0);
  47976. setTimeout(function () {
  47977. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  47978. _this.unlocked = true;
  47979. window.removeEventListener('touchend', unlockaudio, false);
  47980. if (_this.onAudioUnlocked) {
  47981. _this.onAudioUnlocked();
  47982. }
  47983. }
  47984. }, 0);
  47985. };
  47986. window.addEventListener('touchend', unlockaudio, false);
  47987. };
  47988. AudioEngine.prototype._initializeAudioContext = function () {
  47989. try {
  47990. if (this.canUseWebAudio) {
  47991. this._audioContext = new AudioContext();
  47992. // create a global volume gain node
  47993. this.masterGain = this._audioContext.createGain();
  47994. this.masterGain.gain.value = 1;
  47995. this.masterGain.connect(this._audioContext.destination);
  47996. this._audioContextInitialized = true;
  47997. }
  47998. }
  47999. catch (e) {
  48000. this.canUseWebAudio = false;
  48001. BABYLON.Tools.Error("Web Audio: " + e.message);
  48002. }
  48003. };
  48004. AudioEngine.prototype.dispose = function () {
  48005. if (this.canUseWebAudio && this._audioContextInitialized) {
  48006. if (this._connectedAnalyser && this._audioContext) {
  48007. this._connectedAnalyser.stopDebugCanvas();
  48008. this._connectedAnalyser.dispose();
  48009. this.masterGain.disconnect();
  48010. this.masterGain.connect(this._audioContext.destination);
  48011. this._connectedAnalyser = null;
  48012. }
  48013. this.masterGain.gain.value = 1;
  48014. }
  48015. this.WarnedWebAudioUnsupported = false;
  48016. };
  48017. AudioEngine.prototype.getGlobalVolume = function () {
  48018. if (this.canUseWebAudio && this._audioContextInitialized) {
  48019. return this.masterGain.gain.value;
  48020. }
  48021. else {
  48022. return -1;
  48023. }
  48024. };
  48025. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48026. if (this.canUseWebAudio && this._audioContextInitialized) {
  48027. this.masterGain.gain.value = newVolume;
  48028. }
  48029. };
  48030. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48031. if (this._connectedAnalyser) {
  48032. this._connectedAnalyser.stopDebugCanvas();
  48033. }
  48034. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48035. this._connectedAnalyser = analyser;
  48036. this.masterGain.disconnect();
  48037. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48038. }
  48039. };
  48040. return AudioEngine;
  48041. }());
  48042. BABYLON.AudioEngine = AudioEngine;
  48043. })(BABYLON || (BABYLON = {}));
  48044. //# sourceMappingURL=babylon.audioEngine.js.map
  48045. var BABYLON;
  48046. (function (BABYLON) {
  48047. var Sound = /** @class */ (function () {
  48048. /**
  48049. * Create a sound and attach it to a scene
  48050. * @param name Name of your sound
  48051. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48052. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48053. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48054. */
  48055. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48056. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48057. var _this = this;
  48058. this.autoplay = false;
  48059. this.loop = false;
  48060. this.useCustomAttenuation = false;
  48061. this.spatialSound = false;
  48062. this.refDistance = 1;
  48063. this.rolloffFactor = 1;
  48064. this.maxDistance = 100;
  48065. this.distanceModel = "linear";
  48066. this._panningModel = "equalpower";
  48067. this._playbackRate = 1;
  48068. this._streaming = false;
  48069. this._startTime = 0;
  48070. this._startOffset = 0;
  48071. this._position = BABYLON.Vector3.Zero();
  48072. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48073. this._volume = 1;
  48074. this._isLoaded = false;
  48075. this._isReadyToPlay = false;
  48076. this.isPlaying = false;
  48077. this.isPaused = false;
  48078. this._isDirectional = false;
  48079. // Used if you'd like to create a directional sound.
  48080. // If not set, the sound will be omnidirectional
  48081. this._coneInnerAngle = 360;
  48082. this._coneOuterAngle = 360;
  48083. this._coneOuterGain = 0;
  48084. this._isOutputConnected = false;
  48085. this._urlType = "Unknown";
  48086. this.name = name;
  48087. this._scene = scene;
  48088. this._readyToPlayCallback = readyToPlayCallback;
  48089. // Default custom attenuation function is a linear attenuation
  48090. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48091. if (currentDistance < maxDistance) {
  48092. return currentVolume * (1 - currentDistance / maxDistance);
  48093. }
  48094. else {
  48095. return 0;
  48096. }
  48097. };
  48098. if (options) {
  48099. this.autoplay = options.autoplay || false;
  48100. this.loop = options.loop || false;
  48101. // if volume === 0, we need another way to check this option
  48102. if (options.volume !== undefined) {
  48103. this._volume = options.volume;
  48104. }
  48105. this.spatialSound = options.spatialSound || false;
  48106. this.maxDistance = options.maxDistance || 100;
  48107. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48108. this.rolloffFactor = options.rolloffFactor || 1;
  48109. this.refDistance = options.refDistance || 1;
  48110. this.distanceModel = options.distanceModel || "linear";
  48111. this._playbackRate = options.playbackRate || 1;
  48112. this._streaming = options.streaming || false;
  48113. }
  48114. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48115. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48116. this._soundGain.gain.value = this._volume;
  48117. this._inputAudioNode = this._soundGain;
  48118. this._ouputAudioNode = this._soundGain;
  48119. if (this.spatialSound) {
  48120. this._createSpatialParameters();
  48121. }
  48122. this._scene.mainSoundTrack.AddSound(this);
  48123. var validParameter = true;
  48124. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48125. if (urlOrArrayBuffer) {
  48126. if (typeof (urlOrArrayBuffer) === "string")
  48127. this._urlType = "String";
  48128. if (Array.isArray(urlOrArrayBuffer))
  48129. this._urlType = "Array";
  48130. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48131. this._urlType = "ArrayBuffer";
  48132. var urls = [];
  48133. var codecSupportedFound = false;
  48134. switch (this._urlType) {
  48135. case "ArrayBuffer":
  48136. if (urlOrArrayBuffer.byteLength > 0) {
  48137. codecSupportedFound = true;
  48138. this._soundLoaded(urlOrArrayBuffer);
  48139. }
  48140. break;
  48141. case "String":
  48142. urls.push(urlOrArrayBuffer);
  48143. case "Array":
  48144. if (urls.length === 0)
  48145. urls = urlOrArrayBuffer;
  48146. // If we found a supported format, we load it immediately and stop the loop
  48147. for (var i = 0; i < urls.length; i++) {
  48148. var url = urls[i];
  48149. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48150. codecSupportedFound = true;
  48151. }
  48152. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48153. codecSupportedFound = true;
  48154. }
  48155. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48156. codecSupportedFound = true;
  48157. }
  48158. if (url.indexOf("blob:") !== -1) {
  48159. codecSupportedFound = true;
  48160. }
  48161. if (codecSupportedFound) {
  48162. // Loading sound using XHR2
  48163. if (!this._streaming) {
  48164. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48165. }
  48166. else {
  48167. this._htmlAudioElement = new Audio(url);
  48168. this._htmlAudioElement.controls = false;
  48169. this._htmlAudioElement.loop = this.loop;
  48170. this._htmlAudioElement.crossOrigin = "anonymous";
  48171. this._htmlAudioElement.preload = "auto";
  48172. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48173. _this._isReadyToPlay = true;
  48174. if (_this.autoplay) {
  48175. _this.play();
  48176. }
  48177. if (_this._readyToPlayCallback) {
  48178. _this._readyToPlayCallback();
  48179. }
  48180. });
  48181. document.body.appendChild(this._htmlAudioElement);
  48182. }
  48183. break;
  48184. }
  48185. }
  48186. break;
  48187. default:
  48188. validParameter = false;
  48189. break;
  48190. }
  48191. if (!validParameter) {
  48192. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  48193. }
  48194. else {
  48195. if (!codecSupportedFound) {
  48196. this._isReadyToPlay = true;
  48197. // Simulating a ready to play event to avoid breaking code path
  48198. if (this._readyToPlayCallback) {
  48199. window.setTimeout(function () {
  48200. if (_this._readyToPlayCallback) {
  48201. _this._readyToPlayCallback();
  48202. }
  48203. }, 1000);
  48204. }
  48205. }
  48206. }
  48207. }
  48208. }
  48209. else {
  48210. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  48211. this._scene.mainSoundTrack.AddSound(this);
  48212. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  48213. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  48214. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  48215. }
  48216. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  48217. if (this._readyToPlayCallback) {
  48218. window.setTimeout(function () {
  48219. if (_this._readyToPlayCallback) {
  48220. _this._readyToPlayCallback();
  48221. }
  48222. }, 1000);
  48223. }
  48224. }
  48225. }
  48226. Sound.prototype.dispose = function () {
  48227. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  48228. if (this.isPlaying) {
  48229. this.stop();
  48230. }
  48231. this._isReadyToPlay = false;
  48232. if (this.soundTrackId === -1) {
  48233. this._scene.mainSoundTrack.RemoveSound(this);
  48234. }
  48235. else {
  48236. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  48237. }
  48238. if (this._soundGain) {
  48239. this._soundGain.disconnect();
  48240. this._soundGain = null;
  48241. }
  48242. if (this._soundPanner) {
  48243. this._soundPanner.disconnect();
  48244. this._soundPanner = null;
  48245. }
  48246. if (this._soundSource) {
  48247. this._soundSource.disconnect();
  48248. this._soundSource = null;
  48249. }
  48250. this._audioBuffer = null;
  48251. if (this._htmlAudioElement) {
  48252. this._htmlAudioElement.pause();
  48253. this._htmlAudioElement.src = "";
  48254. document.body.removeChild(this._htmlAudioElement);
  48255. }
  48256. if (this._connectedMesh && this._registerFunc) {
  48257. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48258. this._connectedMesh = null;
  48259. }
  48260. }
  48261. };
  48262. Sound.prototype.isReady = function () {
  48263. return this._isReadyToPlay;
  48264. };
  48265. Sound.prototype._soundLoaded = function (audioData) {
  48266. var _this = this;
  48267. this._isLoaded = true;
  48268. if (!BABYLON.Engine.audioEngine.audioContext) {
  48269. return;
  48270. }
  48271. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  48272. _this._audioBuffer = buffer;
  48273. _this._isReadyToPlay = true;
  48274. if (_this.autoplay) {
  48275. _this.play();
  48276. }
  48277. if (_this._readyToPlayCallback) {
  48278. _this._readyToPlayCallback();
  48279. }
  48280. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  48281. };
  48282. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  48283. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48284. this._audioBuffer = audioBuffer;
  48285. this._isReadyToPlay = true;
  48286. }
  48287. };
  48288. Sound.prototype.updateOptions = function (options) {
  48289. if (options) {
  48290. this.loop = options.loop || this.loop;
  48291. this.maxDistance = options.maxDistance || this.maxDistance;
  48292. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  48293. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  48294. this.refDistance = options.refDistance || this.refDistance;
  48295. this.distanceModel = options.distanceModel || this.distanceModel;
  48296. this._playbackRate = options.playbackRate || this._playbackRate;
  48297. this._updateSpatialParameters();
  48298. if (this.isPlaying) {
  48299. if (this._streaming) {
  48300. this._htmlAudioElement.playbackRate = this._playbackRate;
  48301. }
  48302. else {
  48303. if (this._soundSource) {
  48304. this._soundSource.playbackRate.value = this._playbackRate;
  48305. }
  48306. }
  48307. }
  48308. }
  48309. };
  48310. Sound.prototype._createSpatialParameters = function () {
  48311. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48312. if (this._scene.headphone) {
  48313. this._panningModel = "HRTF";
  48314. }
  48315. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  48316. this._updateSpatialParameters();
  48317. this._soundPanner.connect(this._ouputAudioNode);
  48318. this._inputAudioNode = this._soundPanner;
  48319. }
  48320. };
  48321. Sound.prototype._updateSpatialParameters = function () {
  48322. if (this.spatialSound && this._soundPanner) {
  48323. if (this.useCustomAttenuation) {
  48324. // Tricks to disable in a way embedded Web Audio attenuation
  48325. this._soundPanner.distanceModel = "linear";
  48326. this._soundPanner.maxDistance = Number.MAX_VALUE;
  48327. this._soundPanner.refDistance = 1;
  48328. this._soundPanner.rolloffFactor = 1;
  48329. this._soundPanner.panningModel = this._panningModel;
  48330. }
  48331. else {
  48332. this._soundPanner.distanceModel = this.distanceModel;
  48333. this._soundPanner.maxDistance = this.maxDistance;
  48334. this._soundPanner.refDistance = this.refDistance;
  48335. this._soundPanner.rolloffFactor = this.rolloffFactor;
  48336. this._soundPanner.panningModel = this._panningModel;
  48337. }
  48338. }
  48339. };
  48340. Sound.prototype.switchPanningModelToHRTF = function () {
  48341. this._panningModel = "HRTF";
  48342. this._switchPanningModel();
  48343. };
  48344. Sound.prototype.switchPanningModelToEqualPower = function () {
  48345. this._panningModel = "equalpower";
  48346. this._switchPanningModel();
  48347. };
  48348. Sound.prototype._switchPanningModel = function () {
  48349. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48350. this._soundPanner.panningModel = this._panningModel;
  48351. }
  48352. };
  48353. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  48354. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48355. if (this._isOutputConnected) {
  48356. this._ouputAudioNode.disconnect();
  48357. }
  48358. this._ouputAudioNode.connect(soundTrackAudioNode);
  48359. this._isOutputConnected = true;
  48360. }
  48361. };
  48362. /**
  48363. * Transform this sound into a directional source
  48364. * @param coneInnerAngle Size of the inner cone in degree
  48365. * @param coneOuterAngle Size of the outer cone in degree
  48366. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  48367. */
  48368. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  48369. if (coneOuterAngle < coneInnerAngle) {
  48370. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  48371. return;
  48372. }
  48373. this._coneInnerAngle = coneInnerAngle;
  48374. this._coneOuterAngle = coneOuterAngle;
  48375. this._coneOuterGain = coneOuterGain;
  48376. this._isDirectional = true;
  48377. if (this.isPlaying && this.loop) {
  48378. this.stop();
  48379. this.play();
  48380. }
  48381. };
  48382. Sound.prototype.setPosition = function (newPosition) {
  48383. this._position = newPosition;
  48384. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48385. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48386. }
  48387. };
  48388. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  48389. this._localDirection = newLocalDirection;
  48390. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  48391. this._updateDirection();
  48392. }
  48393. };
  48394. Sound.prototype._updateDirection = function () {
  48395. if (!this._connectedMesh || !this._soundPanner) {
  48396. return;
  48397. }
  48398. var mat = this._connectedMesh.getWorldMatrix();
  48399. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  48400. direction.normalize();
  48401. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  48402. };
  48403. Sound.prototype.updateDistanceFromListener = function () {
  48404. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  48405. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  48406. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  48407. }
  48408. };
  48409. Sound.prototype.setAttenuationFunction = function (callback) {
  48410. this._customAttenuationFunction = callback;
  48411. };
  48412. /**
  48413. * Play the sound
  48414. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  48415. * @param offset (optional) Start the sound setting it at a specific time
  48416. */
  48417. Sound.prototype.play = function (time, offset) {
  48418. var _this = this;
  48419. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  48420. try {
  48421. if (this._startOffset < 0) {
  48422. time = -this._startOffset;
  48423. this._startOffset = 0;
  48424. }
  48425. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48426. if (!this._soundSource || !this._streamingSource) {
  48427. if (this.spatialSound && this._soundPanner) {
  48428. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48429. if (this._isDirectional) {
  48430. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  48431. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  48432. this._soundPanner.coneOuterGain = this._coneOuterGain;
  48433. if (this._connectedMesh) {
  48434. this._updateDirection();
  48435. }
  48436. else {
  48437. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  48438. }
  48439. }
  48440. }
  48441. }
  48442. if (this._streaming) {
  48443. if (!this._streamingSource) {
  48444. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  48445. this._htmlAudioElement.onended = function () { _this._onended(); };
  48446. this._htmlAudioElement.playbackRate = this._playbackRate;
  48447. }
  48448. this._streamingSource.disconnect();
  48449. this._streamingSource.connect(this._inputAudioNode);
  48450. this._htmlAudioElement.play();
  48451. }
  48452. else {
  48453. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  48454. this._soundSource.buffer = this._audioBuffer;
  48455. this._soundSource.connect(this._inputAudioNode);
  48456. this._soundSource.loop = this.loop;
  48457. this._soundSource.playbackRate.value = this._playbackRate;
  48458. this._soundSource.onended = function () { _this._onended(); };
  48459. if (this._soundSource.buffer) {
  48460. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  48461. }
  48462. }
  48463. this._startTime = startTime;
  48464. this.isPlaying = true;
  48465. this.isPaused = false;
  48466. }
  48467. catch (ex) {
  48468. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  48469. }
  48470. }
  48471. };
  48472. Sound.prototype._onended = function () {
  48473. this.isPlaying = false;
  48474. if (this.onended) {
  48475. this.onended();
  48476. }
  48477. };
  48478. /**
  48479. * Stop the sound
  48480. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  48481. */
  48482. Sound.prototype.stop = function (time) {
  48483. if (this.isPlaying) {
  48484. if (this._streaming) {
  48485. this._htmlAudioElement.pause();
  48486. // Test needed for Firefox or it will generate an Invalid State Error
  48487. if (this._htmlAudioElement.currentTime > 0) {
  48488. this._htmlAudioElement.currentTime = 0;
  48489. }
  48490. }
  48491. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  48492. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48493. this._soundSource.stop(stopTime);
  48494. this._soundSource.onended = function () { };
  48495. if (!this.isPaused) {
  48496. this._startOffset = 0;
  48497. }
  48498. }
  48499. this.isPlaying = false;
  48500. }
  48501. };
  48502. Sound.prototype.pause = function () {
  48503. if (this.isPlaying) {
  48504. this.isPaused = true;
  48505. if (this._streaming) {
  48506. this._htmlAudioElement.pause();
  48507. }
  48508. else if (BABYLON.Engine.audioEngine.audioContext) {
  48509. this.stop(0);
  48510. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  48511. }
  48512. }
  48513. };
  48514. Sound.prototype.setVolume = function (newVolume, time) {
  48515. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  48516. if (time && BABYLON.Engine.audioEngine.audioContext) {
  48517. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  48518. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  48519. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  48520. }
  48521. else {
  48522. this._soundGain.gain.value = newVolume;
  48523. }
  48524. }
  48525. this._volume = newVolume;
  48526. };
  48527. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  48528. this._playbackRate = newPlaybackRate;
  48529. if (this.isPlaying) {
  48530. if (this._streaming) {
  48531. this._htmlAudioElement.playbackRate = this._playbackRate;
  48532. }
  48533. else if (this._soundSource) {
  48534. this._soundSource.playbackRate.value = this._playbackRate;
  48535. }
  48536. }
  48537. };
  48538. Sound.prototype.getVolume = function () {
  48539. return this._volume;
  48540. };
  48541. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  48542. var _this = this;
  48543. if (this._connectedMesh && this._registerFunc) {
  48544. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48545. this._registerFunc = null;
  48546. }
  48547. this._connectedMesh = meshToConnectTo;
  48548. if (!this.spatialSound) {
  48549. this.spatialSound = true;
  48550. this._createSpatialParameters();
  48551. if (this.isPlaying && this.loop) {
  48552. this.stop();
  48553. this.play();
  48554. }
  48555. }
  48556. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  48557. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  48558. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  48559. };
  48560. Sound.prototype.detachFromMesh = function () {
  48561. if (this._connectedMesh && this._registerFunc) {
  48562. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48563. this._registerFunc = null;
  48564. this._connectedMesh = null;
  48565. }
  48566. };
  48567. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  48568. var boundingInfo = connectedMesh.getBoundingInfo();
  48569. if (!boundingInfo) {
  48570. return;
  48571. }
  48572. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  48573. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  48574. this._updateDirection();
  48575. }
  48576. };
  48577. Sound.prototype.clone = function () {
  48578. var _this = this;
  48579. if (!this._streaming) {
  48580. var setBufferAndRun = function () {
  48581. if (_this._isReadyToPlay) {
  48582. clonedSound._audioBuffer = _this.getAudioBuffer();
  48583. clonedSound._isReadyToPlay = true;
  48584. if (clonedSound.autoplay) {
  48585. clonedSound.play();
  48586. }
  48587. }
  48588. else {
  48589. window.setTimeout(setBufferAndRun, 300);
  48590. }
  48591. };
  48592. var currentOptions = {
  48593. autoplay: this.autoplay, loop: this.loop,
  48594. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  48595. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  48596. refDistance: this.refDistance, distanceModel: this.distanceModel
  48597. };
  48598. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  48599. if (this.useCustomAttenuation) {
  48600. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  48601. }
  48602. clonedSound.setPosition(this._position);
  48603. clonedSound.setPlaybackRate(this._playbackRate);
  48604. setBufferAndRun();
  48605. return clonedSound;
  48606. }
  48607. else {
  48608. return null;
  48609. }
  48610. };
  48611. Sound.prototype.getAudioBuffer = function () {
  48612. return this._audioBuffer;
  48613. };
  48614. Sound.prototype.serialize = function () {
  48615. var serializationObject = {
  48616. name: this.name,
  48617. url: this.name,
  48618. autoplay: this.autoplay,
  48619. loop: this.loop,
  48620. volume: this._volume,
  48621. spatialSound: this.spatialSound,
  48622. maxDistance: this.maxDistance,
  48623. rolloffFactor: this.rolloffFactor,
  48624. refDistance: this.refDistance,
  48625. distanceModel: this.distanceModel,
  48626. playbackRate: this._playbackRate,
  48627. panningModel: this._panningModel,
  48628. soundTrackId: this.soundTrackId
  48629. };
  48630. if (this.spatialSound) {
  48631. if (this._connectedMesh)
  48632. serializationObject.connectedMeshId = this._connectedMesh.id;
  48633. serializationObject.position = this._position.asArray();
  48634. serializationObject.refDistance = this.refDistance;
  48635. serializationObject.distanceModel = this.distanceModel;
  48636. serializationObject.isDirectional = this._isDirectional;
  48637. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  48638. serializationObject.coneInnerAngle = this._coneInnerAngle;
  48639. serializationObject.coneOuterAngle = this._coneOuterAngle;
  48640. serializationObject.coneOuterGain = this._coneOuterGain;
  48641. }
  48642. return serializationObject;
  48643. };
  48644. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  48645. var soundName = parsedSound.name;
  48646. var soundUrl;
  48647. if (parsedSound.url) {
  48648. soundUrl = rootUrl + parsedSound.url;
  48649. }
  48650. else {
  48651. soundUrl = rootUrl + soundName;
  48652. }
  48653. var options = {
  48654. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  48655. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  48656. rolloffFactor: parsedSound.rolloffFactor,
  48657. refDistance: parsedSound.refDistance,
  48658. distanceModel: parsedSound.distanceModel,
  48659. playbackRate: parsedSound.playbackRate
  48660. };
  48661. var newSound;
  48662. if (!sourceSound) {
  48663. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  48664. scene._addPendingData(newSound);
  48665. }
  48666. else {
  48667. var setBufferAndRun = function () {
  48668. if (sourceSound._isReadyToPlay) {
  48669. newSound._audioBuffer = sourceSound.getAudioBuffer();
  48670. newSound._isReadyToPlay = true;
  48671. if (newSound.autoplay) {
  48672. newSound.play();
  48673. }
  48674. }
  48675. else {
  48676. window.setTimeout(setBufferAndRun, 300);
  48677. }
  48678. };
  48679. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  48680. setBufferAndRun();
  48681. }
  48682. if (parsedSound.position) {
  48683. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  48684. newSound.setPosition(soundPosition);
  48685. }
  48686. if (parsedSound.isDirectional) {
  48687. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  48688. if (parsedSound.localDirectionToMesh) {
  48689. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  48690. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  48691. }
  48692. }
  48693. if (parsedSound.connectedMeshId) {
  48694. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  48695. if (connectedMesh) {
  48696. newSound.attachToMesh(connectedMesh);
  48697. }
  48698. }
  48699. return newSound;
  48700. };
  48701. return Sound;
  48702. }());
  48703. BABYLON.Sound = Sound;
  48704. })(BABYLON || (BABYLON = {}));
  48705. //# sourceMappingURL=babylon.sound.js.map
  48706. var BABYLON;
  48707. (function (BABYLON) {
  48708. var SoundTrack = /** @class */ (function () {
  48709. function SoundTrack(scene, options) {
  48710. this.id = -1;
  48711. this._isMainTrack = false;
  48712. this._isInitialized = false;
  48713. this._scene = scene;
  48714. this.soundCollection = new Array();
  48715. this._options = options;
  48716. if (!this._isMainTrack) {
  48717. this._scene.soundTracks.push(this);
  48718. this.id = this._scene.soundTracks.length - 1;
  48719. }
  48720. }
  48721. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  48722. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48723. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  48724. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  48725. if (this._options) {
  48726. if (this._options.volume) {
  48727. this._outputAudioNode.gain.value = this._options.volume;
  48728. }
  48729. if (this._options.mainTrack) {
  48730. this._isMainTrack = this._options.mainTrack;
  48731. }
  48732. }
  48733. this._isInitialized = true;
  48734. }
  48735. };
  48736. SoundTrack.prototype.dispose = function () {
  48737. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48738. if (this._connectedAnalyser) {
  48739. this._connectedAnalyser.stopDebugCanvas();
  48740. }
  48741. while (this.soundCollection.length) {
  48742. this.soundCollection[0].dispose();
  48743. }
  48744. if (this._outputAudioNode) {
  48745. this._outputAudioNode.disconnect();
  48746. }
  48747. this._outputAudioNode = null;
  48748. }
  48749. };
  48750. SoundTrack.prototype.AddSound = function (sound) {
  48751. if (!this._isInitialized) {
  48752. this._initializeSoundTrackAudioGraph();
  48753. }
  48754. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48755. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  48756. }
  48757. if (sound.soundTrackId) {
  48758. if (sound.soundTrackId === -1) {
  48759. this._scene.mainSoundTrack.RemoveSound(sound);
  48760. }
  48761. else {
  48762. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  48763. }
  48764. }
  48765. this.soundCollection.push(sound);
  48766. sound.soundTrackId = this.id;
  48767. };
  48768. SoundTrack.prototype.RemoveSound = function (sound) {
  48769. var index = this.soundCollection.indexOf(sound);
  48770. if (index !== -1) {
  48771. this.soundCollection.splice(index, 1);
  48772. }
  48773. };
  48774. SoundTrack.prototype.setVolume = function (newVolume) {
  48775. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48776. this._outputAudioNode.gain.value = newVolume;
  48777. }
  48778. };
  48779. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  48780. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48781. for (var i = 0; i < this.soundCollection.length; i++) {
  48782. this.soundCollection[i].switchPanningModelToHRTF();
  48783. }
  48784. }
  48785. };
  48786. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  48787. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48788. for (var i = 0; i < this.soundCollection.length; i++) {
  48789. this.soundCollection[i].switchPanningModelToEqualPower();
  48790. }
  48791. }
  48792. };
  48793. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  48794. if (this._connectedAnalyser) {
  48795. this._connectedAnalyser.stopDebugCanvas();
  48796. }
  48797. this._connectedAnalyser = analyser;
  48798. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48799. this._outputAudioNode.disconnect();
  48800. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  48801. }
  48802. };
  48803. return SoundTrack;
  48804. }());
  48805. BABYLON.SoundTrack = SoundTrack;
  48806. })(BABYLON || (BABYLON = {}));
  48807. //# sourceMappingURL=babylon.soundtrack.js.map
  48808. var BABYLON;
  48809. (function (BABYLON) {
  48810. var Analyser = /** @class */ (function () {
  48811. function Analyser(scene) {
  48812. this.SMOOTHING = 0.75;
  48813. this.FFT_SIZE = 512;
  48814. this.BARGRAPHAMPLITUDE = 256;
  48815. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  48816. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  48817. this._scene = scene;
  48818. this._audioEngine = BABYLON.Engine.audioEngine;
  48819. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  48820. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  48821. this._webAudioAnalyser.minDecibels = -140;
  48822. this._webAudioAnalyser.maxDecibels = 0;
  48823. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48824. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48825. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  48826. }
  48827. }
  48828. Analyser.prototype.getFrequencyBinCount = function () {
  48829. if (this._audioEngine.canUseWebAudio) {
  48830. return this._webAudioAnalyser.frequencyBinCount;
  48831. }
  48832. else {
  48833. return 0;
  48834. }
  48835. };
  48836. Analyser.prototype.getByteFrequencyData = function () {
  48837. if (this._audioEngine.canUseWebAudio) {
  48838. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48839. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48840. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  48841. }
  48842. return this._byteFreqs;
  48843. };
  48844. Analyser.prototype.getByteTimeDomainData = function () {
  48845. if (this._audioEngine.canUseWebAudio) {
  48846. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48847. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48848. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  48849. }
  48850. return this._byteTime;
  48851. };
  48852. Analyser.prototype.getFloatFrequencyData = function () {
  48853. if (this._audioEngine.canUseWebAudio) {
  48854. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48855. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48856. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  48857. }
  48858. return this._floatFreqs;
  48859. };
  48860. Analyser.prototype.drawDebugCanvas = function () {
  48861. var _this = this;
  48862. if (this._audioEngine.canUseWebAudio) {
  48863. if (!this._debugCanvas) {
  48864. this._debugCanvas = document.createElement("canvas");
  48865. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  48866. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  48867. this._debugCanvas.style.position = "absolute";
  48868. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  48869. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  48870. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  48871. document.body.appendChild(this._debugCanvas);
  48872. this._registerFunc = function () {
  48873. _this.drawDebugCanvas();
  48874. };
  48875. this._scene.registerBeforeRender(this._registerFunc);
  48876. }
  48877. if (this._registerFunc && this._debugCanvasContext) {
  48878. var workingArray = this.getByteFrequencyData();
  48879. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  48880. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  48881. // Draw the frequency domain chart.
  48882. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  48883. var value = workingArray[i];
  48884. var percent = value / this.BARGRAPHAMPLITUDE;
  48885. var height = this.DEBUGCANVASSIZE.height * percent;
  48886. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  48887. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  48888. var hue = i / this.getFrequencyBinCount() * 360;
  48889. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  48890. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  48891. }
  48892. }
  48893. }
  48894. };
  48895. Analyser.prototype.stopDebugCanvas = function () {
  48896. if (this._debugCanvas) {
  48897. if (this._registerFunc) {
  48898. this._scene.unregisterBeforeRender(this._registerFunc);
  48899. this._registerFunc = null;
  48900. }
  48901. document.body.removeChild(this._debugCanvas);
  48902. this._debugCanvas = null;
  48903. this._debugCanvasContext = null;
  48904. }
  48905. };
  48906. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  48907. if (this._audioEngine.canUseWebAudio) {
  48908. inputAudioNode.connect(this._webAudioAnalyser);
  48909. this._webAudioAnalyser.connect(outputAudioNode);
  48910. }
  48911. };
  48912. Analyser.prototype.dispose = function () {
  48913. if (this._audioEngine.canUseWebAudio) {
  48914. this._webAudioAnalyser.disconnect();
  48915. }
  48916. };
  48917. return Analyser;
  48918. }());
  48919. BABYLON.Analyser = Analyser;
  48920. })(BABYLON || (BABYLON = {}));
  48921. //# sourceMappingURL=babylon.analyser.js.map
  48922. var BABYLON;
  48923. (function (BABYLON) {
  48924. var CubeTexture = /** @class */ (function (_super) {
  48925. __extends(CubeTexture, _super);
  48926. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  48927. if (extensions === void 0) { extensions = null; }
  48928. if (noMipmap === void 0) { noMipmap = false; }
  48929. if (files === void 0) { files = null; }
  48930. if (onLoad === void 0) { onLoad = null; }
  48931. if (onError === void 0) { onError = null; }
  48932. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  48933. if (prefiltered === void 0) { prefiltered = false; }
  48934. if (forcedExtension === void 0) { forcedExtension = null; }
  48935. var _this = _super.call(this, scene) || this;
  48936. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  48937. _this.name = rootUrl;
  48938. _this.url = rootUrl;
  48939. _this._noMipmap = noMipmap;
  48940. _this.hasAlpha = false;
  48941. _this._format = format;
  48942. _this._prefiltered = prefiltered;
  48943. _this.isCube = true;
  48944. _this._textureMatrix = BABYLON.Matrix.Identity();
  48945. if (prefiltered) {
  48946. _this.gammaSpace = false;
  48947. }
  48948. if (!rootUrl && !files) {
  48949. return _this;
  48950. }
  48951. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  48952. if (!files) {
  48953. if (!extensions) {
  48954. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  48955. }
  48956. files = [];
  48957. for (var index = 0; index < extensions.length; index++) {
  48958. files.push(rootUrl + extensions[index]);
  48959. }
  48960. _this._extensions = extensions;
  48961. }
  48962. _this._files = files;
  48963. if (!_this._texture) {
  48964. if (!scene.useDelayedTextureLoading) {
  48965. if (prefiltered) {
  48966. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  48967. }
  48968. else {
  48969. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  48970. }
  48971. }
  48972. else {
  48973. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  48974. }
  48975. }
  48976. else if (onLoad) {
  48977. if (_this._texture.isReady) {
  48978. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  48979. }
  48980. else {
  48981. _this._texture.onLoadedObservable.add(onLoad);
  48982. }
  48983. }
  48984. return _this;
  48985. }
  48986. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  48987. return new CubeTexture("", scene, null, noMipmap, files);
  48988. };
  48989. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  48990. if (forcedExtension === void 0) { forcedExtension = null; }
  48991. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  48992. };
  48993. // Methods
  48994. CubeTexture.prototype.delayLoad = function () {
  48995. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  48996. return;
  48997. }
  48998. var scene = this.getScene();
  48999. if (!scene) {
  49000. return;
  49001. }
  49002. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49003. this._texture = this._getFromCache(this.url, this._noMipmap);
  49004. if (!this._texture) {
  49005. if (this._prefiltered) {
  49006. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49007. }
  49008. else {
  49009. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49010. }
  49011. }
  49012. };
  49013. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49014. return this._textureMatrix;
  49015. };
  49016. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49017. this._textureMatrix = value;
  49018. };
  49019. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49020. var texture = BABYLON.SerializationHelper.Parse(function () {
  49021. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49022. }, parsedTexture, scene);
  49023. // Animations
  49024. if (parsedTexture.animations) {
  49025. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49026. var parsedAnimation = parsedTexture.animations[animationIndex];
  49027. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49028. }
  49029. }
  49030. return texture;
  49031. };
  49032. CubeTexture.prototype.clone = function () {
  49033. var _this = this;
  49034. return BABYLON.SerializationHelper.Clone(function () {
  49035. var scene = _this.getScene();
  49036. if (!scene) {
  49037. return _this;
  49038. }
  49039. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49040. }, this);
  49041. };
  49042. return CubeTexture;
  49043. }(BABYLON.BaseTexture));
  49044. BABYLON.CubeTexture = CubeTexture;
  49045. })(BABYLON || (BABYLON = {}));
  49046. //# sourceMappingURL=babylon.cubeTexture.js.map
  49047. var BABYLON;
  49048. (function (BABYLON) {
  49049. var RenderTargetTexture = /** @class */ (function (_super) {
  49050. __extends(RenderTargetTexture, _super);
  49051. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49052. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49053. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49054. if (isCube === void 0) { isCube = false; }
  49055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49056. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49057. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49058. if (isMulti === void 0) { isMulti = false; }
  49059. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49060. _this.isCube = isCube;
  49061. /**
  49062. * Use this list to define the list of mesh you want to render.
  49063. */
  49064. _this.renderList = new Array();
  49065. _this.renderParticles = true;
  49066. _this.renderSprites = false;
  49067. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49068. _this.ignoreCameraViewport = false;
  49069. // Events
  49070. /**
  49071. * An event triggered when the texture is unbind.
  49072. * @type {BABYLON.Observable}
  49073. */
  49074. _this.onBeforeBindObservable = new BABYLON.Observable();
  49075. /**
  49076. * An event triggered when the texture is unbind.
  49077. * @type {BABYLON.Observable}
  49078. */
  49079. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49080. /**
  49081. * An event triggered before rendering the texture
  49082. * @type {BABYLON.Observable}
  49083. */
  49084. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49085. /**
  49086. * An event triggered after rendering the texture
  49087. * @type {BABYLON.Observable}
  49088. */
  49089. _this.onAfterRenderObservable = new BABYLON.Observable();
  49090. /**
  49091. * An event triggered after the texture clear
  49092. * @type {BABYLON.Observable}
  49093. */
  49094. _this.onClearObservable = new BABYLON.Observable();
  49095. _this._currentRefreshId = -1;
  49096. _this._refreshRate = 1;
  49097. _this._samples = 1;
  49098. scene = _this.getScene();
  49099. if (!scene) {
  49100. return _this;
  49101. }
  49102. _this.name = name;
  49103. _this.isRenderTarget = true;
  49104. _this._size = size;
  49105. _this._generateMipMaps = generateMipMaps ? true : false;
  49106. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49107. // Rendering groups
  49108. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49109. if (isMulti) {
  49110. return _this;
  49111. }
  49112. _this._renderTargetOptions = {
  49113. generateMipMaps: generateMipMaps,
  49114. type: type,
  49115. samplingMode: samplingMode,
  49116. generateDepthBuffer: generateDepthBuffer,
  49117. generateStencilBuffer: generateStencilBuffer
  49118. };
  49119. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49120. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49121. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49122. }
  49123. if (isCube) {
  49124. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  49125. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49126. _this._textureMatrix = BABYLON.Matrix.Identity();
  49127. }
  49128. else {
  49129. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  49130. }
  49131. return _this;
  49132. }
  49133. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49134. get: function () {
  49135. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49136. },
  49137. enumerable: true,
  49138. configurable: true
  49139. });
  49140. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49141. get: function () {
  49142. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49143. },
  49144. enumerable: true,
  49145. configurable: true
  49146. });
  49147. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49148. get: function () {
  49149. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49150. },
  49151. enumerable: true,
  49152. configurable: true
  49153. });
  49154. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49155. set: function (callback) {
  49156. if (this._onAfterUnbindObserver) {
  49157. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49158. }
  49159. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49160. },
  49161. enumerable: true,
  49162. configurable: true
  49163. });
  49164. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  49165. set: function (callback) {
  49166. if (this._onBeforeRenderObserver) {
  49167. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49168. }
  49169. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49170. },
  49171. enumerable: true,
  49172. configurable: true
  49173. });
  49174. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49175. set: function (callback) {
  49176. if (this._onAfterRenderObserver) {
  49177. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49178. }
  49179. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49180. },
  49181. enumerable: true,
  49182. configurable: true
  49183. });
  49184. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  49185. set: function (callback) {
  49186. if (this._onClearObserver) {
  49187. this.onClearObservable.remove(this._onClearObserver);
  49188. }
  49189. this._onClearObserver = this.onClearObservable.add(callback);
  49190. },
  49191. enumerable: true,
  49192. configurable: true
  49193. });
  49194. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  49195. get: function () {
  49196. return this._renderTargetOptions;
  49197. },
  49198. enumerable: true,
  49199. configurable: true
  49200. });
  49201. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  49202. get: function () {
  49203. return this._samples;
  49204. },
  49205. set: function (value) {
  49206. if (this._samples === value) {
  49207. return;
  49208. }
  49209. var scene = this.getScene();
  49210. if (!scene) {
  49211. return;
  49212. }
  49213. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  49214. },
  49215. enumerable: true,
  49216. configurable: true
  49217. });
  49218. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  49219. this._currentRefreshId = -1;
  49220. };
  49221. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  49222. get: function () {
  49223. return this._refreshRate;
  49224. },
  49225. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49226. set: function (value) {
  49227. this._refreshRate = value;
  49228. this.resetRefreshCounter();
  49229. },
  49230. enumerable: true,
  49231. configurable: true
  49232. });
  49233. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  49234. if (!this._postProcessManager) {
  49235. var scene = this.getScene();
  49236. if (!scene) {
  49237. return;
  49238. }
  49239. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  49240. this._postProcesses = new Array();
  49241. }
  49242. this._postProcesses.push(postProcess);
  49243. this._postProcesses[0].autoClear = false;
  49244. };
  49245. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  49246. if (!this._postProcesses) {
  49247. return;
  49248. }
  49249. if (dispose) {
  49250. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  49251. var postProcess = _a[_i];
  49252. postProcess.dispose();
  49253. }
  49254. }
  49255. this._postProcesses = [];
  49256. };
  49257. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  49258. if (!this._postProcesses) {
  49259. return;
  49260. }
  49261. var index = this._postProcesses.indexOf(postProcess);
  49262. if (index === -1) {
  49263. return;
  49264. }
  49265. this._postProcesses.splice(index, 1);
  49266. if (this._postProcesses.length > 0) {
  49267. this._postProcesses[0].autoClear = false;
  49268. }
  49269. };
  49270. RenderTargetTexture.prototype._shouldRender = function () {
  49271. if (this._currentRefreshId === -1) {
  49272. this._currentRefreshId = 1;
  49273. return true;
  49274. }
  49275. if (this.refreshRate === this._currentRefreshId) {
  49276. this._currentRefreshId = 1;
  49277. return true;
  49278. }
  49279. this._currentRefreshId++;
  49280. return false;
  49281. };
  49282. RenderTargetTexture.prototype.getRenderSize = function () {
  49283. return this._size;
  49284. };
  49285. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  49286. get: function () {
  49287. return true;
  49288. },
  49289. enumerable: true,
  49290. configurable: true
  49291. });
  49292. RenderTargetTexture.prototype.scale = function (ratio) {
  49293. var newSize = this._size * ratio;
  49294. this.resize(newSize);
  49295. };
  49296. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  49297. if (this.isCube) {
  49298. return this._textureMatrix;
  49299. }
  49300. return _super.prototype.getReflectionTextureMatrix.call(this);
  49301. };
  49302. RenderTargetTexture.prototype.resize = function (size) {
  49303. this.releaseInternalTexture();
  49304. var scene = this.getScene();
  49305. if (!scene) {
  49306. return;
  49307. }
  49308. if (this.isCube) {
  49309. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  49310. }
  49311. else {
  49312. this._texture = scene.getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  49313. }
  49314. this._size = size;
  49315. };
  49316. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  49317. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  49318. if (dumpForDebug === void 0) { dumpForDebug = false; }
  49319. var scene = this.getScene();
  49320. if (!scene) {
  49321. return;
  49322. }
  49323. var engine = scene.getEngine();
  49324. if (this.useCameraPostProcesses !== undefined) {
  49325. useCameraPostProcess = this.useCameraPostProcesses;
  49326. }
  49327. if (this._waitingRenderList) {
  49328. this.renderList = [];
  49329. for (var index = 0; index < this._waitingRenderList.length; index++) {
  49330. var id = this._waitingRenderList[index];
  49331. var mesh_1 = scene.getMeshByID(id);
  49332. if (mesh_1) {
  49333. this.renderList.push(mesh_1);
  49334. }
  49335. }
  49336. delete this._waitingRenderList;
  49337. }
  49338. // Is predicate defined?
  49339. if (this.renderListPredicate) {
  49340. if (this.renderList) {
  49341. this.renderList.splice(0); // Clear previous renderList
  49342. }
  49343. else {
  49344. this.renderList = [];
  49345. }
  49346. var scene = this.getScene();
  49347. if (!scene) {
  49348. return;
  49349. }
  49350. var sceneMeshes = scene.meshes;
  49351. for (var index = 0; index < sceneMeshes.length; index++) {
  49352. var mesh = sceneMeshes[index];
  49353. if (this.renderListPredicate(mesh)) {
  49354. this.renderList.push(mesh);
  49355. }
  49356. }
  49357. }
  49358. this.onBeforeBindObservable.notifyObservers(this);
  49359. // Set custom projection.
  49360. // Needs to be before binding to prevent changing the aspect ratio.
  49361. var camera;
  49362. if (this.activeCamera) {
  49363. camera = this.activeCamera;
  49364. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  49365. if (this.activeCamera !== scene.activeCamera) {
  49366. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  49367. }
  49368. }
  49369. else {
  49370. camera = scene.activeCamera;
  49371. if (camera) {
  49372. engine.setViewport(camera.viewport, this._size, this._size);
  49373. }
  49374. }
  49375. // Prepare renderingManager
  49376. this._renderingManager.reset();
  49377. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  49378. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  49379. var sceneRenderId = scene.getRenderId();
  49380. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  49381. var mesh = currentRenderList[meshIndex];
  49382. if (mesh) {
  49383. if (!mesh.isReady()) {
  49384. // Reset _currentRefreshId
  49385. this.resetRefreshCounter();
  49386. continue;
  49387. }
  49388. mesh._preActivateForIntermediateRendering(sceneRenderId);
  49389. var isMasked = void 0;
  49390. if (!this.renderList && camera) {
  49391. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  49392. }
  49393. else {
  49394. isMasked = false;
  49395. }
  49396. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  49397. mesh._activate(sceneRenderId);
  49398. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49399. var subMesh = mesh.subMeshes[subIndex];
  49400. scene._activeIndices.addCount(subMesh.indexCount, false);
  49401. this._renderingManager.dispatch(subMesh);
  49402. }
  49403. }
  49404. }
  49405. }
  49406. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  49407. var particleSystem = scene.particleSystems[particleIndex];
  49408. var emitter = particleSystem.emitter;
  49409. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  49410. continue;
  49411. }
  49412. if (currentRenderList.indexOf(emitter) >= 0) {
  49413. this._renderingManager.dispatchParticles(particleSystem);
  49414. }
  49415. }
  49416. if (this.isCube) {
  49417. for (var face = 0; face < 6; face++) {
  49418. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49419. scene.incrementRenderId();
  49420. scene.resetCachedMaterial();
  49421. }
  49422. }
  49423. else {
  49424. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49425. }
  49426. this.onAfterUnbindObservable.notifyObservers(this);
  49427. if (scene.activeCamera) {
  49428. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  49429. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  49430. }
  49431. engine.setViewport(scene.activeCamera.viewport);
  49432. }
  49433. scene.resetCachedMaterial();
  49434. };
  49435. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  49436. var _this = this;
  49437. var scene = this.getScene();
  49438. if (!scene) {
  49439. return;
  49440. }
  49441. var engine = scene.getEngine();
  49442. if (!this._texture) {
  49443. return;
  49444. }
  49445. // Bind
  49446. if (this._postProcessManager) {
  49447. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  49448. }
  49449. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  49450. if (this._texture) {
  49451. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  49452. }
  49453. }
  49454. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  49455. // Clear
  49456. if (this.onClearObservable.hasObservers()) {
  49457. this.onClearObservable.notifyObservers(engine);
  49458. }
  49459. else {
  49460. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  49461. }
  49462. if (!this._doNotChangeAspectRatio) {
  49463. scene.updateTransformMatrix(true);
  49464. }
  49465. // Render
  49466. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  49467. if (this._postProcessManager) {
  49468. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  49469. }
  49470. else if (useCameraPostProcess) {
  49471. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  49472. }
  49473. if (!this._doNotChangeAspectRatio) {
  49474. scene.updateTransformMatrix(true);
  49475. }
  49476. // Dump ?
  49477. if (dumpForDebug) {
  49478. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  49479. }
  49480. // Unbind
  49481. if (!this.isCube || faceIndex === 5) {
  49482. if (this.isCube) {
  49483. if (faceIndex === 5) {
  49484. engine.generateMipMapsForCubemap(this._texture);
  49485. }
  49486. }
  49487. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  49488. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  49489. });
  49490. }
  49491. else {
  49492. this.onAfterRenderObservable.notifyObservers(faceIndex);
  49493. }
  49494. };
  49495. /**
  49496. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  49497. * This allowed control for front to back rendering or reversly depending of the special needs.
  49498. *
  49499. * @param renderingGroupId The rendering group id corresponding to its index
  49500. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  49501. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  49502. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  49503. */
  49504. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  49505. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  49506. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  49507. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  49508. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  49509. };
  49510. /**
  49511. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  49512. *
  49513. * @param renderingGroupId The rendering group id corresponding to its index
  49514. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  49515. */
  49516. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  49517. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  49518. };
  49519. RenderTargetTexture.prototype.clone = function () {
  49520. var textureSize = this.getSize();
  49521. 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);
  49522. // Base texture
  49523. newTexture.hasAlpha = this.hasAlpha;
  49524. newTexture.level = this.level;
  49525. // RenderTarget Texture
  49526. newTexture.coordinatesMode = this.coordinatesMode;
  49527. if (this.renderList) {
  49528. newTexture.renderList = this.renderList.slice(0);
  49529. }
  49530. return newTexture;
  49531. };
  49532. RenderTargetTexture.prototype.serialize = function () {
  49533. if (!this.name) {
  49534. return null;
  49535. }
  49536. var serializationObject = _super.prototype.serialize.call(this);
  49537. serializationObject.renderTargetSize = this.getRenderSize();
  49538. serializationObject.renderList = [];
  49539. if (this.renderList) {
  49540. for (var index = 0; index < this.renderList.length; index++) {
  49541. serializationObject.renderList.push(this.renderList[index].id);
  49542. }
  49543. }
  49544. return serializationObject;
  49545. };
  49546. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  49547. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  49548. var objBuffer = this.getInternalTexture();
  49549. var scene = this.getScene();
  49550. if (objBuffer && scene) {
  49551. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  49552. }
  49553. };
  49554. RenderTargetTexture.prototype.dispose = function () {
  49555. if (this._postProcessManager) {
  49556. this._postProcessManager.dispose();
  49557. this._postProcessManager = null;
  49558. }
  49559. this.clearPostProcesses(true);
  49560. this.renderList = null;
  49561. // Remove from custom render targets
  49562. var scene = this.getScene();
  49563. if (!scene) {
  49564. return;
  49565. }
  49566. var index = scene.customRenderTargets.indexOf(this);
  49567. if (index >= 0) {
  49568. scene.customRenderTargets.splice(index, 1);
  49569. }
  49570. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  49571. var camera = _a[_i];
  49572. index = camera.customRenderTargets.indexOf(this);
  49573. if (index >= 0) {
  49574. camera.customRenderTargets.splice(index, 1);
  49575. }
  49576. }
  49577. _super.prototype.dispose.call(this);
  49578. };
  49579. RenderTargetTexture.prototype._rebuild = function () {
  49580. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  49581. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  49582. }
  49583. if (this._postProcessManager) {
  49584. this._postProcessManager._rebuild();
  49585. }
  49586. };
  49587. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  49588. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  49589. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  49590. return RenderTargetTexture;
  49591. }(BABYLON.Texture));
  49592. BABYLON.RenderTargetTexture = RenderTargetTexture;
  49593. })(BABYLON || (BABYLON = {}));
  49594. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  49595. var BABYLON;
  49596. (function (BABYLON) {
  49597. ;
  49598. var MultiRenderTarget = /** @class */ (function (_super) {
  49599. __extends(MultiRenderTarget, _super);
  49600. function MultiRenderTarget(name, size, count, scene, options) {
  49601. var _this = this;
  49602. options = options || {};
  49603. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  49604. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  49605. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  49606. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  49607. _this._engine = scene.getEngine();
  49608. if (!_this.isSupported) {
  49609. _this.dispose();
  49610. return;
  49611. }
  49612. var types = [];
  49613. var samplingModes = [];
  49614. for (var i = 0; i < count; i++) {
  49615. if (options.types && options.types[i]) {
  49616. types.push(options.types[i]);
  49617. }
  49618. else {
  49619. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  49620. }
  49621. if (options.samplingModes && options.samplingModes[i]) {
  49622. samplingModes.push(options.samplingModes[i]);
  49623. }
  49624. else {
  49625. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49626. }
  49627. }
  49628. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  49629. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  49630. _this._count = count;
  49631. _this._size = size;
  49632. _this._multiRenderTargetOptions = {
  49633. samplingModes: samplingModes,
  49634. generateMipMaps: generateMipMaps,
  49635. generateDepthBuffer: generateDepthBuffer,
  49636. generateStencilBuffer: generateStencilBuffer,
  49637. generateDepthTexture: generateDepthTexture,
  49638. types: types,
  49639. textureCount: count
  49640. };
  49641. _this._createInternalTextures();
  49642. _this._createTextures();
  49643. return _this;
  49644. }
  49645. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  49646. get: function () {
  49647. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  49648. },
  49649. enumerable: true,
  49650. configurable: true
  49651. });
  49652. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  49653. get: function () {
  49654. return this._textures;
  49655. },
  49656. enumerable: true,
  49657. configurable: true
  49658. });
  49659. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  49660. get: function () {
  49661. return this._textures[this._textures.length - 1];
  49662. },
  49663. enumerable: true,
  49664. configurable: true
  49665. });
  49666. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  49667. set: function (wrap) {
  49668. if (this._textures) {
  49669. for (var i = 0; i < this._textures.length; i++) {
  49670. this._textures[i].wrapU = wrap;
  49671. }
  49672. }
  49673. },
  49674. enumerable: true,
  49675. configurable: true
  49676. });
  49677. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  49678. set: function (wrap) {
  49679. if (this._textures) {
  49680. for (var i = 0; i < this._textures.length; i++) {
  49681. this._textures[i].wrapV = wrap;
  49682. }
  49683. }
  49684. },
  49685. enumerable: true,
  49686. configurable: true
  49687. });
  49688. MultiRenderTarget.prototype._rebuild = function () {
  49689. this.releaseInternalTextures();
  49690. this._createInternalTextures();
  49691. for (var i = 0; i < this._internalTextures.length; i++) {
  49692. var texture = this._textures[i];
  49693. texture._texture = this._internalTextures[i];
  49694. }
  49695. // Keeps references to frame buffer and stencil/depth buffer
  49696. this._texture = this._internalTextures[0];
  49697. };
  49698. MultiRenderTarget.prototype._createInternalTextures = function () {
  49699. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  49700. };
  49701. MultiRenderTarget.prototype._createTextures = function () {
  49702. this._textures = [];
  49703. for (var i = 0; i < this._internalTextures.length; i++) {
  49704. var texture = new BABYLON.Texture(null, this.getScene());
  49705. texture._texture = this._internalTextures[i];
  49706. this._textures.push(texture);
  49707. }
  49708. // Keeps references to frame buffer and stencil/depth buffer
  49709. this._texture = this._internalTextures[0];
  49710. };
  49711. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  49712. get: function () {
  49713. return this._samples;
  49714. },
  49715. set: function (value) {
  49716. if (this._samples === value) {
  49717. return;
  49718. }
  49719. for (var i = 0; i < this._internalTextures.length; i++) {
  49720. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  49721. }
  49722. },
  49723. enumerable: true,
  49724. configurable: true
  49725. });
  49726. MultiRenderTarget.prototype.resize = function (size) {
  49727. this.releaseInternalTextures();
  49728. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  49729. this._createInternalTextures();
  49730. };
  49731. MultiRenderTarget.prototype.dispose = function () {
  49732. this.releaseInternalTextures();
  49733. _super.prototype.dispose.call(this);
  49734. };
  49735. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  49736. if (!this._internalTextures) {
  49737. return;
  49738. }
  49739. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  49740. if (this._internalTextures[i] !== undefined) {
  49741. this._internalTextures[i].dispose();
  49742. this._internalTextures.splice(i, 1);
  49743. }
  49744. }
  49745. };
  49746. return MultiRenderTarget;
  49747. }(BABYLON.RenderTargetTexture));
  49748. BABYLON.MultiRenderTarget = MultiRenderTarget;
  49749. })(BABYLON || (BABYLON = {}));
  49750. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  49751. var BABYLON;
  49752. (function (BABYLON) {
  49753. var MirrorTexture = /** @class */ (function (_super) {
  49754. __extends(MirrorTexture, _super);
  49755. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  49756. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49757. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49758. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49759. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  49760. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  49761. _this._transformMatrix = BABYLON.Matrix.Zero();
  49762. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  49763. _this._blurKernelX = 0;
  49764. _this._blurKernelY = 0;
  49765. _this._blurRatio = 1.0;
  49766. _this.ignoreCameraViewport = true;
  49767. _this.onBeforeRenderObservable.add(function () {
  49768. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  49769. _this._savedViewMatrix = scene.getViewMatrix();
  49770. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  49771. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  49772. scene.clipPlane = _this.mirrorPlane;
  49773. scene.getEngine().cullBackFaces = false;
  49774. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  49775. });
  49776. _this.onAfterRenderObservable.add(function () {
  49777. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  49778. scene.getEngine().cullBackFaces = true;
  49779. scene._mirroredCameraPosition = null;
  49780. delete scene.clipPlane;
  49781. });
  49782. return _this;
  49783. }
  49784. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  49785. get: function () {
  49786. return this._blurRatio;
  49787. },
  49788. set: function (value) {
  49789. if (this._blurRatio === value) {
  49790. return;
  49791. }
  49792. this._blurRatio = value;
  49793. this._preparePostProcesses();
  49794. },
  49795. enumerable: true,
  49796. configurable: true
  49797. });
  49798. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  49799. set: function (value) {
  49800. this.blurKernelX = value;
  49801. this.blurKernelY = value;
  49802. },
  49803. enumerable: true,
  49804. configurable: true
  49805. });
  49806. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  49807. get: function () {
  49808. return this._blurKernelX;
  49809. },
  49810. set: function (value) {
  49811. if (this._blurKernelX === value) {
  49812. return;
  49813. }
  49814. this._blurKernelX = value;
  49815. this._preparePostProcesses();
  49816. },
  49817. enumerable: true,
  49818. configurable: true
  49819. });
  49820. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  49821. get: function () {
  49822. return this._blurKernelY;
  49823. },
  49824. set: function (value) {
  49825. if (this._blurKernelY === value) {
  49826. return;
  49827. }
  49828. this._blurKernelY = value;
  49829. this._preparePostProcesses();
  49830. },
  49831. enumerable: true,
  49832. configurable: true
  49833. });
  49834. MirrorTexture.prototype._preparePostProcesses = function () {
  49835. this.clearPostProcesses(true);
  49836. if (this._blurKernelX && this._blurKernelY) {
  49837. var engine = this.getScene().getEngine();
  49838. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49839. 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);
  49840. this._blurX.autoClear = false;
  49841. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  49842. this._blurX.outputTexture = this._texture;
  49843. }
  49844. else {
  49845. this._blurX.alwaysForcePOT = true;
  49846. }
  49847. 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);
  49848. this._blurY.autoClear = false;
  49849. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  49850. this.addPostProcess(this._blurX);
  49851. this.addPostProcess(this._blurY);
  49852. }
  49853. };
  49854. MirrorTexture.prototype.clone = function () {
  49855. var scene = this.getScene();
  49856. if (!scene) {
  49857. return this;
  49858. }
  49859. var textureSize = this.getSize();
  49860. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  49861. // Base texture
  49862. newTexture.hasAlpha = this.hasAlpha;
  49863. newTexture.level = this.level;
  49864. // Mirror Texture
  49865. newTexture.mirrorPlane = this.mirrorPlane.clone();
  49866. if (this.renderList) {
  49867. newTexture.renderList = this.renderList.slice(0);
  49868. }
  49869. return newTexture;
  49870. };
  49871. MirrorTexture.prototype.serialize = function () {
  49872. if (!this.name) {
  49873. return null;
  49874. }
  49875. var serializationObject = _super.prototype.serialize.call(this);
  49876. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  49877. return serializationObject;
  49878. };
  49879. return MirrorTexture;
  49880. }(BABYLON.RenderTargetTexture));
  49881. BABYLON.MirrorTexture = MirrorTexture;
  49882. })(BABYLON || (BABYLON = {}));
  49883. //# sourceMappingURL=babylon.mirrorTexture.js.map
  49884. var BABYLON;
  49885. (function (BABYLON) {
  49886. /**
  49887. * Creates a refraction texture used by refraction channel of the standard material.
  49888. * @param name the texture name
  49889. * @param size size of the underlying texture
  49890. * @param scene root scene
  49891. */
  49892. var RefractionTexture = /** @class */ (function (_super) {
  49893. __extends(RefractionTexture, _super);
  49894. function RefractionTexture(name, size, scene, generateMipMaps) {
  49895. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  49896. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  49897. _this.depth = 2.0;
  49898. _this.onBeforeRenderObservable.add(function () {
  49899. scene.clipPlane = _this.refractionPlane;
  49900. });
  49901. _this.onAfterRenderObservable.add(function () {
  49902. delete scene.clipPlane;
  49903. });
  49904. return _this;
  49905. }
  49906. RefractionTexture.prototype.clone = function () {
  49907. var scene = this.getScene();
  49908. if (!scene) {
  49909. return this;
  49910. }
  49911. var textureSize = this.getSize();
  49912. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  49913. // Base texture
  49914. newTexture.hasAlpha = this.hasAlpha;
  49915. newTexture.level = this.level;
  49916. // Refraction Texture
  49917. newTexture.refractionPlane = this.refractionPlane.clone();
  49918. if (this.renderList) {
  49919. newTexture.renderList = this.renderList.slice(0);
  49920. }
  49921. newTexture.depth = this.depth;
  49922. return newTexture;
  49923. };
  49924. RefractionTexture.prototype.serialize = function () {
  49925. if (!this.name) {
  49926. return null;
  49927. }
  49928. var serializationObject = _super.prototype.serialize.call(this);
  49929. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  49930. serializationObject.depth = this.depth;
  49931. return serializationObject;
  49932. };
  49933. return RefractionTexture;
  49934. }(BABYLON.RenderTargetTexture));
  49935. BABYLON.RefractionTexture = RefractionTexture;
  49936. })(BABYLON || (BABYLON = {}));
  49937. //# sourceMappingURL=babylon.refractionTexture.js.map
  49938. var BABYLON;
  49939. (function (BABYLON) {
  49940. var DynamicTexture = /** @class */ (function (_super) {
  49941. __extends(DynamicTexture, _super);
  49942. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  49943. if (scene === void 0) { scene = null; }
  49944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49945. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49946. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  49947. _this.name = name;
  49948. _this._engine = _this.getScene().getEngine();
  49949. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49950. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49951. _this._generateMipMaps = generateMipMaps;
  49952. if (options.getContext) {
  49953. _this._canvas = options;
  49954. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  49955. }
  49956. else {
  49957. _this._canvas = document.createElement("canvas");
  49958. if (options.width) {
  49959. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  49960. }
  49961. else {
  49962. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  49963. }
  49964. }
  49965. var textureSize = _this.getSize();
  49966. _this._canvas.width = textureSize.width;
  49967. _this._canvas.height = textureSize.height;
  49968. _this._context = _this._canvas.getContext("2d");
  49969. return _this;
  49970. }
  49971. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  49972. get: function () {
  49973. return true;
  49974. },
  49975. enumerable: true,
  49976. configurable: true
  49977. });
  49978. DynamicTexture.prototype._recreate = function (textureSize) {
  49979. this._canvas.width = textureSize.width;
  49980. this._canvas.height = textureSize.height;
  49981. this.releaseInternalTexture();
  49982. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  49983. };
  49984. DynamicTexture.prototype.scale = function (ratio) {
  49985. var textureSize = this.getSize();
  49986. textureSize.width *= ratio;
  49987. textureSize.height *= ratio;
  49988. this._recreate(textureSize);
  49989. };
  49990. DynamicTexture.prototype.scaleTo = function (width, height) {
  49991. var textureSize = this.getSize();
  49992. textureSize.width = width;
  49993. textureSize.height = height;
  49994. this._recreate(textureSize);
  49995. };
  49996. DynamicTexture.prototype.getContext = function () {
  49997. return this._context;
  49998. };
  49999. DynamicTexture.prototype.clear = function () {
  50000. var size = this.getSize();
  50001. this._context.fillRect(0, 0, size.width, size.height);
  50002. };
  50003. DynamicTexture.prototype.update = function (invertY) {
  50004. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50005. };
  50006. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50007. if (update === void 0) { update = true; }
  50008. var size = this.getSize();
  50009. if (clearColor) {
  50010. this._context.fillStyle = clearColor;
  50011. this._context.fillRect(0, 0, size.width, size.height);
  50012. }
  50013. this._context.font = font;
  50014. if (x === null || x === undefined) {
  50015. var textSize = this._context.measureText(text);
  50016. x = (size.width - textSize.width) / 2;
  50017. }
  50018. if (y === null || y === undefined) {
  50019. var fontSize = parseInt((font.replace(/\D/g, '')));
  50020. ;
  50021. y = (size.height / 2) + (fontSize / 3.65);
  50022. }
  50023. this._context.fillStyle = color;
  50024. this._context.fillText(text, x, y);
  50025. if (update) {
  50026. this.update(invertY);
  50027. }
  50028. };
  50029. DynamicTexture.prototype.clone = function () {
  50030. var scene = this.getScene();
  50031. if (!scene) {
  50032. return this;
  50033. }
  50034. var textureSize = this.getSize();
  50035. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50036. // Base texture
  50037. newTexture.hasAlpha = this.hasAlpha;
  50038. newTexture.level = this.level;
  50039. // Dynamic Texture
  50040. newTexture.wrapU = this.wrapU;
  50041. newTexture.wrapV = this.wrapV;
  50042. return newTexture;
  50043. };
  50044. DynamicTexture.prototype._rebuild = function () {
  50045. this.update();
  50046. };
  50047. return DynamicTexture;
  50048. }(BABYLON.Texture));
  50049. BABYLON.DynamicTexture = DynamicTexture;
  50050. })(BABYLON || (BABYLON = {}));
  50051. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50052. var BABYLON;
  50053. (function (BABYLON) {
  50054. var VideoTexture = /** @class */ (function (_super) {
  50055. __extends(VideoTexture, _super);
  50056. /**
  50057. * Creates a video texture.
  50058. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50059. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50060. * @param {BABYLON.Scene} scene is obviously the current scene.
  50061. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50062. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50063. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50064. */
  50065. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50066. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50067. if (invertY === void 0) { invertY = false; }
  50068. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50069. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50070. _this._autoLaunch = true;
  50071. var urls = null;
  50072. _this.name = name;
  50073. if (urlsOrVideo instanceof HTMLVideoElement) {
  50074. _this.video = urlsOrVideo;
  50075. }
  50076. else {
  50077. urls = urlsOrVideo;
  50078. _this.video = document.createElement("video");
  50079. _this.video.autoplay = false;
  50080. _this.video.loop = true;
  50081. }
  50082. _this._engine = _this.getScene().getEngine();
  50083. _this._generateMipMaps = generateMipMaps;
  50084. _this._samplingMode = samplingMode;
  50085. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  50086. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50087. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50088. }
  50089. else {
  50090. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50091. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50092. _this._generateMipMaps = false;
  50093. }
  50094. if (urls) {
  50095. _this.video.addEventListener("canplay", function () {
  50096. _this._createTexture();
  50097. });
  50098. urls.forEach(function (url) {
  50099. var source = document.createElement("source");
  50100. source.src = url;
  50101. _this.video.appendChild(source);
  50102. });
  50103. }
  50104. else {
  50105. _this._createTexture();
  50106. }
  50107. _this._lastUpdate = BABYLON.Tools.Now;
  50108. return _this;
  50109. }
  50110. VideoTexture.prototype.__setTextureReady = function () {
  50111. if (this._texture) {
  50112. this._texture.isReady = true;
  50113. }
  50114. };
  50115. VideoTexture.prototype._createTexture = function () {
  50116. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  50117. if (this._autoLaunch) {
  50118. this._autoLaunch = false;
  50119. this.video.play();
  50120. }
  50121. this._setTextureReady = this.__setTextureReady.bind(this);
  50122. this.video.addEventListener("playing", this._setTextureReady);
  50123. };
  50124. VideoTexture.prototype._rebuild = function () {
  50125. this.update();
  50126. };
  50127. VideoTexture.prototype.update = function () {
  50128. var now = BABYLON.Tools.Now;
  50129. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  50130. return false;
  50131. }
  50132. this._lastUpdate = now;
  50133. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  50134. return true;
  50135. };
  50136. VideoTexture.prototype.dispose = function () {
  50137. _super.prototype.dispose.call(this);
  50138. this.video.removeEventListener("playing", this._setTextureReady);
  50139. };
  50140. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  50141. var video = document.createElement("video");
  50142. var constraintsDeviceId;
  50143. if (constraints && constraints.deviceId) {
  50144. constraintsDeviceId = {
  50145. exact: constraints.deviceId
  50146. };
  50147. }
  50148. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  50149. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  50150. if (navigator.getUserMedia) {
  50151. navigator.getUserMedia({
  50152. video: {
  50153. deviceId: constraintsDeviceId,
  50154. width: {
  50155. min: (constraints && constraints.minWidth) || 256,
  50156. max: (constraints && constraints.maxWidth) || 640
  50157. },
  50158. height: {
  50159. min: (constraints && constraints.minHeight) || 256,
  50160. max: (constraints && constraints.maxHeight) || 480
  50161. }
  50162. }
  50163. }, function (stream) {
  50164. if (video.mozSrcObject !== undefined) {
  50165. video.mozSrcObject = stream;
  50166. }
  50167. else {
  50168. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  50169. }
  50170. video.play();
  50171. if (onReady) {
  50172. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  50173. }
  50174. }, function (e) {
  50175. BABYLON.Tools.Error(e.name);
  50176. });
  50177. }
  50178. };
  50179. return VideoTexture;
  50180. }(BABYLON.Texture));
  50181. BABYLON.VideoTexture = VideoTexture;
  50182. })(BABYLON || (BABYLON = {}));
  50183. //# sourceMappingURL=babylon.videoTexture.js.map
  50184. var BABYLON;
  50185. (function (BABYLON) {
  50186. var RawTexture = /** @class */ (function (_super) {
  50187. __extends(RawTexture, _super);
  50188. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50189. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50190. if (invertY === void 0) { invertY = false; }
  50191. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50192. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50193. _this.format = format;
  50194. _this._engine = scene.getEngine();
  50195. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50196. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50197. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50198. return _this;
  50199. }
  50200. RawTexture.prototype.update = function (data) {
  50201. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  50202. };
  50203. // Statics
  50204. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50205. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50206. if (invertY === void 0) { invertY = false; }
  50207. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50208. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50209. };
  50210. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50211. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50212. if (invertY === void 0) { invertY = false; }
  50213. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50214. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50215. };
  50216. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50217. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50218. if (invertY === void 0) { invertY = false; }
  50219. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50220. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50221. };
  50222. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50223. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50224. if (invertY === void 0) { invertY = false; }
  50225. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50226. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50227. };
  50228. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50229. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50230. if (invertY === void 0) { invertY = false; }
  50231. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50232. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50233. };
  50234. return RawTexture;
  50235. }(BABYLON.Texture));
  50236. BABYLON.RawTexture = RawTexture;
  50237. })(BABYLON || (BABYLON = {}));
  50238. //# sourceMappingURL=babylon.rawTexture.js.map
  50239. var BABYLON;
  50240. (function (BABYLON) {
  50241. var PostProcess = /** @class */ (function () {
  50242. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  50243. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  50244. if (defines === void 0) { defines = null; }
  50245. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50246. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  50247. if (blockCompilation === void 0) { blockCompilation = false; }
  50248. this.name = name;
  50249. this.width = -1;
  50250. this.height = -1;
  50251. this.autoClear = true;
  50252. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  50253. /*
  50254. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  50255. Can only be used on a single postprocess or on the last one of a chain.
  50256. */
  50257. this.enablePixelPerfectMode = false;
  50258. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  50259. this.alwaysForcePOT = false;
  50260. this.samples = 1;
  50261. this.adaptScaleToCurrentViewport = false;
  50262. this._reusable = false;
  50263. this._textures = new BABYLON.SmartArray(2);
  50264. this._currentRenderTextureInd = 0;
  50265. this._scaleRatio = new BABYLON.Vector2(1, 1);
  50266. this._texelSize = BABYLON.Vector2.Zero();
  50267. // Events
  50268. /**
  50269. * An event triggered when the postprocess is activated.
  50270. * @type {BABYLON.Observable}
  50271. */
  50272. this.onActivateObservable = new BABYLON.Observable();
  50273. /**
  50274. * An event triggered when the postprocess changes its size.
  50275. * @type {BABYLON.Observable}
  50276. */
  50277. this.onSizeChangedObservable = new BABYLON.Observable();
  50278. /**
  50279. * An event triggered when the postprocess applies its effect.
  50280. * @type {BABYLON.Observable}
  50281. */
  50282. this.onApplyObservable = new BABYLON.Observable();
  50283. /**
  50284. * An event triggered before rendering the postprocess
  50285. * @type {BABYLON.Observable}
  50286. */
  50287. this.onBeforeRenderObservable = new BABYLON.Observable();
  50288. /**
  50289. * An event triggered after rendering the postprocess
  50290. * @type {BABYLON.Observable}
  50291. */
  50292. this.onAfterRenderObservable = new BABYLON.Observable();
  50293. if (camera != null) {
  50294. this._camera = camera;
  50295. this._scene = camera.getScene();
  50296. camera.attachPostProcess(this);
  50297. this._engine = this._scene.getEngine();
  50298. this._scene.postProcesses.push(this);
  50299. }
  50300. else if (engine) {
  50301. this._engine = engine;
  50302. this._engine.postProcesses.push(this);
  50303. }
  50304. this._options = options;
  50305. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  50306. this._reusable = reusable || false;
  50307. this._textureType = textureType;
  50308. this._samplers = samplers || [];
  50309. this._samplers.push("textureSampler");
  50310. this._fragmentUrl = fragmentUrl;
  50311. this._vertexUrl = vertexUrl;
  50312. this._parameters = parameters || [];
  50313. this._parameters.push("scale");
  50314. this._indexParameters = indexParameters;
  50315. if (!blockCompilation) {
  50316. this.updateEffect(defines);
  50317. }
  50318. }
  50319. Object.defineProperty(PostProcess.prototype, "onActivate", {
  50320. set: function (callback) {
  50321. if (this._onActivateObserver) {
  50322. this.onActivateObservable.remove(this._onActivateObserver);
  50323. }
  50324. if (callback) {
  50325. this._onActivateObserver = this.onActivateObservable.add(callback);
  50326. }
  50327. },
  50328. enumerable: true,
  50329. configurable: true
  50330. });
  50331. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  50332. set: function (callback) {
  50333. if (this._onSizeChangedObserver) {
  50334. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  50335. }
  50336. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  50337. },
  50338. enumerable: true,
  50339. configurable: true
  50340. });
  50341. Object.defineProperty(PostProcess.prototype, "onApply", {
  50342. set: function (callback) {
  50343. if (this._onApplyObserver) {
  50344. this.onApplyObservable.remove(this._onApplyObserver);
  50345. }
  50346. this._onApplyObserver = this.onApplyObservable.add(callback);
  50347. },
  50348. enumerable: true,
  50349. configurable: true
  50350. });
  50351. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  50352. set: function (callback) {
  50353. if (this._onBeforeRenderObserver) {
  50354. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50355. }
  50356. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50357. },
  50358. enumerable: true,
  50359. configurable: true
  50360. });
  50361. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  50362. set: function (callback) {
  50363. if (this._onAfterRenderObserver) {
  50364. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50365. }
  50366. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50367. },
  50368. enumerable: true,
  50369. configurable: true
  50370. });
  50371. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  50372. get: function () {
  50373. return this._textures.data[this._currentRenderTextureInd];
  50374. },
  50375. set: function (value) {
  50376. this._forcedOutputTexture = value;
  50377. },
  50378. enumerable: true,
  50379. configurable: true
  50380. });
  50381. PostProcess.prototype.getCamera = function () {
  50382. return this._camera;
  50383. };
  50384. Object.defineProperty(PostProcess.prototype, "texelSize", {
  50385. get: function () {
  50386. if (this._shareOutputWithPostProcess) {
  50387. return this._shareOutputWithPostProcess.texelSize;
  50388. }
  50389. if (this._forcedOutputTexture) {
  50390. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  50391. }
  50392. return this._texelSize;
  50393. },
  50394. enumerable: true,
  50395. configurable: true
  50396. });
  50397. PostProcess.prototype.getEngine = function () {
  50398. return this._engine;
  50399. };
  50400. PostProcess.prototype.getEffect = function () {
  50401. return this._effect;
  50402. };
  50403. PostProcess.prototype.shareOutputWith = function (postProcess) {
  50404. this._disposeTextures();
  50405. this._shareOutputWithPostProcess = postProcess;
  50406. return this;
  50407. };
  50408. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  50409. if (defines === void 0) { defines = null; }
  50410. if (uniforms === void 0) { uniforms = null; }
  50411. if (samplers === void 0) { samplers = null; }
  50412. 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);
  50413. };
  50414. PostProcess.prototype.isReusable = function () {
  50415. return this._reusable;
  50416. };
  50417. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  50418. PostProcess.prototype.markTextureDirty = function () {
  50419. this.width = -1;
  50420. };
  50421. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  50422. var _this = this;
  50423. if (sourceTexture === void 0) { sourceTexture = null; }
  50424. camera = camera || this._camera;
  50425. var scene = camera.getScene();
  50426. var engine = scene.getEngine();
  50427. var maxSize = engine.getCaps().maxTextureSize;
  50428. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  50429. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  50430. var desiredWidth = (this._options.width || requiredWidth);
  50431. var desiredHeight = this._options.height || requiredHeight;
  50432. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  50433. if (this.adaptScaleToCurrentViewport) {
  50434. var currentViewport = engine.currentViewport;
  50435. if (currentViewport) {
  50436. desiredWidth *= currentViewport.width;
  50437. desiredHeight *= currentViewport.height;
  50438. }
  50439. }
  50440. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  50441. if (!this._options.width) {
  50442. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  50443. }
  50444. if (!this._options.height) {
  50445. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  50446. }
  50447. }
  50448. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  50449. if (this._textures.length > 0) {
  50450. for (var i = 0; i < this._textures.length; i++) {
  50451. this._engine._releaseTexture(this._textures.data[i]);
  50452. }
  50453. this._textures.reset();
  50454. }
  50455. this.width = desiredWidth;
  50456. this.height = desiredHeight;
  50457. var textureSize = { width: this.width, height: this.height };
  50458. var textureOptions = {
  50459. generateMipMaps: false,
  50460. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  50461. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  50462. samplingMode: this.renderTargetSamplingMode,
  50463. type: this._textureType
  50464. };
  50465. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50466. if (this._reusable) {
  50467. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50468. }
  50469. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  50470. this.onSizeChangedObservable.notifyObservers(this);
  50471. }
  50472. this._textures.forEach(function (texture) {
  50473. if (texture.samples !== _this.samples) {
  50474. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  50475. }
  50476. });
  50477. }
  50478. var target;
  50479. if (this._shareOutputWithPostProcess) {
  50480. target = this._shareOutputWithPostProcess.outputTexture;
  50481. }
  50482. else if (this._forcedOutputTexture) {
  50483. target = this._forcedOutputTexture;
  50484. this.width = this._forcedOutputTexture.width;
  50485. this.height = this._forcedOutputTexture.height;
  50486. }
  50487. else {
  50488. target = this.outputTexture;
  50489. }
  50490. if (this.enablePixelPerfectMode) {
  50491. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  50492. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  50493. }
  50494. else {
  50495. this._scaleRatio.copyFromFloats(1, 1);
  50496. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  50497. }
  50498. this.onActivateObservable.notifyObservers(camera);
  50499. // Clear
  50500. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  50501. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  50502. }
  50503. if (this._reusable) {
  50504. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  50505. }
  50506. };
  50507. Object.defineProperty(PostProcess.prototype, "isSupported", {
  50508. get: function () {
  50509. return this._effect.isSupported;
  50510. },
  50511. enumerable: true,
  50512. configurable: true
  50513. });
  50514. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  50515. get: function () {
  50516. if (this._shareOutputWithPostProcess) {
  50517. return this._shareOutputWithPostProcess.aspectRatio;
  50518. }
  50519. if (this._forcedOutputTexture) {
  50520. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  50521. }
  50522. return this.width / this.height;
  50523. },
  50524. enumerable: true,
  50525. configurable: true
  50526. });
  50527. PostProcess.prototype.apply = function () {
  50528. // Check
  50529. if (!this._effect || !this._effect.isReady())
  50530. return null;
  50531. // States
  50532. this._engine.enableEffect(this._effect);
  50533. this._engine.setState(false);
  50534. this._engine.setDepthBuffer(false);
  50535. this._engine.setDepthWrite(false);
  50536. // Alpha
  50537. this._engine.setAlphaMode(this.alphaMode);
  50538. if (this.alphaConstants) {
  50539. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  50540. }
  50541. // Texture
  50542. var source;
  50543. if (this._shareOutputWithPostProcess) {
  50544. source = this._shareOutputWithPostProcess.outputTexture;
  50545. }
  50546. else if (this._forcedOutputTexture) {
  50547. source = this._forcedOutputTexture;
  50548. }
  50549. else {
  50550. source = this.outputTexture;
  50551. }
  50552. this._effect._bindTexture("textureSampler", source);
  50553. // Parameters
  50554. this._effect.setVector2("scale", this._scaleRatio);
  50555. this.onApplyObservable.notifyObservers(this._effect);
  50556. return this._effect;
  50557. };
  50558. PostProcess.prototype._disposeTextures = function () {
  50559. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  50560. return;
  50561. }
  50562. if (this._textures.length > 0) {
  50563. for (var i = 0; i < this._textures.length; i++) {
  50564. this._engine._releaseTexture(this._textures.data[i]);
  50565. }
  50566. }
  50567. this._textures.dispose();
  50568. };
  50569. PostProcess.prototype.dispose = function (camera) {
  50570. camera = camera || this._camera;
  50571. this._disposeTextures();
  50572. if (this._scene) {
  50573. var index_1 = this._scene.postProcesses.indexOf(this);
  50574. if (index_1 !== -1) {
  50575. this._scene.postProcesses.splice(index_1, 1);
  50576. }
  50577. }
  50578. else {
  50579. var index_2 = this._engine.postProcesses.indexOf(this);
  50580. if (index_2 !== -1) {
  50581. this._engine.postProcesses.splice(index_2, 1);
  50582. }
  50583. }
  50584. if (!camera) {
  50585. return;
  50586. }
  50587. camera.detachPostProcess(this);
  50588. var index = camera._postProcesses.indexOf(this);
  50589. if (index === 0 && camera._postProcesses.length > 0) {
  50590. this._camera._postProcesses[0].markTextureDirty();
  50591. }
  50592. this.onActivateObservable.clear();
  50593. this.onAfterRenderObservable.clear();
  50594. this.onApplyObservable.clear();
  50595. this.onBeforeRenderObservable.clear();
  50596. this.onSizeChangedObservable.clear();
  50597. };
  50598. return PostProcess;
  50599. }());
  50600. BABYLON.PostProcess = PostProcess;
  50601. })(BABYLON || (BABYLON = {}));
  50602. //# sourceMappingURL=babylon.postProcess.js.map
  50603. var BABYLON;
  50604. (function (BABYLON) {
  50605. var PassPostProcess = /** @class */ (function (_super) {
  50606. __extends(PassPostProcess, _super);
  50607. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50608. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50609. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  50610. }
  50611. return PassPostProcess;
  50612. }(BABYLON.PostProcess));
  50613. BABYLON.PassPostProcess = PassPostProcess;
  50614. })(BABYLON || (BABYLON = {}));
  50615. //# sourceMappingURL=babylon.passPostProcess.js.map
  50616. var BABYLON;
  50617. (function (BABYLON) {
  50618. var ShadowGenerator = /** @class */ (function () {
  50619. /**
  50620. * Creates a ShadowGenerator object.
  50621. * A ShadowGenerator is the required tool to use the shadows.
  50622. * Each light casting shadows needs to use its own ShadowGenerator.
  50623. * Required parameters :
  50624. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  50625. * - `light`: the light object generating the shadows.
  50626. * - `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.
  50627. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  50628. */
  50629. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  50630. // Members
  50631. this._bias = 0.00005;
  50632. this._blurBoxOffset = 1;
  50633. this._blurScale = 2;
  50634. this._blurKernel = 1;
  50635. this._useKernelBlur = false;
  50636. this._filter = ShadowGenerator.FILTER_NONE;
  50637. this._darkness = 0;
  50638. this._transparencyShadow = false;
  50639. /**
  50640. * Controls the extent to which the shadows fade out at the edge of the frustum
  50641. * Used only by directionals and spots
  50642. */
  50643. this.frustumEdgeFalloff = 0;
  50644. this.forceBackFacesOnly = false;
  50645. this._lightDirection = BABYLON.Vector3.Zero();
  50646. this._viewMatrix = BABYLON.Matrix.Zero();
  50647. this._projectionMatrix = BABYLON.Matrix.Zero();
  50648. this._transformMatrix = BABYLON.Matrix.Zero();
  50649. this._currentFaceIndex = 0;
  50650. this._currentFaceIndexCache = 0;
  50651. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  50652. this._mapSize = mapSize;
  50653. this._light = light;
  50654. this._scene = light.getScene();
  50655. light._shadowGenerator = this;
  50656. // Texture type fallback from float to int if not supported.
  50657. var caps = this._scene.getEngine().getCaps();
  50658. if (!useFullFloatFirst) {
  50659. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50660. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50661. }
  50662. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50663. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50664. }
  50665. else {
  50666. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50667. }
  50668. }
  50669. else {
  50670. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50671. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50672. }
  50673. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50674. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50675. }
  50676. else {
  50677. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50678. }
  50679. }
  50680. this._initializeGenerator();
  50681. }
  50682. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  50683. // Static
  50684. get: function () {
  50685. return ShadowGenerator._FILTER_NONE;
  50686. },
  50687. enumerable: true,
  50688. configurable: true
  50689. });
  50690. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  50691. get: function () {
  50692. return ShadowGenerator._FILTER_POISSONSAMPLING;
  50693. },
  50694. enumerable: true,
  50695. configurable: true
  50696. });
  50697. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  50698. get: function () {
  50699. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  50700. },
  50701. enumerable: true,
  50702. configurable: true
  50703. });
  50704. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  50705. get: function () {
  50706. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  50707. },
  50708. enumerable: true,
  50709. configurable: true
  50710. });
  50711. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  50712. get: function () {
  50713. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50714. },
  50715. enumerable: true,
  50716. configurable: true
  50717. });
  50718. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  50719. get: function () {
  50720. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50721. },
  50722. enumerable: true,
  50723. configurable: true
  50724. });
  50725. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  50726. get: function () {
  50727. return this._bias;
  50728. },
  50729. set: function (bias) {
  50730. this._bias = bias;
  50731. },
  50732. enumerable: true,
  50733. configurable: true
  50734. });
  50735. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  50736. get: function () {
  50737. return this._blurBoxOffset;
  50738. },
  50739. set: function (value) {
  50740. if (this._blurBoxOffset === value) {
  50741. return;
  50742. }
  50743. this._blurBoxOffset = value;
  50744. this._disposeBlurPostProcesses();
  50745. },
  50746. enumerable: true,
  50747. configurable: true
  50748. });
  50749. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  50750. get: function () {
  50751. return this._blurScale;
  50752. },
  50753. set: function (value) {
  50754. if (this._blurScale === value) {
  50755. return;
  50756. }
  50757. this._blurScale = value;
  50758. this._disposeBlurPostProcesses();
  50759. },
  50760. enumerable: true,
  50761. configurable: true
  50762. });
  50763. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  50764. get: function () {
  50765. return this._blurKernel;
  50766. },
  50767. set: function (value) {
  50768. if (this._blurKernel === value) {
  50769. return;
  50770. }
  50771. this._blurKernel = value;
  50772. this._disposeBlurPostProcesses();
  50773. },
  50774. enumerable: true,
  50775. configurable: true
  50776. });
  50777. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  50778. get: function () {
  50779. return this._useKernelBlur;
  50780. },
  50781. set: function (value) {
  50782. if (this._useKernelBlur === value) {
  50783. return;
  50784. }
  50785. this._useKernelBlur = value;
  50786. this._disposeBlurPostProcesses();
  50787. },
  50788. enumerable: true,
  50789. configurable: true
  50790. });
  50791. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  50792. get: function () {
  50793. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  50794. },
  50795. set: function (value) {
  50796. this._depthScale = value;
  50797. },
  50798. enumerable: true,
  50799. configurable: true
  50800. });
  50801. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  50802. get: function () {
  50803. return this._filter;
  50804. },
  50805. set: function (value) {
  50806. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  50807. if (this._light.needCube()) {
  50808. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50809. this.useExponentialShadowMap = true;
  50810. return;
  50811. }
  50812. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50813. this.useCloseExponentialShadowMap = true;
  50814. return;
  50815. }
  50816. }
  50817. if (this._filter === value) {
  50818. return;
  50819. }
  50820. this._filter = value;
  50821. this._disposeBlurPostProcesses();
  50822. this._applyFilterValues();
  50823. this._light._markMeshesAsLightDirty();
  50824. },
  50825. enumerable: true,
  50826. configurable: true
  50827. });
  50828. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  50829. get: function () {
  50830. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  50831. },
  50832. set: function (value) {
  50833. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  50834. return;
  50835. }
  50836. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  50837. },
  50838. enumerable: true,
  50839. configurable: true
  50840. });
  50841. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  50842. get: function () {
  50843. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  50844. return this.useExponentialShadowMap;
  50845. },
  50846. set: function (value) {
  50847. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  50848. this.useExponentialShadowMap = value;
  50849. },
  50850. enumerable: true,
  50851. configurable: true
  50852. });
  50853. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  50854. get: function () {
  50855. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  50856. return this.useBlurExponentialShadowMap;
  50857. },
  50858. set: function (value) {
  50859. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  50860. this.useBlurExponentialShadowMap = value;
  50861. },
  50862. enumerable: true,
  50863. configurable: true
  50864. });
  50865. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  50866. get: function () {
  50867. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  50868. },
  50869. set: function (value) {
  50870. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  50871. return;
  50872. }
  50873. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50874. },
  50875. enumerable: true,
  50876. configurable: true
  50877. });
  50878. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  50879. get: function () {
  50880. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  50881. },
  50882. set: function (value) {
  50883. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50884. return;
  50885. }
  50886. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50887. },
  50888. enumerable: true,
  50889. configurable: true
  50890. });
  50891. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  50892. get: function () {
  50893. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50894. },
  50895. set: function (value) {
  50896. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  50897. return;
  50898. }
  50899. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50900. },
  50901. enumerable: true,
  50902. configurable: true
  50903. });
  50904. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  50905. get: function () {
  50906. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50907. },
  50908. set: function (value) {
  50909. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50910. return;
  50911. }
  50912. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50913. },
  50914. enumerable: true,
  50915. configurable: true
  50916. });
  50917. /**
  50918. * Returns the darkness value (float).
  50919. */
  50920. ShadowGenerator.prototype.getDarkness = function () {
  50921. return this._darkness;
  50922. };
  50923. /**
  50924. * Sets the ShadowGenerator darkness value (float <= 1.0).
  50925. * Returns the ShadowGenerator.
  50926. */
  50927. ShadowGenerator.prototype.setDarkness = function (darkness) {
  50928. if (darkness >= 1.0)
  50929. this._darkness = 1.0;
  50930. else if (darkness <= 0.0)
  50931. this._darkness = 0.0;
  50932. else
  50933. this._darkness = darkness;
  50934. return this;
  50935. };
  50936. /**
  50937. * Sets the ability to have transparent shadow (boolean).
  50938. * Returns the ShadowGenerator.
  50939. */
  50940. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  50941. this._transparencyShadow = hasShadow;
  50942. return this;
  50943. };
  50944. /**
  50945. * Returns a RenderTargetTexture object : the shadow map texture.
  50946. */
  50947. ShadowGenerator.prototype.getShadowMap = function () {
  50948. return this._shadowMap;
  50949. };
  50950. /**
  50951. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  50952. */
  50953. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  50954. if (this._shadowMap2) {
  50955. return this._shadowMap2;
  50956. }
  50957. return this._shadowMap;
  50958. };
  50959. /**
  50960. * Helper function to add a mesh and its descendants to the list of shadow casters
  50961. * @param mesh Mesh to add
  50962. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  50963. */
  50964. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  50965. if (includeDescendants === void 0) { includeDescendants = true; }
  50966. if (!this._shadowMap) {
  50967. return this;
  50968. }
  50969. if (!this._shadowMap.renderList) {
  50970. this._shadowMap.renderList = [];
  50971. }
  50972. this._shadowMap.renderList.push(mesh);
  50973. if (includeDescendants) {
  50974. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  50975. }
  50976. return this;
  50977. var _a;
  50978. };
  50979. /**
  50980. * Helper function to remove a mesh and its descendants from the list of shadow casters
  50981. * @param mesh Mesh to remove
  50982. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  50983. */
  50984. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  50985. if (includeDescendants === void 0) { includeDescendants = true; }
  50986. if (!this._shadowMap || !this._shadowMap.renderList) {
  50987. return this;
  50988. }
  50989. var index = this._shadowMap.renderList.indexOf(mesh);
  50990. if (index !== -1) {
  50991. this._shadowMap.renderList.splice(index, 1);
  50992. }
  50993. if (includeDescendants) {
  50994. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  50995. var child = _a[_i];
  50996. this.removeShadowCaster(child);
  50997. }
  50998. }
  50999. return this;
  51000. };
  51001. /**
  51002. * Returns the associated light object.
  51003. */
  51004. ShadowGenerator.prototype.getLight = function () {
  51005. return this._light;
  51006. };
  51007. ShadowGenerator.prototype._initializeGenerator = function () {
  51008. this._light._markMeshesAsLightDirty();
  51009. this._initializeShadowMap();
  51010. };
  51011. ShadowGenerator.prototype._initializeShadowMap = function () {
  51012. var _this = this;
  51013. // Render target
  51014. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51015. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51016. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51017. this._shadowMap.anisotropicFilteringLevel = 1;
  51018. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51019. this._shadowMap.renderParticles = false;
  51020. this._shadowMap.ignoreCameraViewport = true;
  51021. // Record Face Index before render.
  51022. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51023. _this._currentFaceIndex = faceIndex;
  51024. });
  51025. // Custom render function.
  51026. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51027. // Blur if required afer render.
  51028. this._shadowMap.onAfterUnbindObservable.add(function () {
  51029. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51030. return;
  51031. }
  51032. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51033. _this._initializeBlurRTTAndPostProcesses();
  51034. }
  51035. var shadowMap = _this.getShadowMapForRendering();
  51036. if (shadowMap) {
  51037. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51038. }
  51039. });
  51040. // Clear according to the chosen filter.
  51041. this._shadowMap.onClearObservable.add(function (engine) {
  51042. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51043. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51044. }
  51045. else {
  51046. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51047. }
  51048. });
  51049. };
  51050. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51051. var _this = this;
  51052. var engine = this._scene.getEngine();
  51053. var targetSize = this._mapSize / this.blurScale;
  51054. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51055. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51056. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51057. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51058. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51059. }
  51060. if (this.useKernelBlur) {
  51061. 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);
  51062. this._kernelBlurXPostprocess.width = targetSize;
  51063. this._kernelBlurXPostprocess.height = targetSize;
  51064. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51065. effect.setTexture("textureSampler", _this._shadowMap);
  51066. });
  51067. 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);
  51068. this._kernelBlurXPostprocess.autoClear = false;
  51069. this._kernelBlurYPostprocess.autoClear = false;
  51070. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51071. this._kernelBlurXPostprocess.packedFloat = true;
  51072. this._kernelBlurYPostprocess.packedFloat = true;
  51073. }
  51074. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51075. }
  51076. else {
  51077. 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);
  51078. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51079. effect.setFloat2("screenSize", targetSize, targetSize);
  51080. effect.setTexture("textureSampler", _this._shadowMap);
  51081. });
  51082. this._boxBlurPostprocess.autoClear = false;
  51083. this._blurPostProcesses = [this._boxBlurPostprocess];
  51084. }
  51085. };
  51086. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  51087. var index;
  51088. var engine = this._scene.getEngine();
  51089. if (depthOnlySubMeshes.length) {
  51090. engine.setColorWrite(false);
  51091. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  51092. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  51093. }
  51094. engine.setColorWrite(true);
  51095. }
  51096. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51097. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  51098. }
  51099. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51100. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  51101. }
  51102. if (this._transparencyShadow) {
  51103. for (index = 0; index < transparentSubMeshes.length; index++) {
  51104. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  51105. }
  51106. }
  51107. };
  51108. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  51109. var _this = this;
  51110. var mesh = subMesh.getRenderingMesh();
  51111. var scene = this._scene;
  51112. var engine = scene.getEngine();
  51113. var material = subMesh.getMaterial();
  51114. if (!material) {
  51115. return;
  51116. }
  51117. // Culling
  51118. engine.setState(material.backFaceCulling);
  51119. // Managing instances
  51120. var batch = mesh._getInstancesRenderList(subMesh._id);
  51121. if (batch.mustReturn) {
  51122. return;
  51123. }
  51124. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  51125. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  51126. engine.enableEffect(this._effect);
  51127. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  51128. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  51129. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  51130. this._effect.setVector3("lightPosition", this.getLight().position);
  51131. if (scene.activeCamera) {
  51132. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  51133. }
  51134. // Alpha test
  51135. if (material && material.needAlphaTesting()) {
  51136. var alphaTexture = material.getAlphaTestTexture();
  51137. if (alphaTexture) {
  51138. this._effect.setTexture("diffuseSampler", alphaTexture);
  51139. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  51140. }
  51141. }
  51142. // Bones
  51143. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51144. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  51145. }
  51146. if (this.forceBackFacesOnly) {
  51147. engine.setState(true, 0, false, true);
  51148. }
  51149. // Draw
  51150. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51151. if (this.forceBackFacesOnly) {
  51152. engine.setState(true, 0, false, false);
  51153. }
  51154. }
  51155. else {
  51156. // Need to reset refresh rate of the shadowMap
  51157. if (this._shadowMap) {
  51158. this._shadowMap.resetRefreshCounter();
  51159. }
  51160. }
  51161. };
  51162. ShadowGenerator.prototype._applyFilterValues = function () {
  51163. if (!this._shadowMap) {
  51164. return;
  51165. }
  51166. if (this.filter === ShadowGenerator.FILTER_NONE) {
  51167. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  51168. }
  51169. else {
  51170. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51171. }
  51172. };
  51173. /**
  51174. * Force shader compilation including textures ready check
  51175. */
  51176. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  51177. var _this = this;
  51178. var shadowMap = this.getShadowMap();
  51179. if (!shadowMap) {
  51180. return;
  51181. }
  51182. var subMeshes = new Array();
  51183. var currentIndex = 0;
  51184. var renderList = shadowMap.renderList;
  51185. if (!renderList) {
  51186. return;
  51187. }
  51188. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  51189. var mesh = renderList_1[_i];
  51190. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  51191. }
  51192. var checkReady = function () {
  51193. if (!_this._scene || !_this._scene.getEngine()) {
  51194. return;
  51195. }
  51196. var subMesh = subMeshes[currentIndex];
  51197. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  51198. currentIndex++;
  51199. if (currentIndex >= subMeshes.length) {
  51200. if (onCompiled) {
  51201. onCompiled(_this);
  51202. }
  51203. return;
  51204. }
  51205. }
  51206. setTimeout(checkReady, 16);
  51207. };
  51208. if (subMeshes.length > 0) {
  51209. checkReady();
  51210. }
  51211. };
  51212. /**
  51213. * Boolean : true when the ShadowGenerator is finally computed.
  51214. */
  51215. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  51216. var defines = [];
  51217. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51218. defines.push("#define FLOAT");
  51219. }
  51220. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51221. defines.push("#define ESM");
  51222. }
  51223. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51224. var mesh = subMesh.getMesh();
  51225. var material = subMesh.getMaterial();
  51226. // Alpha test
  51227. if (material && material.needAlphaTesting()) {
  51228. var alphaTexture = material.getAlphaTestTexture();
  51229. if (alphaTexture) {
  51230. defines.push("#define ALPHATEST");
  51231. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51232. attribs.push(BABYLON.VertexBuffer.UVKind);
  51233. defines.push("#define UV1");
  51234. }
  51235. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51236. if (alphaTexture.coordinatesIndex === 1) {
  51237. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51238. defines.push("#define UV2");
  51239. }
  51240. }
  51241. }
  51242. }
  51243. // Bones
  51244. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51245. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51246. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51247. if (mesh.numBoneInfluencers > 4) {
  51248. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51249. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51250. }
  51251. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51252. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51253. }
  51254. else {
  51255. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51256. }
  51257. // Instances
  51258. if (useInstances) {
  51259. defines.push("#define INSTANCES");
  51260. attribs.push("world0");
  51261. attribs.push("world1");
  51262. attribs.push("world2");
  51263. attribs.push("world3");
  51264. }
  51265. // Get correct effect
  51266. var join = defines.join("\n");
  51267. if (this._cachedDefines !== join) {
  51268. this._cachedDefines = join;
  51269. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  51270. }
  51271. return this._effect.isReady();
  51272. };
  51273. /**
  51274. * This creates the defines related to the standard BJS materials.
  51275. */
  51276. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  51277. var scene = this._scene;
  51278. var light = this._light;
  51279. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51280. return;
  51281. }
  51282. defines["SHADOW" + lightIndex] = true;
  51283. if (this.usePoissonSampling) {
  51284. defines["SHADOWPCF" + lightIndex] = true;
  51285. }
  51286. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51287. defines["SHADOWESM" + lightIndex] = true;
  51288. }
  51289. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  51290. defines["SHADOWCLOSEESM" + lightIndex] = true;
  51291. }
  51292. if (light.needCube()) {
  51293. defines["SHADOWCUBE" + lightIndex] = true;
  51294. }
  51295. };
  51296. /**
  51297. * This binds shadow lights related to the standard BJS materials.
  51298. * It implies the unifroms available on the materials are the standard BJS ones.
  51299. */
  51300. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  51301. var light = this._light;
  51302. var scene = this._scene;
  51303. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51304. return;
  51305. }
  51306. var camera = scene.activeCamera;
  51307. if (!camera) {
  51308. return;
  51309. }
  51310. var shadowMap = this.getShadowMap();
  51311. if (!shadowMap) {
  51312. return;
  51313. }
  51314. if (!light.needCube()) {
  51315. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  51316. }
  51317. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  51318. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  51319. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  51320. };
  51321. // Methods
  51322. /**
  51323. * Returns a Matrix object : the updated transformation matrix.
  51324. */
  51325. ShadowGenerator.prototype.getTransformMatrix = function () {
  51326. var scene = this._scene;
  51327. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  51328. return this._transformMatrix;
  51329. }
  51330. this._currentRenderID = scene.getRenderId();
  51331. this._currentFaceIndexCache = this._currentFaceIndex;
  51332. var lightPosition = this._light.position;
  51333. if (this._light.computeTransformedInformation()) {
  51334. lightPosition = this._light.transformedPosition;
  51335. }
  51336. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  51337. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  51338. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  51339. }
  51340. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  51341. this._cachedPosition = lightPosition.clone();
  51342. this._cachedDirection = this._lightDirection.clone();
  51343. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  51344. var shadowMap = this.getShadowMap();
  51345. if (shadowMap) {
  51346. var renderList = shadowMap.renderList;
  51347. if (renderList) {
  51348. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  51349. }
  51350. }
  51351. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  51352. }
  51353. return this._transformMatrix;
  51354. };
  51355. ShadowGenerator.prototype.recreateShadowMap = function () {
  51356. var shadowMap = this._shadowMap;
  51357. if (!shadowMap) {
  51358. return;
  51359. }
  51360. // Track render list.
  51361. var renderList = shadowMap.renderList;
  51362. // Clean up existing data.
  51363. this._disposeRTTandPostProcesses();
  51364. // Reinitializes.
  51365. this._initializeGenerator();
  51366. // Reaffect the filter to ensure a correct fallback if necessary.
  51367. this.filter = this.filter;
  51368. // Reaffect the filter.
  51369. this._applyFilterValues();
  51370. // Reaffect Render List.
  51371. shadowMap.renderList = renderList;
  51372. };
  51373. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  51374. if (this._shadowMap2) {
  51375. this._shadowMap2.dispose();
  51376. this._shadowMap2 = null;
  51377. }
  51378. if (this._downSamplePostprocess) {
  51379. this._downSamplePostprocess.dispose();
  51380. this._downSamplePostprocess = null;
  51381. }
  51382. if (this._boxBlurPostprocess) {
  51383. this._boxBlurPostprocess.dispose();
  51384. this._boxBlurPostprocess = null;
  51385. }
  51386. if (this._kernelBlurXPostprocess) {
  51387. this._kernelBlurXPostprocess.dispose();
  51388. this._kernelBlurXPostprocess = null;
  51389. }
  51390. if (this._kernelBlurYPostprocess) {
  51391. this._kernelBlurYPostprocess.dispose();
  51392. this._kernelBlurYPostprocess = null;
  51393. }
  51394. this._blurPostProcesses = [];
  51395. };
  51396. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  51397. if (this._shadowMap) {
  51398. this._shadowMap.dispose();
  51399. this._shadowMap = null;
  51400. }
  51401. this._disposeBlurPostProcesses();
  51402. };
  51403. /**
  51404. * Disposes the ShadowGenerator.
  51405. * Returns nothing.
  51406. */
  51407. ShadowGenerator.prototype.dispose = function () {
  51408. this._disposeRTTandPostProcesses();
  51409. if (this._light) {
  51410. this._light._shadowGenerator = null;
  51411. this._light._markMeshesAsLightDirty();
  51412. }
  51413. };
  51414. /**
  51415. * Serializes the ShadowGenerator and returns a serializationObject.
  51416. */
  51417. ShadowGenerator.prototype.serialize = function () {
  51418. var serializationObject = {};
  51419. var shadowMap = this.getShadowMap();
  51420. if (!shadowMap) {
  51421. return serializationObject;
  51422. }
  51423. serializationObject.lightId = this._light.id;
  51424. serializationObject.mapSize = shadowMap.getRenderSize();
  51425. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  51426. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  51427. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51428. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51429. serializationObject.usePoissonSampling = this.usePoissonSampling;
  51430. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  51431. serializationObject.depthScale = this.depthScale;
  51432. serializationObject.darkness = this.getDarkness();
  51433. serializationObject.blurBoxOffset = this.blurBoxOffset;
  51434. serializationObject.blurKernel = this.blurKernel;
  51435. serializationObject.blurScale = this.blurScale;
  51436. serializationObject.useKernelBlur = this.useKernelBlur;
  51437. serializationObject.transparencyShadow = this._transparencyShadow;
  51438. serializationObject.renderList = [];
  51439. if (shadowMap.renderList) {
  51440. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  51441. var mesh = shadowMap.renderList[meshIndex];
  51442. serializationObject.renderList.push(mesh.id);
  51443. }
  51444. }
  51445. return serializationObject;
  51446. };
  51447. /**
  51448. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  51449. */
  51450. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  51451. //casting to point light, as light is missing the position attr and typescript complains.
  51452. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  51453. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  51454. var shadowMap = shadowGenerator.getShadowMap();
  51455. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  51456. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  51457. meshes.forEach(function (mesh) {
  51458. if (!shadowMap) {
  51459. return;
  51460. }
  51461. if (!shadowMap.renderList) {
  51462. shadowMap.renderList = [];
  51463. }
  51464. shadowMap.renderList.push(mesh);
  51465. });
  51466. }
  51467. if (parsedShadowGenerator.usePoissonSampling) {
  51468. shadowGenerator.usePoissonSampling = true;
  51469. }
  51470. else if (parsedShadowGenerator.useExponentialShadowMap) {
  51471. shadowGenerator.useExponentialShadowMap = true;
  51472. }
  51473. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  51474. shadowGenerator.useBlurExponentialShadowMap = true;
  51475. }
  51476. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  51477. shadowGenerator.useCloseExponentialShadowMap = true;
  51478. }
  51479. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  51480. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  51481. }
  51482. else if (parsedShadowGenerator.useVarianceShadowMap) {
  51483. shadowGenerator.useExponentialShadowMap = true;
  51484. }
  51485. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  51486. shadowGenerator.useBlurExponentialShadowMap = true;
  51487. }
  51488. if (parsedShadowGenerator.depthScale) {
  51489. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  51490. }
  51491. if (parsedShadowGenerator.blurScale) {
  51492. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  51493. }
  51494. if (parsedShadowGenerator.blurBoxOffset) {
  51495. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  51496. }
  51497. if (parsedShadowGenerator.useKernelBlur) {
  51498. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  51499. }
  51500. if (parsedShadowGenerator.blurKernel) {
  51501. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  51502. }
  51503. if (parsedShadowGenerator.bias !== undefined) {
  51504. shadowGenerator.bias = parsedShadowGenerator.bias;
  51505. }
  51506. if (parsedShadowGenerator.darkness) {
  51507. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  51508. }
  51509. if (parsedShadowGenerator.transparencyShadow) {
  51510. shadowGenerator.setTransparencyShadow(true);
  51511. }
  51512. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  51513. return shadowGenerator;
  51514. };
  51515. ShadowGenerator._FILTER_NONE = 0;
  51516. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  51517. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  51518. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  51519. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  51520. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  51521. return ShadowGenerator;
  51522. }());
  51523. BABYLON.ShadowGenerator = ShadowGenerator;
  51524. })(BABYLON || (BABYLON = {}));
  51525. //# sourceMappingURL=babylon.shadowGenerator.js.map
  51526. var BABYLON;
  51527. (function (BABYLON) {
  51528. var DefaultLoadingScreen = /** @class */ (function () {
  51529. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  51530. if (_loadingText === void 0) { _loadingText = ""; }
  51531. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  51532. var _this = this;
  51533. this._renderingCanvas = _renderingCanvas;
  51534. this._loadingText = _loadingText;
  51535. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  51536. // Resize
  51537. this._resizeLoadingUI = function () {
  51538. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  51539. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  51540. if (!_this._loadingDiv) {
  51541. return;
  51542. }
  51543. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  51544. _this._loadingDiv.style.left = canvasRect.left + "px";
  51545. _this._loadingDiv.style.top = canvasRect.top + "px";
  51546. _this._loadingDiv.style.width = canvasRect.width + "px";
  51547. _this._loadingDiv.style.height = canvasRect.height + "px";
  51548. };
  51549. }
  51550. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  51551. if (this._loadingDiv) {
  51552. // Do not add a loading screen if there is already one
  51553. return;
  51554. }
  51555. this._loadingDiv = document.createElement("div");
  51556. this._loadingDiv.id = "babylonjsLoadingDiv";
  51557. this._loadingDiv.style.opacity = "0";
  51558. this._loadingDiv.style.transition = "opacity 1.5s ease";
  51559. this._loadingDiv.style.pointerEvents = "none";
  51560. // Loading text
  51561. this._loadingTextDiv = document.createElement("div");
  51562. this._loadingTextDiv.style.position = "absolute";
  51563. this._loadingTextDiv.style.left = "0";
  51564. this._loadingTextDiv.style.top = "50%";
  51565. this._loadingTextDiv.style.marginTop = "80px";
  51566. this._loadingTextDiv.style.width = "100%";
  51567. this._loadingTextDiv.style.height = "20px";
  51568. this._loadingTextDiv.style.fontFamily = "Arial";
  51569. this._loadingTextDiv.style.fontSize = "14px";
  51570. this._loadingTextDiv.style.color = "white";
  51571. this._loadingTextDiv.style.textAlign = "center";
  51572. this._loadingTextDiv.innerHTML = "Loading";
  51573. this._loadingDiv.appendChild(this._loadingTextDiv);
  51574. //set the predefined text
  51575. this._loadingTextDiv.innerHTML = this._loadingText;
  51576. // Generating keyframes
  51577. var style = document.createElement('style');
  51578. style.type = 'text/css';
  51579. 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 }";
  51580. style.innerHTML = keyFrames;
  51581. document.getElementsByTagName('head')[0].appendChild(style);
  51582. // Loading img
  51583. var imgBack = new Image();
  51584. 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";
  51585. imgBack.style.position = "absolute";
  51586. imgBack.style.left = "50%";
  51587. imgBack.style.top = "50%";
  51588. imgBack.style.marginLeft = "-60px";
  51589. imgBack.style.marginTop = "-60px";
  51590. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  51591. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  51592. imgBack.style.transformOrigin = "50% 50%";
  51593. imgBack.style.webkitTransformOrigin = "50% 50%";
  51594. this._loadingDiv.appendChild(imgBack);
  51595. this._resizeLoadingUI();
  51596. window.addEventListener("resize", this._resizeLoadingUI);
  51597. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51598. document.body.appendChild(this._loadingDiv);
  51599. this._loadingDiv.style.opacity = "1";
  51600. };
  51601. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  51602. var _this = this;
  51603. if (!this._loadingDiv) {
  51604. return;
  51605. }
  51606. var onTransitionEnd = function () {
  51607. if (!_this._loadingDiv) {
  51608. return;
  51609. }
  51610. document.body.removeChild(_this._loadingDiv);
  51611. window.removeEventListener("resize", _this._resizeLoadingUI);
  51612. _this._loadingDiv = null;
  51613. };
  51614. this._loadingDiv.style.opacity = "0";
  51615. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  51616. };
  51617. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  51618. set: function (text) {
  51619. this._loadingText = text;
  51620. if (this._loadingTextDiv) {
  51621. this._loadingTextDiv.innerHTML = this._loadingText;
  51622. }
  51623. },
  51624. enumerable: true,
  51625. configurable: true
  51626. });
  51627. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  51628. get: function () {
  51629. return this._loadingDivBackgroundColor;
  51630. },
  51631. set: function (color) {
  51632. this._loadingDivBackgroundColor = color;
  51633. if (!this._loadingDiv) {
  51634. return;
  51635. }
  51636. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51637. },
  51638. enumerable: true,
  51639. configurable: true
  51640. });
  51641. return DefaultLoadingScreen;
  51642. }());
  51643. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  51644. })(BABYLON || (BABYLON = {}));
  51645. //# sourceMappingURL=babylon.loadingScreen.js.map
  51646. var BABYLON;
  51647. (function (BABYLON) {
  51648. var SceneLoader = /** @class */ (function () {
  51649. function SceneLoader() {
  51650. }
  51651. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  51652. get: function () {
  51653. return 0;
  51654. },
  51655. enumerable: true,
  51656. configurable: true
  51657. });
  51658. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  51659. get: function () {
  51660. return 1;
  51661. },
  51662. enumerable: true,
  51663. configurable: true
  51664. });
  51665. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  51666. get: function () {
  51667. return 2;
  51668. },
  51669. enumerable: true,
  51670. configurable: true
  51671. });
  51672. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  51673. get: function () {
  51674. return 3;
  51675. },
  51676. enumerable: true,
  51677. configurable: true
  51678. });
  51679. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  51680. get: function () {
  51681. return SceneLoader._ForceFullSceneLoadingForIncremental;
  51682. },
  51683. set: function (value) {
  51684. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  51685. },
  51686. enumerable: true,
  51687. configurable: true
  51688. });
  51689. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  51690. get: function () {
  51691. return SceneLoader._ShowLoadingScreen;
  51692. },
  51693. set: function (value) {
  51694. SceneLoader._ShowLoadingScreen = value;
  51695. },
  51696. enumerable: true,
  51697. configurable: true
  51698. });
  51699. Object.defineProperty(SceneLoader, "loggingLevel", {
  51700. get: function () {
  51701. return SceneLoader._loggingLevel;
  51702. },
  51703. set: function (value) {
  51704. SceneLoader._loggingLevel = value;
  51705. },
  51706. enumerable: true,
  51707. configurable: true
  51708. });
  51709. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  51710. get: function () {
  51711. return SceneLoader._CleanBoneMatrixWeights;
  51712. },
  51713. set: function (value) {
  51714. SceneLoader._CleanBoneMatrixWeights = value;
  51715. },
  51716. enumerable: true,
  51717. configurable: true
  51718. });
  51719. SceneLoader._getDefaultPlugin = function () {
  51720. return SceneLoader._registeredPlugins[".babylon"];
  51721. };
  51722. SceneLoader._getPluginForExtension = function (extension) {
  51723. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  51724. if (registeredPlugin) {
  51725. return registeredPlugin;
  51726. }
  51727. return SceneLoader._getDefaultPlugin();
  51728. };
  51729. SceneLoader._getPluginForDirectLoad = function (data) {
  51730. for (var extension in SceneLoader._registeredPlugins) {
  51731. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  51732. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  51733. return SceneLoader._registeredPlugins[extension];
  51734. }
  51735. }
  51736. return SceneLoader._getDefaultPlugin();
  51737. };
  51738. SceneLoader._getPluginForFilename = function (sceneFilename) {
  51739. if (sceneFilename.name) {
  51740. sceneFilename = sceneFilename.name;
  51741. }
  51742. var dotPosition = sceneFilename.lastIndexOf(".");
  51743. var queryStringPosition = sceneFilename.indexOf("?");
  51744. if (queryStringPosition === -1) {
  51745. queryStringPosition = sceneFilename.length;
  51746. }
  51747. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  51748. return SceneLoader._getPluginForExtension(extension);
  51749. };
  51750. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  51751. SceneLoader._getDirectLoad = function (sceneFilename) {
  51752. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  51753. return sceneFilename.substr(5);
  51754. }
  51755. return null;
  51756. };
  51757. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51758. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  51759. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  51760. var plugin = registeredPlugin.plugin;
  51761. var useArrayBuffer = registeredPlugin.isBinary;
  51762. var database;
  51763. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  51764. var dataCallback = function (data) {
  51765. if (scene.isDisposed) {
  51766. onError("Scene has been disposed");
  51767. return;
  51768. }
  51769. scene.database = database;
  51770. try {
  51771. onSuccess(plugin, data);
  51772. }
  51773. catch (e) {
  51774. onError(null, e);
  51775. }
  51776. };
  51777. var manifestChecked = function (success) {
  51778. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  51779. if (request) {
  51780. onError(request.status + " " + request.statusText);
  51781. }
  51782. });
  51783. };
  51784. if (directLoad) {
  51785. dataCallback(directLoad);
  51786. return;
  51787. }
  51788. if (rootUrl.indexOf("file:") === -1) {
  51789. if (scene.getEngine().enableOfflineSupport) {
  51790. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  51791. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  51792. }
  51793. else {
  51794. manifestChecked(true);
  51795. }
  51796. }
  51797. else {
  51798. var fileOrString = sceneFilename;
  51799. if (fileOrString.name) {
  51800. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  51801. }
  51802. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  51803. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  51804. }
  51805. else {
  51806. onError("Unable to find file named " + sceneFilename);
  51807. return;
  51808. }
  51809. }
  51810. };
  51811. // Public functions
  51812. SceneLoader.GetPluginForExtension = function (extension) {
  51813. return SceneLoader._getPluginForExtension(extension).plugin;
  51814. };
  51815. SceneLoader.RegisterPlugin = function (plugin) {
  51816. if (typeof plugin.extensions === "string") {
  51817. var extension = plugin.extensions;
  51818. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51819. plugin: plugin,
  51820. isBinary: false
  51821. };
  51822. }
  51823. else {
  51824. var extensions = plugin.extensions;
  51825. Object.keys(extensions).forEach(function (extension) {
  51826. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51827. plugin: plugin,
  51828. isBinary: extensions[extension].isBinary
  51829. };
  51830. });
  51831. }
  51832. };
  51833. /**
  51834. * Import meshes into a scene
  51835. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  51836. * @param rootUrl a string that defines the root url for scene and resources
  51837. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51838. * @param scene the instance of BABYLON.Scene to append to
  51839. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  51840. * @param onProgress a callback with a progress event for each file being loaded
  51841. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51842. */
  51843. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51844. if (onSuccess === void 0) { onSuccess = null; }
  51845. if (onProgress === void 0) { onProgress = null; }
  51846. if (onError === void 0) { onError = null; }
  51847. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  51848. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  51849. return;
  51850. }
  51851. var loadingToken = {};
  51852. scene._addPendingData(loadingToken);
  51853. var errorHandler = function (message, exception) {
  51854. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  51855. if (onError) {
  51856. onError(scene, errorMessage, exception);
  51857. }
  51858. else {
  51859. BABYLON.Tools.Error(errorMessage);
  51860. // should the exception be thrown?
  51861. }
  51862. scene._removePendingData(loadingToken);
  51863. };
  51864. var progressHandler = function (event) {
  51865. if (onProgress) {
  51866. onProgress(event);
  51867. }
  51868. };
  51869. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  51870. if (plugin.importMesh) {
  51871. var syncedPlugin = plugin;
  51872. var meshes = new Array();
  51873. var particleSystems = new Array();
  51874. var skeletons = new Array();
  51875. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  51876. return;
  51877. }
  51878. if (onSuccess) {
  51879. // wrap onSuccess with try-catch to know if something went wrong.
  51880. try {
  51881. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  51882. onSuccess(meshes, particleSystems, skeletons);
  51883. scene._removePendingData(loadingToken);
  51884. }
  51885. catch (e) {
  51886. var message = 'Error in onSuccess callback.';
  51887. errorHandler(message, e);
  51888. }
  51889. }
  51890. }
  51891. else {
  51892. var asyncedPlugin = plugin;
  51893. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  51894. if (onSuccess) {
  51895. try {
  51896. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  51897. onSuccess(meshes, particleSystems, skeletons);
  51898. scene._removePendingData(loadingToken);
  51899. }
  51900. catch (e) {
  51901. var message = 'Error in onSuccess callback.';
  51902. errorHandler(message, e);
  51903. }
  51904. }
  51905. }, progressHandler, errorHandler);
  51906. }
  51907. }, progressHandler, errorHandler);
  51908. };
  51909. /**
  51910. * Load a scene
  51911. * @param rootUrl a string that defines the root url for scene and resources
  51912. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51913. * @param engine is the instance of BABYLON.Engine to use to create the scene
  51914. * @param onSuccess a callback with the scene when import succeeds
  51915. * @param onProgress a callback with a progress event for each file being loaded
  51916. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51917. */
  51918. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  51919. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  51920. };
  51921. /**
  51922. * Append a scene
  51923. * @param rootUrl a string that defines the root url for scene and resources
  51924. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51925. * @param scene is the instance of BABYLON.Scene to append to
  51926. * @param onSuccess a callback with the scene when import succeeds
  51927. * @param onProgress a callback with a progress event for each file being loaded
  51928. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51929. */
  51930. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51931. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  51932. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  51933. return;
  51934. }
  51935. if (SceneLoader.ShowLoadingScreen) {
  51936. scene.getEngine().displayLoadingUI();
  51937. }
  51938. var loadingToken = {};
  51939. scene._addPendingData(loadingToken);
  51940. var errorHandler = function (message, exception) {
  51941. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  51942. if (onError) {
  51943. onError(scene, errorMessage, exception);
  51944. }
  51945. else {
  51946. BABYLON.Tools.Error(errorMessage);
  51947. // should the exception be thrown?
  51948. }
  51949. scene._removePendingData(loadingToken);
  51950. scene.getEngine().hideLoadingUI();
  51951. };
  51952. var progressHandler = function (event) {
  51953. if (onProgress) {
  51954. onProgress(event);
  51955. }
  51956. };
  51957. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  51958. if (plugin.load) {
  51959. var syncedPlugin = plugin;
  51960. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  51961. return;
  51962. }
  51963. if (onSuccess) {
  51964. try {
  51965. onSuccess(scene);
  51966. }
  51967. catch (e) {
  51968. errorHandler("Error in onSuccess callback", e);
  51969. }
  51970. }
  51971. scene.loadingPluginName = plugin.name;
  51972. scene._removePendingData(loadingToken);
  51973. }
  51974. else {
  51975. var asyncedPlugin = plugin;
  51976. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  51977. if (onSuccess) {
  51978. onSuccess(scene);
  51979. }
  51980. scene.loadingPluginName = plugin.name;
  51981. scene._removePendingData(loadingToken);
  51982. }, progressHandler, errorHandler);
  51983. }
  51984. if (SceneLoader.ShowLoadingScreen) {
  51985. scene.executeWhenReady(function () {
  51986. scene.getEngine().hideLoadingUI();
  51987. });
  51988. }
  51989. }, progressHandler, errorHandler);
  51990. };
  51991. // Flags
  51992. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  51993. SceneLoader._ShowLoadingScreen = true;
  51994. SceneLoader._CleanBoneMatrixWeights = false;
  51995. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  51996. // Members
  51997. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  51998. SceneLoader._registeredPlugins = {};
  51999. return SceneLoader;
  52000. }());
  52001. BABYLON.SceneLoader = SceneLoader;
  52002. ;
  52003. })(BABYLON || (BABYLON = {}));
  52004. //# sourceMappingURL=babylon.sceneLoader.js.map
  52005. var BABYLON;
  52006. (function (BABYLON) {
  52007. var Internals;
  52008. (function (Internals) {
  52009. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52010. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52011. var parsedMaterial = parsedData.materials[index];
  52012. if (parsedMaterial.id === id) {
  52013. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52014. }
  52015. }
  52016. return null;
  52017. };
  52018. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52019. for (var i in names) {
  52020. if (mesh.name === names[i]) {
  52021. hierarchyIds.push(mesh.id);
  52022. return true;
  52023. }
  52024. }
  52025. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52026. hierarchyIds.push(mesh.id);
  52027. return true;
  52028. }
  52029. return false;
  52030. };
  52031. var logOperation = function (operation, producer) {
  52032. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52033. };
  52034. BABYLON.SceneLoader.RegisterPlugin({
  52035. name: "babylon.js",
  52036. extensions: ".babylon",
  52037. canDirectLoad: function (data) {
  52038. if (data.indexOf("babylon") !== -1) {
  52039. return true;
  52040. }
  52041. return false;
  52042. },
  52043. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52044. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52045. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52046. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52047. // and avoid problems with multiple concurrent .babylon loads.
  52048. var log = "importMesh has failed JSON parse";
  52049. try {
  52050. var parsedData = JSON.parse(data);
  52051. log = "";
  52052. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52053. if (!meshesNames) {
  52054. meshesNames = null;
  52055. }
  52056. else if (!Array.isArray(meshesNames)) {
  52057. meshesNames = [meshesNames];
  52058. }
  52059. var hierarchyIds = new Array();
  52060. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52061. var loadedSkeletonsIds = [];
  52062. var loadedMaterialsIds = [];
  52063. var index;
  52064. var cache;
  52065. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52066. var parsedMesh = parsedData.meshes[index];
  52067. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52068. if (meshesNames !== null) {
  52069. // Remove found mesh name from list.
  52070. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52071. }
  52072. //Geometry?
  52073. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  52074. //does the file contain geometries?
  52075. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  52076. //find the correct geometry and add it to the scene
  52077. var found = false;
  52078. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  52079. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  52080. return;
  52081. }
  52082. else {
  52083. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  52084. if (parsedGeometryData.id === parsedMesh.geometryId) {
  52085. switch (geometryType) {
  52086. case "boxes":
  52087. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  52088. break;
  52089. case "spheres":
  52090. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  52091. break;
  52092. case "cylinders":
  52093. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  52094. break;
  52095. case "toruses":
  52096. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  52097. break;
  52098. case "grounds":
  52099. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  52100. break;
  52101. case "planes":
  52102. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  52103. break;
  52104. case "torusKnots":
  52105. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  52106. break;
  52107. case "vertexData":
  52108. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  52109. break;
  52110. }
  52111. found = true;
  52112. }
  52113. });
  52114. }
  52115. });
  52116. if (found === false) {
  52117. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  52118. }
  52119. }
  52120. }
  52121. // Material ?
  52122. if (parsedMesh.materialId) {
  52123. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  52124. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52125. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  52126. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  52127. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  52128. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  52129. var subMatId = parsedMultiMaterial.materials[matIndex];
  52130. loadedMaterialsIds.push(subMatId);
  52131. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  52132. log += "\n\tMaterial " + mat.toString(fullDetails);
  52133. }
  52134. loadedMaterialsIds.push(parsedMultiMaterial.id);
  52135. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52136. materialFound = true;
  52137. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  52138. break;
  52139. }
  52140. }
  52141. }
  52142. if (materialFound === false) {
  52143. loadedMaterialsIds.push(parsedMesh.materialId);
  52144. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  52145. if (!mat) {
  52146. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  52147. }
  52148. else {
  52149. log += "\n\tMaterial " + mat.toString(fullDetails);
  52150. }
  52151. }
  52152. }
  52153. // Skeleton ?
  52154. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52155. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  52156. if (skeletonAlreadyLoaded === false) {
  52157. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  52158. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  52159. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  52160. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52161. skeletons.push(skeleton);
  52162. loadedSkeletonsIds.push(parsedSkeleton.id);
  52163. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  52164. }
  52165. }
  52166. }
  52167. }
  52168. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52169. meshes.push(mesh);
  52170. log += "\n\tMesh " + mesh.toString(fullDetails);
  52171. }
  52172. }
  52173. // Connecting parents
  52174. var currentMesh;
  52175. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52176. currentMesh = scene.meshes[index];
  52177. if (currentMesh._waitingParentId) {
  52178. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  52179. currentMesh._waitingParentId = null;
  52180. }
  52181. }
  52182. // freeze and compute world matrix application
  52183. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52184. currentMesh = scene.meshes[index];
  52185. if (currentMesh._waitingFreezeWorldMatrix) {
  52186. currentMesh.freezeWorldMatrix();
  52187. currentMesh._waitingFreezeWorldMatrix = null;
  52188. }
  52189. else {
  52190. currentMesh.computeWorldMatrix(true);
  52191. }
  52192. }
  52193. }
  52194. // Particles
  52195. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52196. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52197. var parsedParticleSystem = parsedData.particleSystems[index];
  52198. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  52199. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  52200. }
  52201. }
  52202. }
  52203. return true;
  52204. }
  52205. catch (err) {
  52206. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  52207. if (onError) {
  52208. onError(msg, err);
  52209. }
  52210. else {
  52211. BABYLON.Tools.Log(msg);
  52212. throw err;
  52213. }
  52214. }
  52215. finally {
  52216. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52217. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52218. }
  52219. }
  52220. return false;
  52221. },
  52222. load: function (scene, data, rootUrl, onError) {
  52223. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52224. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52225. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52226. // and avoid problems with multiple concurrent .babylon loads.
  52227. var log = "importScene has failed JSON parse";
  52228. try {
  52229. var parsedData = JSON.parse(data);
  52230. log = "";
  52231. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52232. // Scene
  52233. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  52234. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  52235. }
  52236. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  52237. scene.autoClear = parsedData.autoClear;
  52238. }
  52239. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  52240. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  52241. }
  52242. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  52243. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  52244. }
  52245. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  52246. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  52247. }
  52248. // Fog
  52249. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  52250. scene.fogMode = parsedData.fogMode;
  52251. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  52252. scene.fogStart = parsedData.fogStart;
  52253. scene.fogEnd = parsedData.fogEnd;
  52254. scene.fogDensity = parsedData.fogDensity;
  52255. log += "\tFog mode for scene: ";
  52256. switch (scene.fogMode) {
  52257. // getters not compiling, so using hardcoded
  52258. case 1:
  52259. log += "exp\n";
  52260. break;
  52261. case 2:
  52262. log += "exp2\n";
  52263. break;
  52264. case 3:
  52265. log += "linear\n";
  52266. break;
  52267. }
  52268. }
  52269. //Physics
  52270. if (parsedData.physicsEnabled) {
  52271. var physicsPlugin;
  52272. if (parsedData.physicsEngine === "cannon") {
  52273. physicsPlugin = new BABYLON.CannonJSPlugin();
  52274. }
  52275. else if (parsedData.physicsEngine === "oimo") {
  52276. physicsPlugin = new BABYLON.OimoJSPlugin();
  52277. }
  52278. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  52279. //else - default engine, which is currently oimo
  52280. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  52281. scene.enablePhysics(physicsGravity, physicsPlugin);
  52282. }
  52283. // Metadata
  52284. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  52285. scene.metadata = parsedData.metadata;
  52286. }
  52287. //collisions, if defined. otherwise, default is true
  52288. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  52289. scene.collisionsEnabled = parsedData.collisionsEnabled;
  52290. }
  52291. scene.workerCollisions = !!parsedData.workerCollisions;
  52292. var index;
  52293. var cache;
  52294. // Lights
  52295. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  52296. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  52297. var parsedLight = parsedData.lights[index];
  52298. var light = BABYLON.Light.Parse(parsedLight, scene);
  52299. if (light) {
  52300. log += (index === 0 ? "\n\tLights:" : "");
  52301. log += "\n\t\t" + light.toString(fullDetails);
  52302. }
  52303. }
  52304. }
  52305. // Animations
  52306. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  52307. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  52308. var parsedAnimation = parsedData.animations[index];
  52309. var animation = BABYLON.Animation.Parse(parsedAnimation);
  52310. scene.animations.push(animation);
  52311. log += (index === 0 ? "\n\tAnimations:" : "");
  52312. log += "\n\t\t" + animation.toString(fullDetails);
  52313. }
  52314. }
  52315. if (parsedData.autoAnimate) {
  52316. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  52317. }
  52318. // Materials
  52319. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  52320. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52321. var parsedMaterial = parsedData.materials[index];
  52322. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52323. log += (index === 0 ? "\n\tMaterials:" : "");
  52324. log += "\n\t\t" + mat.toString(fullDetails);
  52325. }
  52326. }
  52327. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52328. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  52329. var parsedMultiMaterial = parsedData.multiMaterials[index];
  52330. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52331. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  52332. log += "\n\t\t" + mmat.toString(fullDetails);
  52333. }
  52334. }
  52335. // Morph targets
  52336. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  52337. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  52338. var managerData = _a[_i];
  52339. BABYLON.MorphTargetManager.Parse(managerData, scene);
  52340. }
  52341. }
  52342. // Skeletons
  52343. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52344. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  52345. var parsedSkeleton = parsedData.skeletons[index];
  52346. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52347. log += (index === 0 ? "\n\tSkeletons:" : "");
  52348. log += "\n\t\t" + skeleton.toString(fullDetails);
  52349. }
  52350. }
  52351. // Geometries
  52352. var geometries = parsedData.geometries;
  52353. if (geometries !== undefined && geometries !== null) {
  52354. // Boxes
  52355. var boxes = geometries.boxes;
  52356. if (boxes !== undefined && boxes !== null) {
  52357. for (index = 0, cache = boxes.length; index < cache; index++) {
  52358. var parsedBox = boxes[index];
  52359. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  52360. }
  52361. }
  52362. // Spheres
  52363. var spheres = geometries.spheres;
  52364. if (spheres !== undefined && spheres !== null) {
  52365. for (index = 0, cache = spheres.length; index < cache; index++) {
  52366. var parsedSphere = spheres[index];
  52367. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  52368. }
  52369. }
  52370. // Cylinders
  52371. var cylinders = geometries.cylinders;
  52372. if (cylinders !== undefined && cylinders !== null) {
  52373. for (index = 0, cache = cylinders.length; index < cache; index++) {
  52374. var parsedCylinder = cylinders[index];
  52375. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  52376. }
  52377. }
  52378. // Toruses
  52379. var toruses = geometries.toruses;
  52380. if (toruses !== undefined && toruses !== null) {
  52381. for (index = 0, cache = toruses.length; index < cache; index++) {
  52382. var parsedTorus = toruses[index];
  52383. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  52384. }
  52385. }
  52386. // Grounds
  52387. var grounds = geometries.grounds;
  52388. if (grounds !== undefined && grounds !== null) {
  52389. for (index = 0, cache = grounds.length; index < cache; index++) {
  52390. var parsedGround = grounds[index];
  52391. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  52392. }
  52393. }
  52394. // Planes
  52395. var planes = geometries.planes;
  52396. if (planes !== undefined && planes !== null) {
  52397. for (index = 0, cache = planes.length; index < cache; index++) {
  52398. var parsedPlane = planes[index];
  52399. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  52400. }
  52401. }
  52402. // TorusKnots
  52403. var torusKnots = geometries.torusKnots;
  52404. if (torusKnots !== undefined && torusKnots !== null) {
  52405. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  52406. var parsedTorusKnot = torusKnots[index];
  52407. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  52408. }
  52409. }
  52410. // VertexData
  52411. var vertexData = geometries.vertexData;
  52412. if (vertexData !== undefined && vertexData !== null) {
  52413. for (index = 0, cache = vertexData.length; index < cache; index++) {
  52414. var parsedVertexData = vertexData[index];
  52415. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  52416. }
  52417. }
  52418. }
  52419. // Meshes
  52420. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52421. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52422. var parsedMesh = parsedData.meshes[index];
  52423. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52424. log += (index === 0 ? "\n\tMeshes:" : "");
  52425. log += "\n\t\t" + mesh.toString(fullDetails);
  52426. }
  52427. }
  52428. // Cameras
  52429. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  52430. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  52431. var parsedCamera = parsedData.cameras[index];
  52432. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  52433. log += (index === 0 ? "\n\tCameras:" : "");
  52434. log += "\n\t\t" + camera.toString(fullDetails);
  52435. }
  52436. }
  52437. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  52438. scene.setActiveCameraByID(parsedData.activeCameraID);
  52439. }
  52440. // Browsing all the graph to connect the dots
  52441. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  52442. var camera = scene.cameras[index];
  52443. if (camera._waitingParentId) {
  52444. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  52445. camera._waitingParentId = null;
  52446. }
  52447. }
  52448. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52449. var light_1 = scene.lights[index];
  52450. if (light_1 && light_1._waitingParentId) {
  52451. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  52452. light_1._waitingParentId = null;
  52453. }
  52454. }
  52455. // Sounds
  52456. var loadedSounds = [];
  52457. var loadedSound;
  52458. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  52459. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  52460. var parsedSound = parsedData.sounds[index];
  52461. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52462. if (!parsedSound.url)
  52463. parsedSound.url = parsedSound.name;
  52464. if (!loadedSounds[parsedSound.url]) {
  52465. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  52466. loadedSounds[parsedSound.url] = loadedSound;
  52467. }
  52468. else {
  52469. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  52470. }
  52471. }
  52472. else {
  52473. new BABYLON.Sound(parsedSound.name, null, scene);
  52474. }
  52475. }
  52476. }
  52477. loadedSounds = [];
  52478. // Connect parents & children and parse actions
  52479. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52480. var mesh = scene.meshes[index];
  52481. if (mesh._waitingParentId) {
  52482. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  52483. mesh._waitingParentId = null;
  52484. }
  52485. if (mesh._waitingActions) {
  52486. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  52487. mesh._waitingActions = null;
  52488. }
  52489. }
  52490. // freeze world matrix application
  52491. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52492. var currentMesh = scene.meshes[index];
  52493. if (currentMesh._waitingFreezeWorldMatrix) {
  52494. currentMesh.freezeWorldMatrix();
  52495. currentMesh._waitingFreezeWorldMatrix = null;
  52496. }
  52497. else {
  52498. currentMesh.computeWorldMatrix(true);
  52499. }
  52500. }
  52501. // Particles Systems
  52502. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52503. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52504. var parsedParticleSystem = parsedData.particleSystems[index];
  52505. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  52506. }
  52507. }
  52508. // Environment texture
  52509. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  52510. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  52511. if (parsedData.createDefaultSkybox === true) {
  52512. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  52513. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  52514. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  52515. }
  52516. }
  52517. // Lens flares
  52518. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  52519. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  52520. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  52521. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  52522. }
  52523. }
  52524. // Shadows
  52525. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  52526. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  52527. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  52528. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  52529. }
  52530. }
  52531. // Lights exclusions / inclusions
  52532. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52533. var light_2 = scene.lights[index];
  52534. // Excluded check
  52535. if (light_2._excludedMeshesIds.length > 0) {
  52536. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  52537. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  52538. if (excludedMesh) {
  52539. light_2.excludedMeshes.push(excludedMesh);
  52540. }
  52541. }
  52542. light_2._excludedMeshesIds = [];
  52543. }
  52544. // Included check
  52545. if (light_2._includedOnlyMeshesIds.length > 0) {
  52546. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  52547. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  52548. if (includedOnlyMesh) {
  52549. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  52550. }
  52551. }
  52552. light_2._includedOnlyMeshesIds = [];
  52553. }
  52554. }
  52555. // Actions (scene)
  52556. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  52557. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  52558. }
  52559. // Finish
  52560. return true;
  52561. }
  52562. catch (err) {
  52563. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  52564. if (onError) {
  52565. onError(msg, err);
  52566. }
  52567. else {
  52568. BABYLON.Tools.Log(msg);
  52569. throw err;
  52570. }
  52571. }
  52572. finally {
  52573. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52574. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52575. }
  52576. }
  52577. return false;
  52578. }
  52579. });
  52580. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52581. })(BABYLON || (BABYLON = {}));
  52582. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  52583. var BABYLON;
  52584. (function (BABYLON) {
  52585. var FilesInput = /** @class */ (function () {
  52586. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  52587. this.onProcessFileCallback = function () { return true; };
  52588. this._engine = engine;
  52589. this._currentScene = scene;
  52590. this._sceneLoadedCallback = sceneLoadedCallback;
  52591. this._progressCallback = progressCallback;
  52592. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  52593. this._textureLoadingCallback = textureLoadingCallback;
  52594. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  52595. this._onReloadCallback = onReloadCallback;
  52596. this._errorCallback = errorCallback;
  52597. }
  52598. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  52599. var _this = this;
  52600. if (elementToMonitor) {
  52601. this._elementToMonitor = elementToMonitor;
  52602. this._dragEnterHandler = function (e) { _this.drag(e); };
  52603. this._dragOverHandler = function (e) { _this.drag(e); };
  52604. this._dropHandler = function (e) { _this.drop(e); };
  52605. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  52606. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  52607. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  52608. }
  52609. };
  52610. FilesInput.prototype.dispose = function () {
  52611. if (!this._elementToMonitor) {
  52612. return;
  52613. }
  52614. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  52615. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  52616. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  52617. };
  52618. FilesInput.prototype.renderFunction = function () {
  52619. if (this._additionalRenderLoopLogicCallback) {
  52620. this._additionalRenderLoopLogicCallback();
  52621. }
  52622. if (this._currentScene) {
  52623. if (this._textureLoadingCallback) {
  52624. var remaining = this._currentScene.getWaitingItemsCount();
  52625. if (remaining > 0) {
  52626. this._textureLoadingCallback(remaining);
  52627. }
  52628. }
  52629. this._currentScene.render();
  52630. }
  52631. };
  52632. FilesInput.prototype.drag = function (e) {
  52633. e.stopPropagation();
  52634. e.preventDefault();
  52635. };
  52636. FilesInput.prototype.drop = function (eventDrop) {
  52637. eventDrop.stopPropagation();
  52638. eventDrop.preventDefault();
  52639. this.loadFiles(eventDrop);
  52640. };
  52641. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  52642. var _this = this;
  52643. var reader = folder.createReader();
  52644. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  52645. reader.readEntries(function (entries) {
  52646. remaining.count += entries.length;
  52647. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  52648. var entry = entries_1[_i];
  52649. if (entry.isFile) {
  52650. entry.file(function (file) {
  52651. file.correctName = relativePath + file.name;
  52652. files.push(file);
  52653. if (--remaining.count === 0) {
  52654. callback();
  52655. }
  52656. });
  52657. }
  52658. else if (entry.isDirectory) {
  52659. _this._traverseFolder(entry, files, remaining, callback);
  52660. }
  52661. }
  52662. if (--remaining.count) {
  52663. callback();
  52664. }
  52665. });
  52666. };
  52667. FilesInput.prototype._processFiles = function (files) {
  52668. var skippedFiles = 0;
  52669. for (var i = 0; i < files.length; i++) {
  52670. var name = files[i].correctName.toLowerCase();
  52671. var extension = name.split('.').pop();
  52672. if (!this.onProcessFileCallback(files[i], name, extension)) {
  52673. skippedFiles++;
  52674. continue;
  52675. }
  52676. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  52677. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  52678. this._sceneFileToLoad = files[i];
  52679. }
  52680. else {
  52681. FilesInput.FilesToLoad[name] = files[i];
  52682. }
  52683. }
  52684. if (this._onReloadCallback) {
  52685. this._onReloadCallback(this._sceneFileToLoad);
  52686. }
  52687. else if (skippedFiles < files.length) {
  52688. this.reload();
  52689. }
  52690. };
  52691. FilesInput.prototype.loadFiles = function (event) {
  52692. var _this = this;
  52693. if (this._startingProcessingFilesCallback)
  52694. this._startingProcessingFilesCallback();
  52695. // Handling data transfer via drag'n'drop
  52696. if (event && event.dataTransfer && event.dataTransfer.files) {
  52697. this._filesToLoad = event.dataTransfer.files;
  52698. }
  52699. // Handling files from input files
  52700. if (event && event.target && event.target.files) {
  52701. this._filesToLoad = event.target.files;
  52702. }
  52703. if (this._filesToLoad && this._filesToLoad.length > 0) {
  52704. var files_1 = new Array();
  52705. var folders = [];
  52706. var items = event.dataTransfer ? event.dataTransfer.items : null;
  52707. for (var i = 0; i < this._filesToLoad.length; i++) {
  52708. var fileToLoad = this._filesToLoad[i];
  52709. var name_1 = fileToLoad.name.toLowerCase();
  52710. var entry = void 0;
  52711. fileToLoad.correctName = name_1;
  52712. if (items) {
  52713. var item = items[i];
  52714. if (item.getAsEntry) {
  52715. entry = item.getAsEntry();
  52716. }
  52717. else if (item.webkitGetAsEntry) {
  52718. entry = item.webkitGetAsEntry();
  52719. }
  52720. }
  52721. if (!entry) {
  52722. files_1.push(fileToLoad);
  52723. }
  52724. else {
  52725. if (entry.isDirectory) {
  52726. folders.push(entry);
  52727. }
  52728. else {
  52729. files_1.push(fileToLoad);
  52730. }
  52731. }
  52732. }
  52733. if (folders.length === 0) {
  52734. this._processFiles(files_1);
  52735. }
  52736. else {
  52737. var remaining = { count: folders.length };
  52738. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  52739. var folder = folders_1[_i];
  52740. this._traverseFolder(folder, files_1, remaining, function () {
  52741. _this._processFiles(files_1);
  52742. });
  52743. }
  52744. }
  52745. }
  52746. };
  52747. FilesInput.prototype.reload = function () {
  52748. var _this = this;
  52749. // If a ".babylon" file has been provided
  52750. if (this._sceneFileToLoad) {
  52751. if (this._currentScene) {
  52752. if (BABYLON.Tools.errorsCount > 0) {
  52753. BABYLON.Tools.ClearLogCache();
  52754. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  52755. }
  52756. this._engine.stopRenderLoop();
  52757. this._currentScene.dispose();
  52758. }
  52759. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  52760. _this._currentScene = newScene;
  52761. if (_this._sceneLoadedCallback) {
  52762. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  52763. }
  52764. // Wait for textures and shaders to be ready
  52765. _this._currentScene.executeWhenReady(function () {
  52766. _this._engine.runRenderLoop(function () {
  52767. _this.renderFunction();
  52768. });
  52769. });
  52770. }, function (progress) {
  52771. if (_this._progressCallback) {
  52772. _this._progressCallback(progress);
  52773. }
  52774. }, function (scene, message) {
  52775. _this._currentScene = scene;
  52776. if (_this._errorCallback) {
  52777. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  52778. }
  52779. });
  52780. }
  52781. else {
  52782. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  52783. }
  52784. };
  52785. FilesInput.FilesToLoad = {};
  52786. return FilesInput;
  52787. }());
  52788. BABYLON.FilesInput = FilesInput;
  52789. })(BABYLON || (BABYLON = {}));
  52790. //# sourceMappingURL=babylon.filesInput.js.map
  52791. var BABYLON;
  52792. (function (BABYLON) {
  52793. /**
  52794. * This class implement a typical dictionary using a string as key and the generic type T as value.
  52795. * The underlying implementation relies on an associative array to ensure the best performances.
  52796. * The value can be anything including 'null' but except 'undefined'
  52797. */
  52798. var StringDictionary = /** @class */ (function () {
  52799. function StringDictionary() {
  52800. this._count = 0;
  52801. this._data = {};
  52802. }
  52803. /**
  52804. * This will clear this dictionary and copy the content from the 'source' one.
  52805. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  52806. * @param source the dictionary to take the content from and copy to this dictionary
  52807. */
  52808. StringDictionary.prototype.copyFrom = function (source) {
  52809. var _this = this;
  52810. this.clear();
  52811. source.forEach(function (t, v) { return _this.add(t, v); });
  52812. };
  52813. /**
  52814. * Get a value based from its key
  52815. * @param key the given key to get the matching value from
  52816. * @return the value if found, otherwise undefined is returned
  52817. */
  52818. StringDictionary.prototype.get = function (key) {
  52819. var val = this._data[key];
  52820. if (val !== undefined) {
  52821. return val;
  52822. }
  52823. return undefined;
  52824. };
  52825. /**
  52826. * Get a value from its key or add it if it doesn't exist.
  52827. * This method will ensure you that a given key/data will be present in the dictionary.
  52828. * @param key the given key to get the matching value from
  52829. * @param factory the factory that will create the value if the key is not present in the dictionary.
  52830. * The factory will only be invoked if there's no data for the given key.
  52831. * @return the value corresponding to the key.
  52832. */
  52833. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  52834. var val = this.get(key);
  52835. if (val !== undefined) {
  52836. return val;
  52837. }
  52838. val = factory(key);
  52839. if (val) {
  52840. this.add(key, val);
  52841. }
  52842. return val;
  52843. };
  52844. /**
  52845. * Get a value from its key if present in the dictionary otherwise add it
  52846. * @param key the key to get the value from
  52847. * @param val if there's no such key/value pair in the dictionary add it with this value
  52848. * @return the value corresponding to the key
  52849. */
  52850. StringDictionary.prototype.getOrAdd = function (key, val) {
  52851. var curVal = this.get(key);
  52852. if (curVal !== undefined) {
  52853. return curVal;
  52854. }
  52855. this.add(key, val);
  52856. return val;
  52857. };
  52858. /**
  52859. * Check if there's a given key in the dictionary
  52860. * @param key the key to check for
  52861. * @return true if the key is present, false otherwise
  52862. */
  52863. StringDictionary.prototype.contains = function (key) {
  52864. return this._data[key] !== undefined;
  52865. };
  52866. /**
  52867. * Add a new key and its corresponding value
  52868. * @param key the key to add
  52869. * @param value the value corresponding to the key
  52870. * @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
  52871. */
  52872. StringDictionary.prototype.add = function (key, value) {
  52873. if (this._data[key] !== undefined) {
  52874. return false;
  52875. }
  52876. this._data[key] = value;
  52877. ++this._count;
  52878. return true;
  52879. };
  52880. StringDictionary.prototype.set = function (key, value) {
  52881. if (this._data[key] === undefined) {
  52882. return false;
  52883. }
  52884. this._data[key] = value;
  52885. return true;
  52886. };
  52887. /**
  52888. * Get the element of the given key and remove it from the dictionary
  52889. * @param key
  52890. */
  52891. StringDictionary.prototype.getAndRemove = function (key) {
  52892. var val = this.get(key);
  52893. if (val !== undefined) {
  52894. delete this._data[key];
  52895. --this._count;
  52896. return val;
  52897. }
  52898. return null;
  52899. };
  52900. /**
  52901. * Remove a key/value from the dictionary.
  52902. * @param key the key to remove
  52903. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  52904. */
  52905. StringDictionary.prototype.remove = function (key) {
  52906. if (this.contains(key)) {
  52907. delete this._data[key];
  52908. --this._count;
  52909. return true;
  52910. }
  52911. return false;
  52912. };
  52913. /**
  52914. * Clear the whole content of the dictionary
  52915. */
  52916. StringDictionary.prototype.clear = function () {
  52917. this._data = {};
  52918. this._count = 0;
  52919. };
  52920. Object.defineProperty(StringDictionary.prototype, "count", {
  52921. get: function () {
  52922. return this._count;
  52923. },
  52924. enumerable: true,
  52925. configurable: true
  52926. });
  52927. /**
  52928. * Execute a callback on each key/val of the dictionary.
  52929. * Note that you can remove any element in this dictionary in the callback implementation
  52930. * @param callback the callback to execute on a given key/value pair
  52931. */
  52932. StringDictionary.prototype.forEach = function (callback) {
  52933. for (var cur in this._data) {
  52934. var val = this._data[cur];
  52935. callback(cur, val);
  52936. }
  52937. };
  52938. /**
  52939. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  52940. * If the callback returns null or undefined the method will iterate to the next key/value pair
  52941. * Note that you can remove any element in this dictionary in the callback implementation
  52942. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  52943. */
  52944. StringDictionary.prototype.first = function (callback) {
  52945. for (var cur in this._data) {
  52946. var val = this._data[cur];
  52947. var res = callback(cur, val);
  52948. if (res) {
  52949. return res;
  52950. }
  52951. }
  52952. return null;
  52953. };
  52954. return StringDictionary;
  52955. }());
  52956. BABYLON.StringDictionary = StringDictionary;
  52957. })(BABYLON || (BABYLON = {}));
  52958. //# sourceMappingURL=babylon.stringDictionary.js.map
  52959. var BABYLON;
  52960. (function (BABYLON) {
  52961. var Tags = /** @class */ (function () {
  52962. function Tags() {
  52963. }
  52964. Tags.EnableFor = function (obj) {
  52965. obj._tags = obj._tags || {};
  52966. obj.hasTags = function () {
  52967. return Tags.HasTags(obj);
  52968. };
  52969. obj.addTags = function (tagsString) {
  52970. return Tags.AddTagsTo(obj, tagsString);
  52971. };
  52972. obj.removeTags = function (tagsString) {
  52973. return Tags.RemoveTagsFrom(obj, tagsString);
  52974. };
  52975. obj.matchesTagsQuery = function (tagsQuery) {
  52976. return Tags.MatchesQuery(obj, tagsQuery);
  52977. };
  52978. };
  52979. Tags.DisableFor = function (obj) {
  52980. delete obj._tags;
  52981. delete obj.hasTags;
  52982. delete obj.addTags;
  52983. delete obj.removeTags;
  52984. delete obj.matchesTagsQuery;
  52985. };
  52986. Tags.HasTags = function (obj) {
  52987. if (!obj._tags) {
  52988. return false;
  52989. }
  52990. return !BABYLON.Tools.IsEmpty(obj._tags);
  52991. };
  52992. Tags.GetTags = function (obj, asString) {
  52993. if (asString === void 0) { asString = true; }
  52994. if (!obj._tags) {
  52995. return null;
  52996. }
  52997. if (asString) {
  52998. var tagsArray = [];
  52999. for (var tag in obj._tags) {
  53000. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53001. tagsArray.push(tag);
  53002. }
  53003. }
  53004. return tagsArray.join(" ");
  53005. }
  53006. else {
  53007. return obj._tags;
  53008. }
  53009. };
  53010. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53011. // a tag cannot start with '||', '&&', and '!'
  53012. // it cannot contain whitespaces
  53013. Tags.AddTagsTo = function (obj, tagsString) {
  53014. if (!tagsString) {
  53015. return;
  53016. }
  53017. if (typeof tagsString !== "string") {
  53018. return;
  53019. }
  53020. var tags = tagsString.split(" ");
  53021. tags.forEach(function (tag, index, array) {
  53022. Tags._AddTagTo(obj, tag);
  53023. });
  53024. };
  53025. Tags._AddTagTo = function (obj, tag) {
  53026. tag = tag.trim();
  53027. if (tag === "" || tag === "true" || tag === "false") {
  53028. return;
  53029. }
  53030. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53031. return;
  53032. }
  53033. Tags.EnableFor(obj);
  53034. obj._tags[tag] = true;
  53035. };
  53036. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53037. if (!Tags.HasTags(obj)) {
  53038. return;
  53039. }
  53040. var tags = tagsString.split(" ");
  53041. for (var t in tags) {
  53042. Tags._RemoveTagFrom(obj, tags[t]);
  53043. }
  53044. };
  53045. Tags._RemoveTagFrom = function (obj, tag) {
  53046. delete obj._tags[tag];
  53047. };
  53048. Tags.MatchesQuery = function (obj, tagsQuery) {
  53049. if (tagsQuery === undefined) {
  53050. return true;
  53051. }
  53052. if (tagsQuery === "") {
  53053. return Tags.HasTags(obj);
  53054. }
  53055. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53056. };
  53057. return Tags;
  53058. }());
  53059. BABYLON.Tags = Tags;
  53060. })(BABYLON || (BABYLON = {}));
  53061. //# sourceMappingURL=babylon.tags.js.map
  53062. var BABYLON;
  53063. (function (BABYLON) {
  53064. var Internals;
  53065. (function (Internals) {
  53066. var AndOrNotEvaluator = /** @class */ (function () {
  53067. function AndOrNotEvaluator() {
  53068. }
  53069. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  53070. if (!query.match(/\([^\(\)]*\)/g)) {
  53071. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  53072. }
  53073. else {
  53074. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  53075. // remove parenthesis
  53076. r = r.slice(1, r.length - 1);
  53077. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  53078. });
  53079. }
  53080. if (query === "true") {
  53081. return true;
  53082. }
  53083. if (query === "false") {
  53084. return false;
  53085. }
  53086. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  53087. };
  53088. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  53089. evaluateCallback = evaluateCallback || (function (r) {
  53090. return r === "true" ? true : false;
  53091. });
  53092. var result;
  53093. var or = parenthesisContent.split("||");
  53094. for (var i in or) {
  53095. if (or.hasOwnProperty(i)) {
  53096. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  53097. var and = ori.split("&&");
  53098. if (and.length > 1) {
  53099. for (var j = 0; j < and.length; ++j) {
  53100. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  53101. if (andj !== "true" && andj !== "false") {
  53102. if (andj[0] === "!") {
  53103. result = !evaluateCallback(andj.substring(1));
  53104. }
  53105. else {
  53106. result = evaluateCallback(andj);
  53107. }
  53108. }
  53109. else {
  53110. result = andj === "true" ? true : false;
  53111. }
  53112. if (!result) {
  53113. ori = "false";
  53114. break;
  53115. }
  53116. }
  53117. }
  53118. if (result || ori === "true") {
  53119. result = true;
  53120. break;
  53121. }
  53122. // result equals false (or undefined)
  53123. if (ori !== "true" && ori !== "false") {
  53124. if (ori[0] === "!") {
  53125. result = !evaluateCallback(ori.substring(1));
  53126. }
  53127. else {
  53128. result = evaluateCallback(ori);
  53129. }
  53130. }
  53131. else {
  53132. result = ori === "true" ? true : false;
  53133. }
  53134. }
  53135. }
  53136. // the whole parenthesis scope is replaced by 'true' or 'false'
  53137. return result ? "true" : "false";
  53138. };
  53139. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  53140. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  53141. // remove whitespaces
  53142. r = r.replace(/[\s]/g, function () { return ""; });
  53143. return r.length % 2 ? "!" : "";
  53144. });
  53145. booleanString = booleanString.trim();
  53146. if (booleanString === "!true") {
  53147. booleanString = "false";
  53148. }
  53149. else if (booleanString === "!false") {
  53150. booleanString = "true";
  53151. }
  53152. return booleanString;
  53153. };
  53154. return AndOrNotEvaluator;
  53155. }());
  53156. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  53157. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53158. })(BABYLON || (BABYLON = {}));
  53159. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  53160. var BABYLON;
  53161. (function (BABYLON) {
  53162. var Database = /** @class */ (function () {
  53163. function Database(urlToScene, callbackManifestChecked) {
  53164. // Handling various flavors of prefixed version of IndexedDB
  53165. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  53166. this.callbackManifestChecked = callbackManifestChecked;
  53167. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  53168. this.db = null;
  53169. this._enableSceneOffline = false;
  53170. this._enableTexturesOffline = false;
  53171. this.manifestVersionFound = 0;
  53172. this.mustUpdateRessources = false;
  53173. this.hasReachedQuota = false;
  53174. if (!Database.IDBStorageEnabled) {
  53175. this.callbackManifestChecked(true);
  53176. }
  53177. else {
  53178. this.checkManifestFile();
  53179. }
  53180. }
  53181. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  53182. get: function () {
  53183. return this._enableSceneOffline;
  53184. },
  53185. enumerable: true,
  53186. configurable: true
  53187. });
  53188. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  53189. get: function () {
  53190. return this._enableTexturesOffline;
  53191. },
  53192. enumerable: true,
  53193. configurable: true
  53194. });
  53195. Database.prototype.checkManifestFile = function () {
  53196. var _this = this;
  53197. var noManifestFile = function () {
  53198. _this._enableSceneOffline = false;
  53199. _this._enableTexturesOffline = false;
  53200. _this.callbackManifestChecked(false);
  53201. };
  53202. var timeStampUsed = false;
  53203. var manifestURL = this.currentSceneUrl + ".manifest";
  53204. var xhr = new XMLHttpRequest();
  53205. if (navigator.onLine) {
  53206. // Adding a timestamp to by-pass browsers' cache
  53207. timeStampUsed = true;
  53208. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  53209. }
  53210. xhr.open("GET", manifestURL, true);
  53211. xhr.addEventListener("load", function () {
  53212. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53213. try {
  53214. var manifestFile = JSON.parse(xhr.response);
  53215. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  53216. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  53217. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  53218. _this.manifestVersionFound = manifestFile.version;
  53219. }
  53220. if (_this.callbackManifestChecked) {
  53221. _this.callbackManifestChecked(true);
  53222. }
  53223. }
  53224. catch (ex) {
  53225. noManifestFile();
  53226. }
  53227. }
  53228. else {
  53229. noManifestFile();
  53230. }
  53231. }, false);
  53232. xhr.addEventListener("error", function (event) {
  53233. if (timeStampUsed) {
  53234. timeStampUsed = false;
  53235. // Let's retry without the timeStamp
  53236. // It could fail when coupled with HTML5 Offline API
  53237. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  53238. xhr.open("GET", retryManifestURL, true);
  53239. xhr.send();
  53240. }
  53241. else {
  53242. noManifestFile();
  53243. }
  53244. }, false);
  53245. try {
  53246. xhr.send();
  53247. }
  53248. catch (ex) {
  53249. BABYLON.Tools.Error("Error on XHR send request.");
  53250. this.callbackManifestChecked(false);
  53251. }
  53252. };
  53253. Database.prototype.openAsync = function (successCallback, errorCallback) {
  53254. var _this = this;
  53255. var handleError = function () {
  53256. _this.isSupported = false;
  53257. if (errorCallback)
  53258. errorCallback();
  53259. };
  53260. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  53261. // Your browser doesn't support IndexedDB
  53262. this.isSupported = false;
  53263. if (errorCallback)
  53264. errorCallback();
  53265. }
  53266. else {
  53267. // If the DB hasn't been opened or created yet
  53268. if (!this.db) {
  53269. this.hasReachedQuota = false;
  53270. this.isSupported = true;
  53271. var request = this.idbFactory.open("babylonjs", 1);
  53272. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  53273. request.onerror = function (event) {
  53274. handleError();
  53275. };
  53276. // executes when a version change transaction cannot complete due to other active transactions
  53277. request.onblocked = function (event) {
  53278. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  53279. handleError();
  53280. };
  53281. // DB has been opened successfully
  53282. request.onsuccess = function (event) {
  53283. _this.db = request.result;
  53284. successCallback();
  53285. };
  53286. // Initialization of the DB. Creating Scenes & Textures stores
  53287. request.onupgradeneeded = function (event) {
  53288. _this.db = (event.target).result;
  53289. if (_this.db) {
  53290. try {
  53291. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  53292. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  53293. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  53294. }
  53295. catch (ex) {
  53296. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  53297. handleError();
  53298. }
  53299. }
  53300. };
  53301. }
  53302. else {
  53303. if (successCallback)
  53304. successCallback();
  53305. }
  53306. }
  53307. };
  53308. Database.prototype.loadImageFromDB = function (url, image) {
  53309. var _this = this;
  53310. var completeURL = Database.ReturnFullUrlLocation(url);
  53311. var saveAndLoadImage = function () {
  53312. if (!_this.hasReachedQuota && _this.db !== null) {
  53313. // the texture is not yet in the DB, let's try to save it
  53314. _this._saveImageIntoDBAsync(completeURL, image);
  53315. }
  53316. else {
  53317. image.src = url;
  53318. }
  53319. };
  53320. if (!this.mustUpdateRessources) {
  53321. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  53322. }
  53323. else {
  53324. saveAndLoadImage();
  53325. }
  53326. };
  53327. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  53328. if (this.isSupported && this.db !== null) {
  53329. var texture;
  53330. var transaction = this.db.transaction(["textures"]);
  53331. transaction.onabort = function (event) {
  53332. image.src = url;
  53333. };
  53334. transaction.oncomplete = function (event) {
  53335. var blobTextureURL;
  53336. if (texture) {
  53337. var URL = window.URL || window.webkitURL;
  53338. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  53339. image.onerror = function () {
  53340. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  53341. image.src = url;
  53342. };
  53343. image.src = blobTextureURL;
  53344. }
  53345. else {
  53346. notInDBCallback();
  53347. }
  53348. };
  53349. var getRequest = transaction.objectStore("textures").get(url);
  53350. getRequest.onsuccess = function (event) {
  53351. texture = (event.target).result;
  53352. };
  53353. getRequest.onerror = function (event) {
  53354. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  53355. image.src = url;
  53356. };
  53357. }
  53358. else {
  53359. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53360. image.src = url;
  53361. }
  53362. };
  53363. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  53364. var _this = this;
  53365. if (this.isSupported) {
  53366. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  53367. var generateBlobUrl = function () {
  53368. var blobTextureURL;
  53369. if (blob) {
  53370. var URL = window.URL || window.webkitURL;
  53371. try {
  53372. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  53373. }
  53374. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  53375. catch (ex) {
  53376. blobTextureURL = URL.createObjectURL(blob);
  53377. }
  53378. }
  53379. if (blobTextureURL) {
  53380. image.src = blobTextureURL;
  53381. }
  53382. };
  53383. if (Database.IsUASupportingBlobStorage) {
  53384. var xhr = new XMLHttpRequest(), blob;
  53385. xhr.open("GET", url, true);
  53386. xhr.responseType = "blob";
  53387. xhr.addEventListener("load", function () {
  53388. if (xhr.status === 200 && _this.db) {
  53389. // Blob as response (XHR2)
  53390. blob = xhr.response;
  53391. var transaction = _this.db.transaction(["textures"], "readwrite");
  53392. // the transaction could abort because of a QuotaExceededError error
  53393. transaction.onabort = function (event) {
  53394. try {
  53395. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53396. var srcElement = (event.srcElement || event.target);
  53397. var error = srcElement.error;
  53398. if (error && error.name === "QuotaExceededError") {
  53399. _this.hasReachedQuota = true;
  53400. }
  53401. }
  53402. catch (ex) { }
  53403. generateBlobUrl();
  53404. };
  53405. transaction.oncomplete = function (event) {
  53406. generateBlobUrl();
  53407. };
  53408. var newTexture = { textureUrl: url, data: blob };
  53409. try {
  53410. // Put the blob into the dabase
  53411. var addRequest = transaction.objectStore("textures").put(newTexture);
  53412. addRequest.onsuccess = function (event) {
  53413. };
  53414. addRequest.onerror = function (event) {
  53415. generateBlobUrl();
  53416. };
  53417. }
  53418. catch (ex) {
  53419. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  53420. if (ex.code === 25) {
  53421. Database.IsUASupportingBlobStorage = false;
  53422. }
  53423. image.src = url;
  53424. }
  53425. }
  53426. else {
  53427. image.src = url;
  53428. }
  53429. }, false);
  53430. xhr.addEventListener("error", function (event) {
  53431. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  53432. image.src = url;
  53433. }, false);
  53434. xhr.send();
  53435. }
  53436. else {
  53437. image.src = url;
  53438. }
  53439. }
  53440. else {
  53441. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53442. image.src = url;
  53443. }
  53444. };
  53445. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  53446. var _this = this;
  53447. var updateVersion = function () {
  53448. // the version is not yet in the DB or we need to update it
  53449. _this._saveVersionIntoDBAsync(url, versionLoaded);
  53450. };
  53451. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  53452. };
  53453. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  53454. var _this = this;
  53455. if (this.isSupported && this.db) {
  53456. var version;
  53457. try {
  53458. var transaction = this.db.transaction(["versions"]);
  53459. transaction.oncomplete = function (event) {
  53460. if (version) {
  53461. // If the version in the JSON file is > than the version in DB
  53462. if (_this.manifestVersionFound > version.data) {
  53463. _this.mustUpdateRessources = true;
  53464. updateInDBCallback();
  53465. }
  53466. else {
  53467. callback(version.data);
  53468. }
  53469. }
  53470. else {
  53471. _this.mustUpdateRessources = true;
  53472. updateInDBCallback();
  53473. }
  53474. };
  53475. transaction.onabort = function (event) {
  53476. callback(-1);
  53477. };
  53478. var getRequest = transaction.objectStore("versions").get(url);
  53479. getRequest.onsuccess = function (event) {
  53480. version = (event.target).result;
  53481. };
  53482. getRequest.onerror = function (event) {
  53483. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  53484. callback(-1);
  53485. };
  53486. }
  53487. catch (ex) {
  53488. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  53489. callback(-1);
  53490. }
  53491. }
  53492. else {
  53493. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53494. callback(-1);
  53495. }
  53496. };
  53497. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  53498. var _this = this;
  53499. if (this.isSupported && !this.hasReachedQuota && this.db) {
  53500. try {
  53501. // Open a transaction to the database
  53502. var transaction = this.db.transaction(["versions"], "readwrite");
  53503. // the transaction could abort because of a QuotaExceededError error
  53504. transaction.onabort = function (event) {
  53505. try {
  53506. var error = event.srcElement['error'];
  53507. if (error && error.name === "QuotaExceededError") {
  53508. _this.hasReachedQuota = true;
  53509. }
  53510. }
  53511. catch (ex) { }
  53512. callback(-1);
  53513. };
  53514. transaction.oncomplete = function (event) {
  53515. callback(_this.manifestVersionFound);
  53516. };
  53517. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  53518. // Put the scene into the database
  53519. var addRequest = transaction.objectStore("versions").put(newVersion);
  53520. addRequest.onsuccess = function (event) {
  53521. };
  53522. addRequest.onerror = function (event) {
  53523. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  53524. };
  53525. }
  53526. catch (ex) {
  53527. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  53528. callback(-1);
  53529. }
  53530. }
  53531. else {
  53532. callback(-1);
  53533. }
  53534. };
  53535. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  53536. var _this = this;
  53537. var completeUrl = Database.ReturnFullUrlLocation(url);
  53538. var saveAndLoadFile = function () {
  53539. // the scene is not yet in the DB, let's try to save it
  53540. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  53541. };
  53542. this._checkVersionFromDB(completeUrl, function (version) {
  53543. if (version !== -1) {
  53544. if (!_this.mustUpdateRessources) {
  53545. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  53546. }
  53547. else {
  53548. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  53549. }
  53550. }
  53551. else {
  53552. if (errorCallback) {
  53553. errorCallback();
  53554. }
  53555. }
  53556. });
  53557. };
  53558. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  53559. if (this.isSupported && this.db) {
  53560. var targetStore;
  53561. if (url.indexOf(".babylon") !== -1) {
  53562. targetStore = "scenes";
  53563. }
  53564. else {
  53565. targetStore = "textures";
  53566. }
  53567. var file;
  53568. var transaction = this.db.transaction([targetStore]);
  53569. transaction.oncomplete = function (event) {
  53570. if (file) {
  53571. callback(file.data);
  53572. }
  53573. else {
  53574. notInDBCallback();
  53575. }
  53576. };
  53577. transaction.onabort = function (event) {
  53578. notInDBCallback();
  53579. };
  53580. var getRequest = transaction.objectStore(targetStore).get(url);
  53581. getRequest.onsuccess = function (event) {
  53582. file = (event.target).result;
  53583. };
  53584. getRequest.onerror = function (event) {
  53585. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  53586. notInDBCallback();
  53587. };
  53588. }
  53589. else {
  53590. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53591. callback();
  53592. }
  53593. };
  53594. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  53595. var _this = this;
  53596. if (this.isSupported) {
  53597. var targetStore;
  53598. if (url.indexOf(".babylon") !== -1) {
  53599. targetStore = "scenes";
  53600. }
  53601. else {
  53602. targetStore = "textures";
  53603. }
  53604. // Create XHR
  53605. var xhr = new XMLHttpRequest();
  53606. var fileData;
  53607. xhr.open("GET", url, true);
  53608. if (useArrayBuffer) {
  53609. xhr.responseType = "arraybuffer";
  53610. }
  53611. if (progressCallback) {
  53612. xhr.onprogress = progressCallback;
  53613. }
  53614. xhr.addEventListener("load", function () {
  53615. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  53616. // Blob as response (XHR2)
  53617. //fileData = xhr.responseText;
  53618. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  53619. if (!_this.hasReachedQuota && _this.db) {
  53620. // Open a transaction to the database
  53621. var transaction = _this.db.transaction([targetStore], "readwrite");
  53622. // the transaction could abort because of a QuotaExceededError error
  53623. transaction.onabort = function (event) {
  53624. try {
  53625. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53626. var error = event.srcElement['error'];
  53627. if (error && error.name === "QuotaExceededError") {
  53628. _this.hasReachedQuota = true;
  53629. }
  53630. }
  53631. catch (ex) { }
  53632. callback(fileData);
  53633. };
  53634. transaction.oncomplete = function (event) {
  53635. callback(fileData);
  53636. };
  53637. var newFile;
  53638. if (targetStore === "scenes") {
  53639. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  53640. }
  53641. else {
  53642. newFile = { textureUrl: url, data: fileData };
  53643. }
  53644. try {
  53645. // Put the scene into the database
  53646. var addRequest = transaction.objectStore(targetStore).put(newFile);
  53647. addRequest.onsuccess = function (event) {
  53648. };
  53649. addRequest.onerror = function (event) {
  53650. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  53651. };
  53652. }
  53653. catch (ex) {
  53654. callback(fileData);
  53655. }
  53656. }
  53657. else {
  53658. callback(fileData);
  53659. }
  53660. }
  53661. else {
  53662. callback();
  53663. }
  53664. }, false);
  53665. xhr.addEventListener("error", function (event) {
  53666. BABYLON.Tools.Error("error on XHR request.");
  53667. callback();
  53668. }, false);
  53669. xhr.send();
  53670. }
  53671. else {
  53672. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53673. callback();
  53674. }
  53675. };
  53676. Database.IsUASupportingBlobStorage = true;
  53677. Database.IDBStorageEnabled = true;
  53678. Database.parseURL = function (url) {
  53679. var a = document.createElement('a');
  53680. a.href = url;
  53681. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  53682. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  53683. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  53684. return absLocation;
  53685. };
  53686. Database.ReturnFullUrlLocation = function (url) {
  53687. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  53688. return (Database.parseURL(window.location.href) + url);
  53689. }
  53690. else {
  53691. return url;
  53692. }
  53693. };
  53694. return Database;
  53695. }());
  53696. BABYLON.Database = Database;
  53697. })(BABYLON || (BABYLON = {}));
  53698. //# sourceMappingURL=babylon.database.js.map
  53699. var BABYLON;
  53700. (function (BABYLON) {
  53701. var FresnelParameters = /** @class */ (function () {
  53702. function FresnelParameters() {
  53703. this._isEnabled = true;
  53704. this.leftColor = BABYLON.Color3.White();
  53705. this.rightColor = BABYLON.Color3.Black();
  53706. this.bias = 0;
  53707. this.power = 1;
  53708. }
  53709. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  53710. get: function () {
  53711. return this._isEnabled;
  53712. },
  53713. set: function (value) {
  53714. if (this._isEnabled === value) {
  53715. return;
  53716. }
  53717. this._isEnabled = value;
  53718. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  53719. },
  53720. enumerable: true,
  53721. configurable: true
  53722. });
  53723. FresnelParameters.prototype.clone = function () {
  53724. var newFresnelParameters = new FresnelParameters();
  53725. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  53726. return newFresnelParameters;
  53727. };
  53728. FresnelParameters.prototype.serialize = function () {
  53729. var serializationObject = {};
  53730. serializationObject.isEnabled = this.isEnabled;
  53731. serializationObject.leftColor = this.leftColor;
  53732. serializationObject.rightColor = this.rightColor;
  53733. serializationObject.bias = this.bias;
  53734. serializationObject.power = this.power;
  53735. return serializationObject;
  53736. };
  53737. FresnelParameters.Parse = function (parsedFresnelParameters) {
  53738. var fresnelParameters = new FresnelParameters();
  53739. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  53740. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  53741. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  53742. fresnelParameters.bias = parsedFresnelParameters.bias;
  53743. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  53744. return fresnelParameters;
  53745. };
  53746. return FresnelParameters;
  53747. }());
  53748. BABYLON.FresnelParameters = FresnelParameters;
  53749. })(BABYLON || (BABYLON = {}));
  53750. //# sourceMappingURL=babylon.fresnelParameters.js.map
  53751. var BABYLON;
  53752. (function (BABYLON) {
  53753. var MultiMaterial = /** @class */ (function (_super) {
  53754. __extends(MultiMaterial, _super);
  53755. function MultiMaterial(name, scene) {
  53756. var _this = _super.call(this, name, scene, true) || this;
  53757. scene.multiMaterials.push(_this);
  53758. _this.subMaterials = new Array();
  53759. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  53760. return _this;
  53761. }
  53762. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  53763. get: function () {
  53764. return this._subMaterials;
  53765. },
  53766. set: function (value) {
  53767. this._subMaterials = value;
  53768. this._hookArray(value);
  53769. },
  53770. enumerable: true,
  53771. configurable: true
  53772. });
  53773. MultiMaterial.prototype._hookArray = function (array) {
  53774. var _this = this;
  53775. var oldPush = array.push;
  53776. array.push = function () {
  53777. var items = [];
  53778. for (var _i = 0; _i < arguments.length; _i++) {
  53779. items[_i] = arguments[_i];
  53780. }
  53781. var result = oldPush.apply(array, items);
  53782. _this._markAllSubMeshesAsTexturesDirty();
  53783. return result;
  53784. };
  53785. var oldSplice = array.splice;
  53786. array.splice = function (index, deleteCount) {
  53787. var deleted = oldSplice.apply(array, [index, deleteCount]);
  53788. _this._markAllSubMeshesAsTexturesDirty();
  53789. return deleted;
  53790. };
  53791. };
  53792. // Properties
  53793. MultiMaterial.prototype.getSubMaterial = function (index) {
  53794. if (index < 0 || index >= this.subMaterials.length) {
  53795. return this.getScene().defaultMaterial;
  53796. }
  53797. return this.subMaterials[index];
  53798. };
  53799. MultiMaterial.prototype.getActiveTextures = function () {
  53800. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  53801. if (subMaterial) {
  53802. return subMaterial.getActiveTextures();
  53803. }
  53804. else {
  53805. return [];
  53806. }
  53807. }));
  53808. var _a;
  53809. };
  53810. // Methods
  53811. MultiMaterial.prototype.getClassName = function () {
  53812. return "MultiMaterial";
  53813. };
  53814. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  53815. for (var index = 0; index < this.subMaterials.length; index++) {
  53816. var subMaterial = this.subMaterials[index];
  53817. if (subMaterial) {
  53818. if (subMaterial.storeEffectOnSubMeshes) {
  53819. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  53820. return false;
  53821. }
  53822. continue;
  53823. }
  53824. if (!subMaterial.isReady(mesh)) {
  53825. return false;
  53826. }
  53827. }
  53828. }
  53829. return true;
  53830. };
  53831. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  53832. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  53833. for (var index = 0; index < this.subMaterials.length; index++) {
  53834. var subMaterial = null;
  53835. var current = this.subMaterials[index];
  53836. if (cloneChildren && current) {
  53837. subMaterial = current.clone(name + "-" + current.name);
  53838. }
  53839. else {
  53840. subMaterial = this.subMaterials[index];
  53841. }
  53842. newMultiMaterial.subMaterials.push(subMaterial);
  53843. }
  53844. return newMultiMaterial;
  53845. };
  53846. MultiMaterial.prototype.serialize = function () {
  53847. var serializationObject = {};
  53848. serializationObject.name = this.name;
  53849. serializationObject.id = this.id;
  53850. serializationObject.tags = BABYLON.Tags.GetTags(this);
  53851. serializationObject.materials = [];
  53852. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  53853. var subMat = this.subMaterials[matIndex];
  53854. if (subMat) {
  53855. serializationObject.materials.push(subMat.id);
  53856. }
  53857. else {
  53858. serializationObject.materials.push(null);
  53859. }
  53860. }
  53861. return serializationObject;
  53862. };
  53863. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53864. var scene = this.getScene();
  53865. if (!scene) {
  53866. return;
  53867. }
  53868. var index = scene.multiMaterials.indexOf(this);
  53869. if (index >= 0) {
  53870. scene.multiMaterials.splice(index, 1);
  53871. }
  53872. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53873. };
  53874. return MultiMaterial;
  53875. }(BABYLON.Material));
  53876. BABYLON.MultiMaterial = MultiMaterial;
  53877. })(BABYLON || (BABYLON = {}));
  53878. //# sourceMappingURL=babylon.multiMaterial.js.map
  53879. var BABYLON;
  53880. (function (BABYLON) {
  53881. var FreeCameraTouchInput = /** @class */ (function () {
  53882. function FreeCameraTouchInput() {
  53883. this._offsetX = null;
  53884. this._offsetY = null;
  53885. this._pointerCount = 0;
  53886. this._pointerPressed = new Array();
  53887. this.touchAngularSensibility = 200000.0;
  53888. this.touchMoveSensibility = 250.0;
  53889. }
  53890. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  53891. var _this = this;
  53892. var previousPosition = null;
  53893. if (this._pointerInput === undefined) {
  53894. this._onLostFocus = function (evt) {
  53895. _this._offsetX = null;
  53896. _this._offsetY = null;
  53897. };
  53898. this._pointerInput = function (p, s) {
  53899. var evt = p.event;
  53900. if (evt.pointerType === "mouse") {
  53901. return;
  53902. }
  53903. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  53904. if (!noPreventDefault) {
  53905. evt.preventDefault();
  53906. }
  53907. _this._pointerPressed.push(evt.pointerId);
  53908. if (_this._pointerPressed.length !== 1) {
  53909. return;
  53910. }
  53911. previousPosition = {
  53912. x: evt.clientX,
  53913. y: evt.clientY
  53914. };
  53915. }
  53916. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  53917. if (!noPreventDefault) {
  53918. evt.preventDefault();
  53919. }
  53920. var index = _this._pointerPressed.indexOf(evt.pointerId);
  53921. if (index === -1) {
  53922. return;
  53923. }
  53924. _this._pointerPressed.splice(index, 1);
  53925. if (index != 0) {
  53926. return;
  53927. }
  53928. previousPosition = null;
  53929. _this._offsetX = null;
  53930. _this._offsetY = null;
  53931. }
  53932. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  53933. if (!noPreventDefault) {
  53934. evt.preventDefault();
  53935. }
  53936. if (!previousPosition) {
  53937. return;
  53938. }
  53939. var index = _this._pointerPressed.indexOf(evt.pointerId);
  53940. if (index != 0) {
  53941. return;
  53942. }
  53943. _this._offsetX = evt.clientX - previousPosition.x;
  53944. _this._offsetY = -(evt.clientY - previousPosition.y);
  53945. }
  53946. };
  53947. }
  53948. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  53949. if (this._onLostFocus) {
  53950. element.addEventListener("blur", this._onLostFocus);
  53951. }
  53952. };
  53953. FreeCameraTouchInput.prototype.detachControl = function (element) {
  53954. if (this._pointerInput && element) {
  53955. if (this._observer) {
  53956. this.camera.getScene().onPointerObservable.remove(this._observer);
  53957. this._observer = null;
  53958. }
  53959. if (this._onLostFocus) {
  53960. element.removeEventListener("blur", this._onLostFocus);
  53961. this._onLostFocus = null;
  53962. }
  53963. this._pointerPressed = [];
  53964. this._offsetX = null;
  53965. this._offsetY = null;
  53966. this._pointerCount = 0;
  53967. }
  53968. };
  53969. FreeCameraTouchInput.prototype.checkInputs = function () {
  53970. if (this._offsetX && this._offsetY) {
  53971. var camera = this.camera;
  53972. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  53973. if (this._pointerPressed.length > 1) {
  53974. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  53975. }
  53976. else {
  53977. var speed = camera._computeLocalCameraSpeed();
  53978. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  53979. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  53980. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  53981. }
  53982. }
  53983. };
  53984. FreeCameraTouchInput.prototype.getClassName = function () {
  53985. return "FreeCameraTouchInput";
  53986. };
  53987. FreeCameraTouchInput.prototype.getSimpleName = function () {
  53988. return "touch";
  53989. };
  53990. __decorate([
  53991. BABYLON.serialize()
  53992. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  53993. __decorate([
  53994. BABYLON.serialize()
  53995. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  53996. return FreeCameraTouchInput;
  53997. }());
  53998. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  53999. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54000. })(BABYLON || (BABYLON = {}));
  54001. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54002. var BABYLON;
  54003. (function (BABYLON) {
  54004. // We're mainly based on the logic defined into the FreeCamera code
  54005. var TouchCamera = /** @class */ (function (_super) {
  54006. __extends(TouchCamera, _super);
  54007. //-- end properties for backward compatibility for inputs
  54008. function TouchCamera(name, position, scene) {
  54009. var _this = _super.call(this, name, position, scene) || this;
  54010. _this.inputs.addTouch();
  54011. _this._setupInputs();
  54012. return _this;
  54013. }
  54014. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54015. //-- Begin properties for backward compatibility for inputs
  54016. get: function () {
  54017. var touch = this.inputs.attached["touch"];
  54018. if (touch)
  54019. return touch.touchAngularSensibility;
  54020. return 0;
  54021. },
  54022. set: function (value) {
  54023. var touch = this.inputs.attached["touch"];
  54024. if (touch)
  54025. touch.touchAngularSensibility = value;
  54026. },
  54027. enumerable: true,
  54028. configurable: true
  54029. });
  54030. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54031. get: function () {
  54032. var touch = this.inputs.attached["touch"];
  54033. if (touch)
  54034. return touch.touchMoveSensibility;
  54035. return 0;
  54036. },
  54037. set: function (value) {
  54038. var touch = this.inputs.attached["touch"];
  54039. if (touch)
  54040. touch.touchMoveSensibility = value;
  54041. },
  54042. enumerable: true,
  54043. configurable: true
  54044. });
  54045. TouchCamera.prototype.getClassName = function () {
  54046. return "TouchCamera";
  54047. };
  54048. TouchCamera.prototype._setupInputs = function () {
  54049. var mouse = this.inputs.attached["mouse"];
  54050. if (mouse) {
  54051. mouse.touchEnabled = false;
  54052. }
  54053. };
  54054. return TouchCamera;
  54055. }(BABYLON.FreeCamera));
  54056. BABYLON.TouchCamera = TouchCamera;
  54057. })(BABYLON || (BABYLON = {}));
  54058. //# sourceMappingURL=babylon.touchCamera.js.map
  54059. var BABYLON;
  54060. (function (BABYLON) {
  54061. var ProceduralTexture = /** @class */ (function (_super) {
  54062. __extends(ProceduralTexture, _super);
  54063. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  54064. if (fallbackTexture === void 0) { fallbackTexture = null; }
  54065. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54066. if (isCube === void 0) { isCube = false; }
  54067. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54068. _this.isCube = isCube;
  54069. _this.isEnabled = true;
  54070. _this._currentRefreshId = -1;
  54071. _this._refreshRate = 1;
  54072. _this._vertexBuffers = {};
  54073. _this._uniforms = new Array();
  54074. _this._samplers = new Array();
  54075. _this._textures = {};
  54076. _this._floats = {};
  54077. _this._floatsArrays = {};
  54078. _this._colors3 = {};
  54079. _this._colors4 = {};
  54080. _this._vectors2 = {};
  54081. _this._vectors3 = {};
  54082. _this._matrices = {};
  54083. _this._fallbackTextureUsed = false;
  54084. scene._proceduralTextures.push(_this);
  54085. _this._engine = scene.getEngine();
  54086. _this.name = name;
  54087. _this.isRenderTarget = true;
  54088. _this._size = size;
  54089. _this._generateMipMaps = generateMipMaps;
  54090. _this.setFragment(fragment);
  54091. _this._fallbackTexture = fallbackTexture;
  54092. if (isCube) {
  54093. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  54094. _this.setFloat("face", 0);
  54095. }
  54096. else {
  54097. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  54098. }
  54099. // VBO
  54100. var vertices = [];
  54101. vertices.push(1, 1);
  54102. vertices.push(-1, 1);
  54103. vertices.push(-1, -1);
  54104. vertices.push(1, -1);
  54105. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54106. _this._createIndexBuffer();
  54107. return _this;
  54108. }
  54109. ProceduralTexture.prototype._createIndexBuffer = function () {
  54110. var engine = this._engine;
  54111. // Indices
  54112. var indices = [];
  54113. indices.push(0);
  54114. indices.push(1);
  54115. indices.push(2);
  54116. indices.push(0);
  54117. indices.push(2);
  54118. indices.push(3);
  54119. this._indexBuffer = engine.createIndexBuffer(indices);
  54120. };
  54121. ProceduralTexture.prototype._rebuild = function () {
  54122. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54123. if (vb) {
  54124. vb._rebuild();
  54125. }
  54126. this._createIndexBuffer();
  54127. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54128. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54129. }
  54130. };
  54131. ProceduralTexture.prototype.reset = function () {
  54132. if (this._effect === undefined) {
  54133. return;
  54134. }
  54135. var engine = this._engine;
  54136. engine._releaseEffect(this._effect);
  54137. };
  54138. ProceduralTexture.prototype.isReady = function () {
  54139. var _this = this;
  54140. var engine = this._engine;
  54141. var shaders;
  54142. if (!this._fragment) {
  54143. return false;
  54144. }
  54145. if (this._fallbackTextureUsed) {
  54146. return true;
  54147. }
  54148. if (this._fragment.fragmentElement !== undefined) {
  54149. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  54150. }
  54151. else {
  54152. shaders = { vertex: "procedural", fragment: this._fragment };
  54153. }
  54154. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  54155. _this.releaseInternalTexture();
  54156. if (_this._fallbackTexture) {
  54157. _this._texture = _this._fallbackTexture._texture;
  54158. if (_this._texture) {
  54159. _this._texture.incrementReferences();
  54160. }
  54161. }
  54162. _this._fallbackTextureUsed = true;
  54163. });
  54164. return this._effect.isReady();
  54165. };
  54166. ProceduralTexture.prototype.resetRefreshCounter = function () {
  54167. this._currentRefreshId = -1;
  54168. };
  54169. ProceduralTexture.prototype.setFragment = function (fragment) {
  54170. this._fragment = fragment;
  54171. };
  54172. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  54173. get: function () {
  54174. return this._refreshRate;
  54175. },
  54176. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54177. set: function (value) {
  54178. this._refreshRate = value;
  54179. this.resetRefreshCounter();
  54180. },
  54181. enumerable: true,
  54182. configurable: true
  54183. });
  54184. ProceduralTexture.prototype._shouldRender = function () {
  54185. if (!this.isEnabled || !this.isReady() || !this._texture) {
  54186. return false;
  54187. }
  54188. if (this._fallbackTextureUsed) {
  54189. return false;
  54190. }
  54191. if (this._currentRefreshId === -1) {
  54192. this._currentRefreshId = 1;
  54193. return true;
  54194. }
  54195. if (this.refreshRate === this._currentRefreshId) {
  54196. this._currentRefreshId = 1;
  54197. return true;
  54198. }
  54199. this._currentRefreshId++;
  54200. return false;
  54201. };
  54202. ProceduralTexture.prototype.getRenderSize = function () {
  54203. return this._size;
  54204. };
  54205. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  54206. if (this._fallbackTextureUsed) {
  54207. return;
  54208. }
  54209. this.releaseInternalTexture();
  54210. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  54211. };
  54212. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  54213. if (this._uniforms.indexOf(uniformName) === -1) {
  54214. this._uniforms.push(uniformName);
  54215. }
  54216. };
  54217. ProceduralTexture.prototype.setTexture = function (name, texture) {
  54218. if (this._samplers.indexOf(name) === -1) {
  54219. this._samplers.push(name);
  54220. }
  54221. this._textures[name] = texture;
  54222. return this;
  54223. };
  54224. ProceduralTexture.prototype.setFloat = function (name, value) {
  54225. this._checkUniform(name);
  54226. this._floats[name] = value;
  54227. return this;
  54228. };
  54229. ProceduralTexture.prototype.setFloats = function (name, value) {
  54230. this._checkUniform(name);
  54231. this._floatsArrays[name] = value;
  54232. return this;
  54233. };
  54234. ProceduralTexture.prototype.setColor3 = function (name, value) {
  54235. this._checkUniform(name);
  54236. this._colors3[name] = value;
  54237. return this;
  54238. };
  54239. ProceduralTexture.prototype.setColor4 = function (name, value) {
  54240. this._checkUniform(name);
  54241. this._colors4[name] = value;
  54242. return this;
  54243. };
  54244. ProceduralTexture.prototype.setVector2 = function (name, value) {
  54245. this._checkUniform(name);
  54246. this._vectors2[name] = value;
  54247. return this;
  54248. };
  54249. ProceduralTexture.prototype.setVector3 = function (name, value) {
  54250. this._checkUniform(name);
  54251. this._vectors3[name] = value;
  54252. return this;
  54253. };
  54254. ProceduralTexture.prototype.setMatrix = function (name, value) {
  54255. this._checkUniform(name);
  54256. this._matrices[name] = value;
  54257. return this;
  54258. };
  54259. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54260. var scene = this.getScene();
  54261. if (!scene) {
  54262. return;
  54263. }
  54264. var engine = this._engine;
  54265. // Render
  54266. engine.enableEffect(this._effect);
  54267. engine.setState(false);
  54268. // Texture
  54269. for (var name in this._textures) {
  54270. this._effect.setTexture(name, this._textures[name]);
  54271. }
  54272. // Float
  54273. for (name in this._floats) {
  54274. this._effect.setFloat(name, this._floats[name]);
  54275. }
  54276. // Floats
  54277. for (name in this._floatsArrays) {
  54278. this._effect.setArray(name, this._floatsArrays[name]);
  54279. }
  54280. // Color3
  54281. for (name in this._colors3) {
  54282. this._effect.setColor3(name, this._colors3[name]);
  54283. }
  54284. // Color4
  54285. for (name in this._colors4) {
  54286. var color = this._colors4[name];
  54287. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54288. }
  54289. // Vector2
  54290. for (name in this._vectors2) {
  54291. this._effect.setVector2(name, this._vectors2[name]);
  54292. }
  54293. // Vector3
  54294. for (name in this._vectors3) {
  54295. this._effect.setVector3(name, this._vectors3[name]);
  54296. }
  54297. // Matrix
  54298. for (name in this._matrices) {
  54299. this._effect.setMatrix(name, this._matrices[name]);
  54300. }
  54301. if (!this._texture) {
  54302. return;
  54303. }
  54304. if (this.isCube) {
  54305. for (var face = 0; face < 6; face++) {
  54306. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  54307. // VBOs
  54308. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54309. this._effect.setFloat("face", face);
  54310. // Clear
  54311. engine.clear(scene.clearColor, true, true, true);
  54312. // Draw order
  54313. engine.draw(true, 0, 6);
  54314. // Mipmaps
  54315. if (face === 5) {
  54316. engine.generateMipMapsForCubemap(this._texture);
  54317. }
  54318. }
  54319. }
  54320. else {
  54321. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  54322. // VBOs
  54323. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54324. // Clear
  54325. engine.clear(scene.clearColor, true, true, true);
  54326. // Draw order
  54327. engine.draw(true, 0, 6);
  54328. }
  54329. // Unbind
  54330. engine.unBindFramebuffer(this._texture, this.isCube);
  54331. if (this.onGenerated) {
  54332. this.onGenerated();
  54333. }
  54334. };
  54335. ProceduralTexture.prototype.clone = function () {
  54336. var textureSize = this.getSize();
  54337. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  54338. // Base texture
  54339. newTexture.hasAlpha = this.hasAlpha;
  54340. newTexture.level = this.level;
  54341. // RenderTarget Texture
  54342. newTexture.coordinatesMode = this.coordinatesMode;
  54343. return newTexture;
  54344. };
  54345. ProceduralTexture.prototype.dispose = function () {
  54346. var scene = this.getScene();
  54347. if (!scene) {
  54348. return;
  54349. }
  54350. var index = scene._proceduralTextures.indexOf(this);
  54351. if (index >= 0) {
  54352. scene._proceduralTextures.splice(index, 1);
  54353. }
  54354. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54355. if (vertexBuffer) {
  54356. vertexBuffer.dispose();
  54357. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54358. }
  54359. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  54360. this._indexBuffer = null;
  54361. }
  54362. _super.prototype.dispose.call(this);
  54363. };
  54364. return ProceduralTexture;
  54365. }(BABYLON.Texture));
  54366. BABYLON.ProceduralTexture = ProceduralTexture;
  54367. })(BABYLON || (BABYLON = {}));
  54368. //# sourceMappingURL=babylon.proceduralTexture.js.map
  54369. var BABYLON;
  54370. (function (BABYLON) {
  54371. var CustomProceduralTexture = /** @class */ (function (_super) {
  54372. __extends(CustomProceduralTexture, _super);
  54373. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  54374. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  54375. _this._animate = true;
  54376. _this._time = 0;
  54377. _this._texturePath = texturePath;
  54378. //Try to load json
  54379. _this.loadJson(texturePath);
  54380. _this.refreshRate = 1;
  54381. return _this;
  54382. }
  54383. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  54384. var _this = this;
  54385. var noConfigFile = function () {
  54386. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  54387. try {
  54388. _this.setFragment(_this._texturePath);
  54389. }
  54390. catch (ex) {
  54391. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  54392. }
  54393. };
  54394. var configFileUrl = jsonUrl + "/config.json";
  54395. var xhr = new XMLHttpRequest();
  54396. xhr.open("GET", configFileUrl, true);
  54397. xhr.addEventListener("load", function () {
  54398. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54399. try {
  54400. _this._config = JSON.parse(xhr.response);
  54401. _this.updateShaderUniforms();
  54402. _this.updateTextures();
  54403. _this.setFragment(_this._texturePath + "/custom");
  54404. _this._animate = _this._config.animate;
  54405. _this.refreshRate = _this._config.refreshrate;
  54406. }
  54407. catch (ex) {
  54408. noConfigFile();
  54409. }
  54410. }
  54411. else {
  54412. noConfigFile();
  54413. }
  54414. }, false);
  54415. xhr.addEventListener("error", function () {
  54416. noConfigFile();
  54417. }, false);
  54418. try {
  54419. xhr.send();
  54420. }
  54421. catch (ex) {
  54422. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  54423. }
  54424. };
  54425. CustomProceduralTexture.prototype.isReady = function () {
  54426. if (!_super.prototype.isReady.call(this)) {
  54427. return false;
  54428. }
  54429. for (var name in this._textures) {
  54430. var texture = this._textures[name];
  54431. if (!texture.isReady()) {
  54432. return false;
  54433. }
  54434. }
  54435. return true;
  54436. };
  54437. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54438. var scene = this.getScene();
  54439. if (this._animate && scene) {
  54440. this._time += scene.getAnimationRatio() * 0.03;
  54441. this.updateShaderUniforms();
  54442. }
  54443. _super.prototype.render.call(this, useCameraPostProcess);
  54444. };
  54445. CustomProceduralTexture.prototype.updateTextures = function () {
  54446. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  54447. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  54448. }
  54449. };
  54450. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  54451. if (this._config) {
  54452. for (var j = 0; j < this._config.uniforms.length; j++) {
  54453. var uniform = this._config.uniforms[j];
  54454. switch (uniform.type) {
  54455. case "float":
  54456. this.setFloat(uniform.name, uniform.value);
  54457. break;
  54458. case "color3":
  54459. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  54460. break;
  54461. case "color4":
  54462. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  54463. break;
  54464. case "vector2":
  54465. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  54466. break;
  54467. case "vector3":
  54468. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  54469. break;
  54470. }
  54471. }
  54472. }
  54473. this.setFloat("time", this._time);
  54474. };
  54475. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  54476. get: function () {
  54477. return this._animate;
  54478. },
  54479. set: function (value) {
  54480. this._animate = value;
  54481. },
  54482. enumerable: true,
  54483. configurable: true
  54484. });
  54485. return CustomProceduralTexture;
  54486. }(BABYLON.ProceduralTexture));
  54487. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  54488. })(BABYLON || (BABYLON = {}));
  54489. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  54490. var BABYLON;
  54491. (function (BABYLON) {
  54492. var FreeCameraGamepadInput = /** @class */ (function () {
  54493. function FreeCameraGamepadInput() {
  54494. this.gamepadAngularSensibility = 200;
  54495. this.gamepadMoveSensibility = 40;
  54496. // private members
  54497. this._cameraTransform = BABYLON.Matrix.Identity();
  54498. this._deltaTransform = BABYLON.Vector3.Zero();
  54499. this._vector3 = BABYLON.Vector3.Zero();
  54500. this._vector2 = BABYLON.Vector2.Zero();
  54501. }
  54502. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54503. var _this = this;
  54504. var manager = this.camera.getScene().gamepadManager;
  54505. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54506. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54507. // prioritize XBOX gamepads.
  54508. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54509. _this.gamepad = gamepad;
  54510. }
  54511. }
  54512. });
  54513. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54514. if (_this.gamepad === gamepad) {
  54515. _this.gamepad = null;
  54516. }
  54517. });
  54518. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54519. };
  54520. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  54521. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54522. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54523. this.gamepad = null;
  54524. };
  54525. FreeCameraGamepadInput.prototype.checkInputs = function () {
  54526. if (this.gamepad && this.gamepad.leftStick) {
  54527. var camera = this.camera;
  54528. var LSValues = this.gamepad.leftStick;
  54529. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  54530. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54531. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  54532. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  54533. var RSValues = this.gamepad.rightStick;
  54534. if (RSValues) {
  54535. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  54536. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  54537. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  54538. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  54539. }
  54540. else {
  54541. RSValues = { x: 0, y: 0 };
  54542. }
  54543. if (!camera.rotationQuaternion) {
  54544. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  54545. }
  54546. else {
  54547. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  54548. }
  54549. var speed = camera._computeLocalCameraSpeed() * 50.0;
  54550. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  54551. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  54552. camera.cameraDirection.addInPlace(this._deltaTransform);
  54553. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  54554. camera.cameraRotation.addInPlace(this._vector2);
  54555. }
  54556. };
  54557. FreeCameraGamepadInput.prototype.getClassName = function () {
  54558. return "FreeCameraGamepadInput";
  54559. };
  54560. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  54561. return "gamepad";
  54562. };
  54563. __decorate([
  54564. BABYLON.serialize()
  54565. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  54566. __decorate([
  54567. BABYLON.serialize()
  54568. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54569. return FreeCameraGamepadInput;
  54570. }());
  54571. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  54572. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  54573. })(BABYLON || (BABYLON = {}));
  54574. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  54575. var BABYLON;
  54576. (function (BABYLON) {
  54577. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  54578. function ArcRotateCameraGamepadInput() {
  54579. this.gamepadRotationSensibility = 80;
  54580. this.gamepadMoveSensibility = 40;
  54581. }
  54582. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54583. var _this = this;
  54584. var manager = this.camera.getScene().gamepadManager;
  54585. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54586. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54587. // prioritize XBOX gamepads.
  54588. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54589. _this.gamepad = gamepad;
  54590. }
  54591. }
  54592. });
  54593. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54594. if (_this.gamepad === gamepad) {
  54595. _this.gamepad = null;
  54596. }
  54597. });
  54598. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54599. };
  54600. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  54601. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54602. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54603. this.gamepad = null;
  54604. };
  54605. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  54606. if (this.gamepad) {
  54607. var camera = this.camera;
  54608. var RSValues = this.gamepad.rightStick;
  54609. if (RSValues) {
  54610. if (RSValues.x != 0) {
  54611. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  54612. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  54613. camera.inertialAlphaOffset += normalizedRX;
  54614. }
  54615. }
  54616. if (RSValues.y != 0) {
  54617. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  54618. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  54619. camera.inertialBetaOffset += normalizedRY;
  54620. }
  54621. }
  54622. }
  54623. var LSValues = this.gamepad.leftStick;
  54624. if (LSValues && LSValues.y != 0) {
  54625. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54626. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  54627. this.camera.inertialRadiusOffset -= normalizedLY;
  54628. }
  54629. }
  54630. }
  54631. };
  54632. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  54633. return "ArcRotateCameraGamepadInput";
  54634. };
  54635. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  54636. return "gamepad";
  54637. };
  54638. __decorate([
  54639. BABYLON.serialize()
  54640. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  54641. __decorate([
  54642. BABYLON.serialize()
  54643. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54644. return ArcRotateCameraGamepadInput;
  54645. }());
  54646. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  54647. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  54648. })(BABYLON || (BABYLON = {}));
  54649. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  54650. var BABYLON;
  54651. (function (BABYLON) {
  54652. var GamepadManager = /** @class */ (function () {
  54653. function GamepadManager() {
  54654. var _this = this;
  54655. this._babylonGamepads = [];
  54656. this._oneGamepadConnected = false;
  54657. this._isMonitoring = false;
  54658. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  54659. if (!BABYLON.Tools.IsWindowObjectExist()) {
  54660. this._gamepadEventSupported = false;
  54661. }
  54662. else {
  54663. this._gamepadEventSupported = 'GamepadEvent' in window;
  54664. this._gamepadSupport = (navigator.getGamepads ||
  54665. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  54666. }
  54667. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  54668. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  54669. for (var i in _this._babylonGamepads) {
  54670. var gamepad = _this._babylonGamepads[i];
  54671. if (gamepad && gamepad._isConnected) {
  54672. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  54673. }
  54674. }
  54675. });
  54676. this._onGamepadConnectedEvent = function (evt) {
  54677. var gamepad = evt.gamepad;
  54678. if (gamepad.index in _this._babylonGamepads) {
  54679. if (_this._babylonGamepads[gamepad.index].isConnected) {
  54680. return;
  54681. }
  54682. }
  54683. var newGamepad;
  54684. if (_this._babylonGamepads[gamepad.index]) {
  54685. newGamepad = _this._babylonGamepads[gamepad.index];
  54686. newGamepad.browserGamepad = gamepad;
  54687. newGamepad._isConnected = true;
  54688. }
  54689. else {
  54690. newGamepad = _this._addNewGamepad(gamepad);
  54691. }
  54692. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54693. _this._startMonitoringGamepads();
  54694. };
  54695. this._onGamepadDisconnectedEvent = function (evt) {
  54696. var gamepad = evt.gamepad;
  54697. // Remove the gamepad from the list of gamepads to monitor.
  54698. for (var i in _this._babylonGamepads) {
  54699. if (_this._babylonGamepads[i].index === gamepad.index) {
  54700. var disconnectedGamepad = _this._babylonGamepads[i];
  54701. disconnectedGamepad._isConnected = false;
  54702. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  54703. break;
  54704. }
  54705. }
  54706. };
  54707. if (this._gamepadSupport) {
  54708. //first add already-connected gamepads
  54709. this._updateGamepadObjects();
  54710. if (this._babylonGamepads.length) {
  54711. this._startMonitoringGamepads();
  54712. }
  54713. // Checking if the gamepad connected event is supported (like in Firefox)
  54714. if (this._gamepadEventSupported) {
  54715. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54716. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  54717. }
  54718. else {
  54719. this._startMonitoringGamepads();
  54720. }
  54721. }
  54722. }
  54723. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  54724. get: function () {
  54725. return this._babylonGamepads;
  54726. },
  54727. enumerable: true,
  54728. configurable: true
  54729. });
  54730. GamepadManager.prototype.getGamepadByType = function (type) {
  54731. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  54732. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  54733. var gamepad = _a[_i];
  54734. if (gamepad && gamepad.type === type) {
  54735. return gamepad;
  54736. }
  54737. }
  54738. return null;
  54739. };
  54740. GamepadManager.prototype.dispose = function () {
  54741. if (this._gamepadEventSupported) {
  54742. if (this._onGamepadConnectedEvent) {
  54743. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  54744. }
  54745. if (this._onGamepadDisconnectedEvent) {
  54746. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  54747. }
  54748. this._onGamepadConnectedEvent = null;
  54749. this._onGamepadDisconnectedEvent = null;
  54750. }
  54751. this._babylonGamepads.forEach(function (gamepad) {
  54752. gamepad.dispose();
  54753. });
  54754. this.onGamepadConnectedObservable.clear();
  54755. this.onGamepadDisconnectedObservable.clear();
  54756. this._oneGamepadConnected = false;
  54757. this._stopMonitoringGamepads();
  54758. this._babylonGamepads = [];
  54759. };
  54760. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  54761. if (!this._oneGamepadConnected) {
  54762. this._oneGamepadConnected = true;
  54763. }
  54764. var newGamepad;
  54765. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  54766. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54767. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  54768. }
  54769. else if (gamepad.pose) {
  54770. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  54771. }
  54772. else {
  54773. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  54774. }
  54775. this._babylonGamepads[newGamepad.index] = newGamepad;
  54776. return newGamepad;
  54777. };
  54778. GamepadManager.prototype._startMonitoringGamepads = function () {
  54779. if (!this._isMonitoring) {
  54780. this._isMonitoring = true;
  54781. this._checkGamepadsStatus();
  54782. }
  54783. };
  54784. GamepadManager.prototype._stopMonitoringGamepads = function () {
  54785. this._isMonitoring = false;
  54786. };
  54787. GamepadManager.prototype._checkGamepadsStatus = function () {
  54788. var _this = this;
  54789. // Hack to be compatible Chrome
  54790. this._updateGamepadObjects();
  54791. for (var i in this._babylonGamepads) {
  54792. var gamepad = this._babylonGamepads[i];
  54793. if (!gamepad || !gamepad.isConnected) {
  54794. continue;
  54795. }
  54796. gamepad.update();
  54797. }
  54798. if (this._isMonitoring) {
  54799. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  54800. }
  54801. };
  54802. // This function is called only on Chrome, which does not properly support
  54803. // connection/disconnection events and forces you to recopy again the gamepad object
  54804. GamepadManager.prototype._updateGamepadObjects = function () {
  54805. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54806. for (var i = 0; i < gamepads.length; i++) {
  54807. if (gamepads[i]) {
  54808. if (!this._babylonGamepads[gamepads[i].index]) {
  54809. var newGamepad = this._addNewGamepad(gamepads[i]);
  54810. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54811. }
  54812. else {
  54813. // Forced to copy again this object for Chrome for unknown reason
  54814. this._babylonGamepads[i].browserGamepad = gamepads[i];
  54815. if (!this._babylonGamepads[i].isConnected) {
  54816. this._babylonGamepads[i]._isConnected = true;
  54817. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  54818. }
  54819. }
  54820. }
  54821. }
  54822. };
  54823. return GamepadManager;
  54824. }());
  54825. BABYLON.GamepadManager = GamepadManager;
  54826. })(BABYLON || (BABYLON = {}));
  54827. //# sourceMappingURL=babylon.gamepadManager.js.map
  54828. var BABYLON;
  54829. (function (BABYLON) {
  54830. var StickValues = /** @class */ (function () {
  54831. function StickValues(x, y) {
  54832. this.x = x;
  54833. this.y = y;
  54834. }
  54835. return StickValues;
  54836. }());
  54837. BABYLON.StickValues = StickValues;
  54838. var Gamepad = /** @class */ (function () {
  54839. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  54840. if (leftStickX === void 0) { leftStickX = 0; }
  54841. if (leftStickY === void 0) { leftStickY = 1; }
  54842. if (rightStickX === void 0) { rightStickX = 2; }
  54843. if (rightStickY === void 0) { rightStickY = 3; }
  54844. this.id = id;
  54845. this.index = index;
  54846. this.browserGamepad = browserGamepad;
  54847. this._isConnected = true;
  54848. this.type = Gamepad.GAMEPAD;
  54849. this._leftStickAxisX = leftStickX;
  54850. this._leftStickAxisY = leftStickY;
  54851. this._rightStickAxisX = rightStickX;
  54852. this._rightStickAxisY = rightStickY;
  54853. if (this.browserGamepad.axes.length >= 2) {
  54854. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  54855. }
  54856. if (this.browserGamepad.axes.length >= 4) {
  54857. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  54858. }
  54859. }
  54860. Object.defineProperty(Gamepad.prototype, "isConnected", {
  54861. get: function () {
  54862. return this._isConnected;
  54863. },
  54864. enumerable: true,
  54865. configurable: true
  54866. });
  54867. Gamepad.prototype.onleftstickchanged = function (callback) {
  54868. this._onleftstickchanged = callback;
  54869. };
  54870. Gamepad.prototype.onrightstickchanged = function (callback) {
  54871. this._onrightstickchanged = callback;
  54872. };
  54873. Object.defineProperty(Gamepad.prototype, "leftStick", {
  54874. get: function () {
  54875. return this._leftStick;
  54876. },
  54877. set: function (newValues) {
  54878. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  54879. this._onleftstickchanged(newValues);
  54880. }
  54881. this._leftStick = newValues;
  54882. },
  54883. enumerable: true,
  54884. configurable: true
  54885. });
  54886. Object.defineProperty(Gamepad.prototype, "rightStick", {
  54887. get: function () {
  54888. return this._rightStick;
  54889. },
  54890. set: function (newValues) {
  54891. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  54892. this._onrightstickchanged(newValues);
  54893. }
  54894. this._rightStick = newValues;
  54895. },
  54896. enumerable: true,
  54897. configurable: true
  54898. });
  54899. Gamepad.prototype.update = function () {
  54900. if (this._leftStick) {
  54901. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  54902. }
  54903. if (this._rightStick) {
  54904. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  54905. }
  54906. };
  54907. Gamepad.prototype.dispose = function () {
  54908. };
  54909. Gamepad.GAMEPAD = 0;
  54910. Gamepad.GENERIC = 1;
  54911. Gamepad.XBOX = 2;
  54912. Gamepad.POSE_ENABLED = 3;
  54913. return Gamepad;
  54914. }());
  54915. BABYLON.Gamepad = Gamepad;
  54916. var GenericPad = /** @class */ (function (_super) {
  54917. __extends(GenericPad, _super);
  54918. function GenericPad(id, index, browserGamepad) {
  54919. var _this = _super.call(this, id, index, browserGamepad) || this;
  54920. _this.onButtonDownObservable = new BABYLON.Observable();
  54921. _this.onButtonUpObservable = new BABYLON.Observable();
  54922. _this.type = Gamepad.GENERIC;
  54923. _this._buttons = new Array(browserGamepad.buttons.length);
  54924. return _this;
  54925. }
  54926. GenericPad.prototype.onbuttondown = function (callback) {
  54927. this._onbuttondown = callback;
  54928. };
  54929. GenericPad.prototype.onbuttonup = function (callback) {
  54930. this._onbuttonup = callback;
  54931. };
  54932. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  54933. if (newValue !== currentValue) {
  54934. if (newValue === 1) {
  54935. if (this._onbuttondown) {
  54936. this._onbuttondown(buttonIndex);
  54937. }
  54938. this.onButtonDownObservable.notifyObservers(buttonIndex);
  54939. }
  54940. if (newValue === 0) {
  54941. if (this._onbuttonup) {
  54942. this._onbuttonup(buttonIndex);
  54943. }
  54944. this.onButtonUpObservable.notifyObservers(buttonIndex);
  54945. }
  54946. }
  54947. return newValue;
  54948. };
  54949. GenericPad.prototype.update = function () {
  54950. _super.prototype.update.call(this);
  54951. for (var index = 0; index < this._buttons.length; index++) {
  54952. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  54953. }
  54954. };
  54955. return GenericPad;
  54956. }(Gamepad));
  54957. BABYLON.GenericPad = GenericPad;
  54958. })(BABYLON || (BABYLON = {}));
  54959. //# sourceMappingURL=babylon.gamepad.js.map
  54960. var BABYLON;
  54961. (function (BABYLON) {
  54962. var Xbox360Button;
  54963. (function (Xbox360Button) {
  54964. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  54965. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  54966. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  54967. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  54968. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  54969. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  54970. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  54971. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  54972. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  54973. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  54974. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  54975. var Xbox360Dpad;
  54976. (function (Xbox360Dpad) {
  54977. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  54978. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  54979. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  54980. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  54981. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  54982. var Xbox360Pad = /** @class */ (function (_super) {
  54983. __extends(Xbox360Pad, _super);
  54984. function Xbox360Pad(id, index, gamepad, xboxOne) {
  54985. if (xboxOne === void 0) { xboxOne = false; }
  54986. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  54987. _this._leftTrigger = 0;
  54988. _this._rightTrigger = 0;
  54989. _this.onButtonDownObservable = new BABYLON.Observable();
  54990. _this.onButtonUpObservable = new BABYLON.Observable();
  54991. _this.onPadDownObservable = new BABYLON.Observable();
  54992. _this.onPadUpObservable = new BABYLON.Observable();
  54993. _this._buttonA = 0;
  54994. _this._buttonB = 0;
  54995. _this._buttonX = 0;
  54996. _this._buttonY = 0;
  54997. _this._buttonBack = 0;
  54998. _this._buttonStart = 0;
  54999. _this._buttonLB = 0;
  55000. _this._buttonRB = 0;
  55001. _this._buttonLeftStick = 0;
  55002. _this._buttonRightStick = 0;
  55003. _this._dPadUp = 0;
  55004. _this._dPadDown = 0;
  55005. _this._dPadLeft = 0;
  55006. _this._dPadRight = 0;
  55007. _this._isXboxOnePad = false;
  55008. _this.type = BABYLON.Gamepad.XBOX;
  55009. _this._isXboxOnePad = xboxOne;
  55010. return _this;
  55011. }
  55012. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55013. this._onlefttriggerchanged = callback;
  55014. };
  55015. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55016. this._onrighttriggerchanged = callback;
  55017. };
  55018. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55019. get: function () {
  55020. return this._leftTrigger;
  55021. },
  55022. set: function (newValue) {
  55023. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55024. this._onlefttriggerchanged(newValue);
  55025. }
  55026. this._leftTrigger = newValue;
  55027. },
  55028. enumerable: true,
  55029. configurable: true
  55030. });
  55031. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55032. get: function () {
  55033. return this._rightTrigger;
  55034. },
  55035. set: function (newValue) {
  55036. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55037. this._onrighttriggerchanged(newValue);
  55038. }
  55039. this._rightTrigger = newValue;
  55040. },
  55041. enumerable: true,
  55042. configurable: true
  55043. });
  55044. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55045. this._onbuttondown = callback;
  55046. };
  55047. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55048. this._onbuttonup = callback;
  55049. };
  55050. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55051. this._ondpaddown = callback;
  55052. };
  55053. Xbox360Pad.prototype.ondpadup = function (callback) {
  55054. this._ondpadup = callback;
  55055. };
  55056. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55057. if (newValue !== currentValue) {
  55058. if (newValue === 1) {
  55059. if (this._onbuttondown) {
  55060. this._onbuttondown(buttonType);
  55061. }
  55062. this.onButtonDownObservable.notifyObservers(buttonType);
  55063. }
  55064. if (newValue === 0) {
  55065. if (this._onbuttonup) {
  55066. this._onbuttonup(buttonType);
  55067. }
  55068. this.onButtonUpObservable.notifyObservers(buttonType);
  55069. }
  55070. }
  55071. return newValue;
  55072. };
  55073. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55074. if (newValue !== currentValue) {
  55075. if (newValue === 1) {
  55076. if (this._ondpaddown) {
  55077. this._ondpaddown(buttonType);
  55078. }
  55079. this.onPadDownObservable.notifyObservers(buttonType);
  55080. }
  55081. if (newValue === 0) {
  55082. if (this._ondpadup) {
  55083. this._ondpadup(buttonType);
  55084. }
  55085. this.onPadUpObservable.notifyObservers(buttonType);
  55086. }
  55087. }
  55088. return newValue;
  55089. };
  55090. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55091. get: function () {
  55092. return this._buttonA;
  55093. },
  55094. set: function (value) {
  55095. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55096. },
  55097. enumerable: true,
  55098. configurable: true
  55099. });
  55100. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55101. get: function () {
  55102. return this._buttonB;
  55103. },
  55104. set: function (value) {
  55105. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55106. },
  55107. enumerable: true,
  55108. configurable: true
  55109. });
  55110. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55111. get: function () {
  55112. return this._buttonX;
  55113. },
  55114. set: function (value) {
  55115. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55116. },
  55117. enumerable: true,
  55118. configurable: true
  55119. });
  55120. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55121. get: function () {
  55122. return this._buttonY;
  55123. },
  55124. set: function (value) {
  55125. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55126. },
  55127. enumerable: true,
  55128. configurable: true
  55129. });
  55130. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55131. get: function () {
  55132. return this._buttonStart;
  55133. },
  55134. set: function (value) {
  55135. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55136. },
  55137. enumerable: true,
  55138. configurable: true
  55139. });
  55140. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55141. get: function () {
  55142. return this._buttonBack;
  55143. },
  55144. set: function (value) {
  55145. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55146. },
  55147. enumerable: true,
  55148. configurable: true
  55149. });
  55150. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55151. get: function () {
  55152. return this._buttonLB;
  55153. },
  55154. set: function (value) {
  55155. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55156. },
  55157. enumerable: true,
  55158. configurable: true
  55159. });
  55160. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55161. get: function () {
  55162. return this._buttonRB;
  55163. },
  55164. set: function (value) {
  55165. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55166. },
  55167. enumerable: true,
  55168. configurable: true
  55169. });
  55170. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55171. get: function () {
  55172. return this._buttonLeftStick;
  55173. },
  55174. set: function (value) {
  55175. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55176. },
  55177. enumerable: true,
  55178. configurable: true
  55179. });
  55180. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55181. get: function () {
  55182. return this._buttonRightStick;
  55183. },
  55184. set: function (value) {
  55185. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55186. },
  55187. enumerable: true,
  55188. configurable: true
  55189. });
  55190. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55191. get: function () {
  55192. return this._dPadUp;
  55193. },
  55194. set: function (value) {
  55195. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55196. },
  55197. enumerable: true,
  55198. configurable: true
  55199. });
  55200. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55201. get: function () {
  55202. return this._dPadDown;
  55203. },
  55204. set: function (value) {
  55205. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55206. },
  55207. enumerable: true,
  55208. configurable: true
  55209. });
  55210. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55211. get: function () {
  55212. return this._dPadLeft;
  55213. },
  55214. set: function (value) {
  55215. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55216. },
  55217. enumerable: true,
  55218. configurable: true
  55219. });
  55220. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55221. get: function () {
  55222. return this._dPadRight;
  55223. },
  55224. set: function (value) {
  55225. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55226. },
  55227. enumerable: true,
  55228. configurable: true
  55229. });
  55230. Xbox360Pad.prototype.update = function () {
  55231. _super.prototype.update.call(this);
  55232. if (this._isXboxOnePad) {
  55233. this.buttonA = this.browserGamepad.buttons[0].value;
  55234. this.buttonB = this.browserGamepad.buttons[1].value;
  55235. this.buttonX = this.browserGamepad.buttons[2].value;
  55236. this.buttonY = this.browserGamepad.buttons[3].value;
  55237. this.buttonLB = this.browserGamepad.buttons[4].value;
  55238. this.buttonRB = this.browserGamepad.buttons[5].value;
  55239. this.leftTrigger = this.browserGamepad.axes[2];
  55240. this.rightTrigger = this.browserGamepad.axes[5];
  55241. this.buttonBack = this.browserGamepad.buttons[9].value;
  55242. this.buttonStart = this.browserGamepad.buttons[8].value;
  55243. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  55244. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  55245. this.dPadUp = this.browserGamepad.buttons[11].value;
  55246. this.dPadDown = this.browserGamepad.buttons[12].value;
  55247. this.dPadLeft = this.browserGamepad.buttons[13].value;
  55248. this.dPadRight = this.browserGamepad.buttons[14].value;
  55249. }
  55250. else {
  55251. this.buttonA = this.browserGamepad.buttons[0].value;
  55252. this.buttonB = this.browserGamepad.buttons[1].value;
  55253. this.buttonX = this.browserGamepad.buttons[2].value;
  55254. this.buttonY = this.browserGamepad.buttons[3].value;
  55255. this.buttonLB = this.browserGamepad.buttons[4].value;
  55256. this.buttonRB = this.browserGamepad.buttons[5].value;
  55257. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55258. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55259. this.buttonBack = this.browserGamepad.buttons[8].value;
  55260. this.buttonStart = this.browserGamepad.buttons[9].value;
  55261. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55262. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55263. this.dPadUp = this.browserGamepad.buttons[12].value;
  55264. this.dPadDown = this.browserGamepad.buttons[13].value;
  55265. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55266. this.dPadRight = this.browserGamepad.buttons[15].value;
  55267. }
  55268. };
  55269. return Xbox360Pad;
  55270. }(BABYLON.Gamepad));
  55271. BABYLON.Xbox360Pad = Xbox360Pad;
  55272. })(BABYLON || (BABYLON = {}));
  55273. //# sourceMappingURL=babylon.xboxGamepad.js.map
  55274. var BABYLON;
  55275. (function (BABYLON) {
  55276. var PoseEnabledControllerType;
  55277. (function (PoseEnabledControllerType) {
  55278. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  55279. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  55280. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  55281. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  55282. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  55283. var PoseEnabledControllerHelper = /** @class */ (function () {
  55284. function PoseEnabledControllerHelper() {
  55285. }
  55286. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  55287. // Oculus Touch
  55288. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  55289. return new BABYLON.OculusTouchController(vrGamepad);
  55290. }
  55291. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  55292. return new BABYLON.WindowsMotionController(vrGamepad);
  55293. }
  55294. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  55295. return new BABYLON.ViveController(vrGamepad);
  55296. }
  55297. else {
  55298. return new BABYLON.GenericController(vrGamepad);
  55299. }
  55300. };
  55301. return PoseEnabledControllerHelper;
  55302. }());
  55303. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  55304. var PoseEnabledController = /** @class */ (function (_super) {
  55305. __extends(PoseEnabledController, _super);
  55306. function PoseEnabledController(browserGamepad) {
  55307. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  55308. _this.deviceScaleFactor = 1;
  55309. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  55310. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  55311. _this.controllerType = PoseEnabledControllerType.GENERIC;
  55312. _this.position = BABYLON.Vector3.Zero();
  55313. _this.rotationQuaternion = new BABYLON.Quaternion();
  55314. _this.devicePosition = BABYLON.Vector3.Zero();
  55315. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  55316. _this._calculatedPosition = BABYLON.Vector3.Zero();
  55317. _this._calculatedRotation = new BABYLON.Quaternion();
  55318. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  55319. return _this;
  55320. }
  55321. PoseEnabledController.prototype.update = function () {
  55322. _super.prototype.update.call(this);
  55323. var pose = this.browserGamepad.pose;
  55324. this.updateFromDevice(pose);
  55325. if (this._mesh) {
  55326. this._mesh.position.copyFrom(this._calculatedPosition);
  55327. if (this._mesh.rotationQuaternion) {
  55328. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  55329. }
  55330. }
  55331. };
  55332. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  55333. if (poseData) {
  55334. this.rawPose = poseData;
  55335. if (poseData.position) {
  55336. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  55337. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  55338. this.devicePosition.z *= -1;
  55339. }
  55340. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  55341. this._calculatedPosition.addInPlace(this.position);
  55342. }
  55343. var pose = this.rawPose;
  55344. if (poseData.orientation && pose.orientation) {
  55345. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  55346. if (this._mesh) {
  55347. if (this._mesh.getScene().useRightHandedSystem) {
  55348. this.deviceRotationQuaternion.z *= -1;
  55349. this.deviceRotationQuaternion.w *= -1;
  55350. }
  55351. else {
  55352. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  55353. }
  55354. }
  55355. // if the camera is set, rotate to the camera's rotation
  55356. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  55357. }
  55358. }
  55359. };
  55360. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  55361. if (this._mesh) {
  55362. this._mesh.parent = null;
  55363. }
  55364. this._mesh = mesh;
  55365. if (this._poseControlledCamera) {
  55366. this._mesh.parent = this._poseControlledCamera;
  55367. }
  55368. if (!this._mesh.rotationQuaternion) {
  55369. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  55370. }
  55371. };
  55372. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  55373. this._poseControlledCamera = camera;
  55374. if (this._mesh) {
  55375. this._mesh.parent = this._poseControlledCamera;
  55376. }
  55377. };
  55378. PoseEnabledController.prototype.dispose = function () {
  55379. if (this._mesh) {
  55380. this._mesh.dispose();
  55381. }
  55382. this._mesh = null;
  55383. _super.prototype.dispose.call(this);
  55384. };
  55385. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  55386. get: function () {
  55387. return this._mesh;
  55388. },
  55389. enumerable: true,
  55390. configurable: true
  55391. });
  55392. PoseEnabledController.prototype.getForwardRay = function (length) {
  55393. if (length === void 0) { length = 100; }
  55394. if (!this.mesh) {
  55395. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  55396. }
  55397. var m = this.mesh.getWorldMatrix();
  55398. var origin = m.getTranslation();
  55399. var forward = new BABYLON.Vector3(0, 0, -1);
  55400. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55401. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55402. return new BABYLON.Ray(origin, direction, length);
  55403. };
  55404. return PoseEnabledController;
  55405. }(BABYLON.Gamepad));
  55406. BABYLON.PoseEnabledController = PoseEnabledController;
  55407. })(BABYLON || (BABYLON = {}));
  55408. //# sourceMappingURL=babylon.poseEnabledController.js.map
  55409. var BABYLON;
  55410. (function (BABYLON) {
  55411. var WebVRController = /** @class */ (function (_super) {
  55412. __extends(WebVRController, _super);
  55413. function WebVRController(vrGamepad) {
  55414. var _this = _super.call(this, vrGamepad) || this;
  55415. // Observables
  55416. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  55417. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  55418. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  55419. _this.onPadStateChangedObservable = new BABYLON.Observable();
  55420. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  55421. _this.pad = { x: 0, y: 0 };
  55422. // avoid GC, store state in a tmp object
  55423. _this._changes = {
  55424. pressChanged: false,
  55425. touchChanged: false,
  55426. valueChanged: false,
  55427. changed: false
  55428. };
  55429. _this._buttons = new Array(vrGamepad.buttons.length);
  55430. _this.hand = vrGamepad.hand;
  55431. return _this;
  55432. }
  55433. WebVRController.prototype.onButtonStateChange = function (callback) {
  55434. this._onButtonStateChange = callback;
  55435. };
  55436. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  55437. get: function () {
  55438. return this._defaultModel;
  55439. },
  55440. enumerable: true,
  55441. configurable: true
  55442. });
  55443. WebVRController.prototype.update = function () {
  55444. _super.prototype.update.call(this);
  55445. for (var index = 0; index < this._buttons.length; index++) {
  55446. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  55447. }
  55448. ;
  55449. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  55450. this.pad.x = this.leftStick.x;
  55451. this.pad.y = this.leftStick.y;
  55452. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  55453. }
  55454. };
  55455. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  55456. if (!newState) {
  55457. newState = {
  55458. pressed: false,
  55459. touched: false,
  55460. value: 0
  55461. };
  55462. }
  55463. if (!currentState) {
  55464. this._buttons[buttonIndex] = {
  55465. pressed: newState.pressed,
  55466. touched: newState.touched,
  55467. value: newState.value
  55468. };
  55469. return;
  55470. }
  55471. this._checkChanges(newState, currentState);
  55472. if (this._changes.changed) {
  55473. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  55474. this.handleButtonChange(buttonIndex, newState, this._changes);
  55475. }
  55476. this._buttons[buttonIndex].pressed = newState.pressed;
  55477. this._buttons[buttonIndex].touched = newState.touched;
  55478. // oculus triggers are never 0, thou not touched.
  55479. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  55480. };
  55481. WebVRController.prototype._checkChanges = function (newState, currentState) {
  55482. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  55483. this._changes.touchChanged = newState.touched !== currentState.touched;
  55484. this._changes.valueChanged = newState.value !== currentState.value;
  55485. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  55486. return this._changes;
  55487. };
  55488. WebVRController.prototype.dispose = function () {
  55489. _super.prototype.dispose.call(this);
  55490. this.onTriggerStateChangedObservable.clear();
  55491. this.onMainButtonStateChangedObservable.clear();
  55492. this.onSecondaryButtonStateChangedObservable.clear();
  55493. this.onPadStateChangedObservable.clear();
  55494. this.onPadValuesChangedObservable.clear();
  55495. };
  55496. return WebVRController;
  55497. }(BABYLON.PoseEnabledController));
  55498. BABYLON.WebVRController = WebVRController;
  55499. })(BABYLON || (BABYLON = {}));
  55500. //# sourceMappingURL=babylon.webVRController.js.map
  55501. var BABYLON;
  55502. (function (BABYLON) {
  55503. var OculusTouchController = /** @class */ (function (_super) {
  55504. __extends(OculusTouchController, _super);
  55505. function OculusTouchController(vrGamepad) {
  55506. var _this = _super.call(this, vrGamepad) || this;
  55507. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  55508. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  55509. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  55510. return _this;
  55511. }
  55512. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55513. var _this = this;
  55514. var meshName;
  55515. // Hand
  55516. if (this.hand === 'left') {
  55517. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  55518. }
  55519. else {
  55520. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  55521. }
  55522. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  55523. /*
  55524. Parent Mesh name: oculus_touch_left
  55525. - body
  55526. - trigger
  55527. - thumbstick
  55528. - grip
  55529. - button_y
  55530. - button_x
  55531. - button_enter
  55532. */
  55533. _this._defaultModel = newMeshes[1];
  55534. _this.attachToMesh(_this._defaultModel);
  55535. if (meshLoaded) {
  55536. meshLoaded(_this._defaultModel);
  55537. }
  55538. });
  55539. };
  55540. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  55541. // helper getters for left and right hand.
  55542. get: function () {
  55543. if (this.hand === 'right') {
  55544. return this.onMainButtonStateChangedObservable;
  55545. }
  55546. else {
  55547. throw new Error('No A button on left hand');
  55548. }
  55549. },
  55550. enumerable: true,
  55551. configurable: true
  55552. });
  55553. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  55554. get: function () {
  55555. if (this.hand === 'right') {
  55556. return this.onSecondaryButtonStateChangedObservable;
  55557. }
  55558. else {
  55559. throw new Error('No B button on left hand');
  55560. }
  55561. },
  55562. enumerable: true,
  55563. configurable: true
  55564. });
  55565. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  55566. get: function () {
  55567. if (this.hand === 'left') {
  55568. return this.onMainButtonStateChangedObservable;
  55569. }
  55570. else {
  55571. throw new Error('No X button on right hand');
  55572. }
  55573. },
  55574. enumerable: true,
  55575. configurable: true
  55576. });
  55577. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  55578. get: function () {
  55579. if (this.hand === 'left') {
  55580. return this.onSecondaryButtonStateChangedObservable;
  55581. }
  55582. else {
  55583. throw new Error('No Y button on right hand');
  55584. }
  55585. },
  55586. enumerable: true,
  55587. configurable: true
  55588. });
  55589. /*
  55590. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  55591. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  55592. 2) secondary trigger (same)
  55593. 3) A (right) X (left), touch, pressed = value
  55594. 4) B / Y
  55595. 5) thumb rest
  55596. */
  55597. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55598. var notifyObject = state; //{ state: state, changes: changes };
  55599. var triggerDirection = this.hand === 'right' ? -1 : 1;
  55600. switch (buttonIdx) {
  55601. case 0:
  55602. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55603. return;
  55604. case 1:// index trigger
  55605. if (this._defaultModel) {
  55606. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  55607. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  55608. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  55609. }
  55610. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55611. return;
  55612. case 2:// secondary trigger
  55613. if (this._defaultModel) {
  55614. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  55615. }
  55616. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  55617. return;
  55618. case 3:
  55619. if (this._defaultModel) {
  55620. if (notifyObject.pressed) {
  55621. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  55622. }
  55623. else {
  55624. (this._defaultModel.getChildren()[1]).position.y = 0;
  55625. }
  55626. }
  55627. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55628. return;
  55629. case 4:
  55630. if (this._defaultModel) {
  55631. if (notifyObject.pressed) {
  55632. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55633. }
  55634. else {
  55635. (this._defaultModel.getChildren()[2]).position.y = 0;
  55636. }
  55637. }
  55638. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55639. return;
  55640. case 5:
  55641. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  55642. return;
  55643. }
  55644. };
  55645. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  55646. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  55647. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  55648. return OculusTouchController;
  55649. }(BABYLON.WebVRController));
  55650. BABYLON.OculusTouchController = OculusTouchController;
  55651. })(BABYLON || (BABYLON = {}));
  55652. //# sourceMappingURL=babylon.oculusTouchController.js.map
  55653. var BABYLON;
  55654. (function (BABYLON) {
  55655. var ViveController = /** @class */ (function (_super) {
  55656. __extends(ViveController, _super);
  55657. function ViveController(vrGamepad) {
  55658. var _this = _super.call(this, vrGamepad) || this;
  55659. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  55660. return _this;
  55661. }
  55662. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55663. var _this = this;
  55664. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  55665. /*
  55666. Parent Mesh name: ViveWand
  55667. - body
  55668. - r_gripper
  55669. - l_gripper
  55670. - menu_button
  55671. - system_button
  55672. - trackpad
  55673. - trigger
  55674. - LED
  55675. */
  55676. _this._defaultModel = newMeshes[1];
  55677. _this.attachToMesh(_this._defaultModel);
  55678. if (meshLoaded) {
  55679. meshLoaded(_this._defaultModel);
  55680. }
  55681. });
  55682. };
  55683. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  55684. get: function () {
  55685. return this.onMainButtonStateChangedObservable;
  55686. },
  55687. enumerable: true,
  55688. configurable: true
  55689. });
  55690. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  55691. get: function () {
  55692. return this.onMainButtonStateChangedObservable;
  55693. },
  55694. enumerable: true,
  55695. configurable: true
  55696. });
  55697. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  55698. get: function () {
  55699. return this.onSecondaryButtonStateChangedObservable;
  55700. },
  55701. enumerable: true,
  55702. configurable: true
  55703. });
  55704. /**
  55705. * Vive mapping:
  55706. * 0: touchpad
  55707. * 1: trigger
  55708. * 2: left AND right buttons
  55709. * 3: menu button
  55710. */
  55711. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55712. var notifyObject = state; //{ state: state, changes: changes };
  55713. switch (buttonIdx) {
  55714. case 0:
  55715. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55716. return;
  55717. case 1:// index trigger
  55718. if (this._defaultModel) {
  55719. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  55720. }
  55721. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55722. return;
  55723. case 2:// left AND right button
  55724. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55725. return;
  55726. case 3:
  55727. if (this._defaultModel) {
  55728. if (notifyObject.pressed) {
  55729. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55730. }
  55731. else {
  55732. (this._defaultModel.getChildren()[2]).position.y = 0;
  55733. }
  55734. }
  55735. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55736. return;
  55737. }
  55738. };
  55739. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  55740. ViveController.MODEL_FILENAME = 'wand.babylon';
  55741. return ViveController;
  55742. }(BABYLON.WebVRController));
  55743. BABYLON.ViveController = ViveController;
  55744. })(BABYLON || (BABYLON = {}));
  55745. //# sourceMappingURL=babylon.viveController.js.map
  55746. var BABYLON;
  55747. (function (BABYLON) {
  55748. var GenericController = /** @class */ (function (_super) {
  55749. __extends(GenericController, _super);
  55750. function GenericController(vrGamepad) {
  55751. return _super.call(this, vrGamepad) || this;
  55752. }
  55753. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55754. var _this = this;
  55755. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  55756. _this._defaultModel = newMeshes[1];
  55757. _this.attachToMesh(_this._defaultModel);
  55758. if (meshLoaded) {
  55759. meshLoaded(_this._defaultModel);
  55760. }
  55761. });
  55762. };
  55763. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55764. console.log("Button id: " + buttonIdx + "state: ");
  55765. console.dir(state);
  55766. };
  55767. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  55768. GenericController.MODEL_FILENAME = 'generic.babylon';
  55769. return GenericController;
  55770. }(BABYLON.WebVRController));
  55771. BABYLON.GenericController = GenericController;
  55772. })(BABYLON || (BABYLON = {}));
  55773. //# sourceMappingURL=babylon.genericController.js.map
  55774. var BABYLON;
  55775. (function (BABYLON) {
  55776. var LoadedMeshInfo = /** @class */ (function () {
  55777. function LoadedMeshInfo() {
  55778. this.buttonMeshes = {};
  55779. this.axisMeshes = {};
  55780. }
  55781. return LoadedMeshInfo;
  55782. }());
  55783. var WindowsMotionController = /** @class */ (function (_super) {
  55784. __extends(WindowsMotionController, _super);
  55785. function WindowsMotionController(vrGamepad) {
  55786. var _this = _super.call(this, vrGamepad) || this;
  55787. _this._mapping = {
  55788. // Semantic button names
  55789. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  55790. // A mapping of the button name to glTF model node name
  55791. // that should be transformed by button value.
  55792. buttonMeshNames: {
  55793. 'trigger': 'SELECT',
  55794. 'menu': 'MENU',
  55795. 'grip': 'GRASP',
  55796. 'thumbstick': 'THUMBSTICK_PRESS',
  55797. 'trackpad': 'TOUCHPAD_PRESS'
  55798. },
  55799. // This mapping is used to translate from the Motion Controller to Babylon semantics
  55800. buttonObservableNames: {
  55801. 'trigger': 'onTriggerStateChangedObservable',
  55802. 'menu': 'onSecondaryButtonStateChangedObservable',
  55803. 'grip': 'onMainButtonStateChangedObservable',
  55804. 'thumbstick': 'onPadStateChangedObservable',
  55805. 'trackpad': 'onTrackpadChangedObservable'
  55806. },
  55807. // A mapping of the axis name to glTF model node name
  55808. // that should be transformed by axis value.
  55809. // This array mirrors the browserGamepad.axes array, such that
  55810. // the mesh corresponding to axis 0 is in this array index 0.
  55811. axisMeshNames: [
  55812. 'THUMBSTICK_X',
  55813. 'THUMBSTICK_Y',
  55814. 'TOUCHPAD_TOUCH_X',
  55815. 'TOUCHPAD_TOUCH_Y'
  55816. ],
  55817. pointingPoseMeshName: 'POINTING_POSE'
  55818. };
  55819. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  55820. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  55821. _this._loadedMeshInfo = null;
  55822. return _this;
  55823. }
  55824. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  55825. get: function () {
  55826. return this.onTriggerStateChangedObservable;
  55827. },
  55828. enumerable: true,
  55829. configurable: true
  55830. });
  55831. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  55832. get: function () {
  55833. return this.onSecondaryButtonStateChangedObservable;
  55834. },
  55835. enumerable: true,
  55836. configurable: true
  55837. });
  55838. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  55839. get: function () {
  55840. return this.onMainButtonStateChangedObservable;
  55841. },
  55842. enumerable: true,
  55843. configurable: true
  55844. });
  55845. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  55846. get: function () {
  55847. return this.onPadStateChangedObservable;
  55848. },
  55849. enumerable: true,
  55850. configurable: true
  55851. });
  55852. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  55853. get: function () {
  55854. return this.onTrackpadChangedObservable;
  55855. },
  55856. enumerable: true,
  55857. configurable: true
  55858. });
  55859. /**
  55860. * Called once per frame by the engine.
  55861. */
  55862. WindowsMotionController.prototype.update = function () {
  55863. _super.prototype.update.call(this);
  55864. // Only need to animate axes if there is a loaded mesh
  55865. if (this._loadedMeshInfo) {
  55866. if (this.browserGamepad.axes) {
  55867. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  55868. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  55869. }
  55870. }
  55871. }
  55872. };
  55873. /**
  55874. * Called once for each button that changed state since the last frame
  55875. * @param buttonIdx Which button index changed
  55876. * @param state New state of the button
  55877. * @param changes Which properties on the state changed since last frame
  55878. */
  55879. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55880. var buttonName = this._mapping.buttons[buttonIdx];
  55881. if (!buttonName) {
  55882. return;
  55883. }
  55884. // Only emit events for buttons that we know how to map from index to name
  55885. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  55886. if (observable) {
  55887. observable.notifyObservers(state);
  55888. }
  55889. this.lerpButtonTransform(buttonName, state.value);
  55890. };
  55891. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  55892. // If there is no loaded mesh, there is nothing to transform.
  55893. if (!this._loadedMeshInfo) {
  55894. return;
  55895. }
  55896. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  55897. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  55898. return;
  55899. }
  55900. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  55901. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  55902. };
  55903. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  55904. if (!this._loadedMeshInfo) {
  55905. return;
  55906. }
  55907. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  55908. if (!meshInfo) {
  55909. return;
  55910. }
  55911. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  55912. return;
  55913. }
  55914. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  55915. var lerpValue = axisValue * 0.5 + 0.5;
  55916. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  55917. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  55918. };
  55919. /**
  55920. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  55921. * @param scene scene in which to add meshes
  55922. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  55923. */
  55924. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  55925. var _this = this;
  55926. if (forceDefault === void 0) { forceDefault = false; }
  55927. var path;
  55928. var filename;
  55929. // Checking if GLB loader is present
  55930. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  55931. // Determine the device specific folder based on the ID suffix
  55932. var device = 'default';
  55933. if (this.id && !forceDefault) {
  55934. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  55935. device = ((match && match[0]) || device);
  55936. }
  55937. // Hand
  55938. if (this.hand === 'left') {
  55939. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  55940. }
  55941. else {
  55942. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  55943. }
  55944. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  55945. }
  55946. else {
  55947. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  55948. path = BABYLON.GenericController.MODEL_BASE_URL;
  55949. filename = BABYLON.GenericController.MODEL_FILENAME;
  55950. }
  55951. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  55952. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  55953. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  55954. if (!_this._loadedMeshInfo) {
  55955. return;
  55956. }
  55957. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  55958. _this.attachToMesh(_this._defaultModel);
  55959. if (meshLoaded) {
  55960. meshLoaded(_this._defaultModel);
  55961. }
  55962. }, null, function (scene, message) {
  55963. BABYLON.Tools.Log(message);
  55964. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  55965. if (!forceDefault) {
  55966. _this.initControllerMesh(scene, meshLoaded, true);
  55967. }
  55968. });
  55969. };
  55970. /**
  55971. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  55972. * can be transformed by button presses and axes values, based on this._mapping.
  55973. *
  55974. * @param scene scene in which the meshes exist
  55975. * @param meshes list of meshes that make up the controller model to process
  55976. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  55977. */
  55978. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  55979. var loadedMeshInfo = null;
  55980. // Create a new mesh to contain the glTF hierarchy
  55981. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  55982. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  55983. var childMesh = null;
  55984. for (var i = 0; i < meshes.length; i++) {
  55985. var mesh = meshes[i];
  55986. if (!mesh.parent) {
  55987. // Exclude controller meshes from picking results
  55988. mesh.isPickable = false;
  55989. // Handle root node, attach to the new parentMesh
  55990. childMesh = mesh;
  55991. break;
  55992. }
  55993. }
  55994. if (childMesh) {
  55995. childMesh.setParent(parentMesh);
  55996. // Create our mesh info. Note that this method will always return non-null.
  55997. loadedMeshInfo = this.createMeshInfo(parentMesh);
  55998. }
  55999. else {
  56000. BABYLON.Tools.Warn('Could not find root node in model file.');
  56001. }
  56002. return loadedMeshInfo;
  56003. };
  56004. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  56005. var loadedMeshInfo = new LoadedMeshInfo();
  56006. var i;
  56007. loadedMeshInfo.rootNode = rootNode;
  56008. // Reset the caches
  56009. loadedMeshInfo.buttonMeshes = {};
  56010. loadedMeshInfo.axisMeshes = {};
  56011. // Button Meshes
  56012. for (i = 0; i < this._mapping.buttons.length; i++) {
  56013. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56014. if (!buttonMeshName) {
  56015. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56016. continue;
  56017. }
  56018. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56019. if (!buttonMesh) {
  56020. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56021. continue;
  56022. }
  56023. var buttonMeshInfo = {
  56024. index: i,
  56025. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56026. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56027. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56028. };
  56029. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56030. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56031. }
  56032. else {
  56033. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56034. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56035. '(VALUE: ' + !!buttonMeshInfo.value +
  56036. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56037. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56038. ')');
  56039. }
  56040. }
  56041. // Axis Meshes
  56042. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56043. var axisMeshName = this._mapping.axisMeshNames[i];
  56044. if (!axisMeshName) {
  56045. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56046. continue;
  56047. }
  56048. var axisMesh = getChildByName(rootNode, axisMeshName);
  56049. if (!axisMesh) {
  56050. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56051. continue;
  56052. }
  56053. var axisMeshInfo = {
  56054. index: i,
  56055. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56056. min: getImmediateChildByName(axisMesh, 'MIN'),
  56057. max: getImmediateChildByName(axisMesh, 'MAX')
  56058. };
  56059. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  56060. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  56061. }
  56062. else {
  56063. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  56064. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  56065. '(VALUE: ' + !!axisMeshInfo.value +
  56066. ', MIN: ' + !!axisMeshInfo.min +
  56067. ', MAX:' + !!axisMeshInfo.max +
  56068. ')');
  56069. }
  56070. }
  56071. // Pointing Ray
  56072. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  56073. if (!loadedMeshInfo.pointingPoseNode) {
  56074. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  56075. }
  56076. return loadedMeshInfo;
  56077. // Look through all children recursively. This will return null if no mesh exists with the given name.
  56078. function getChildByName(node, name) {
  56079. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  56080. }
  56081. // Look through only immediate children. This will return null if no mesh exists with the given name.
  56082. function getImmediateChildByName(node, name) {
  56083. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  56084. }
  56085. };
  56086. WindowsMotionController.prototype.getForwardRay = function (length) {
  56087. if (length === void 0) { length = 100; }
  56088. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  56089. return _super.prototype.getForwardRay.call(this, length);
  56090. }
  56091. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  56092. var origin = m.getTranslation();
  56093. var forward = new BABYLON.Vector3(0, 0, -1);
  56094. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56095. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56096. return new BABYLON.Ray(origin, direction, length);
  56097. };
  56098. WindowsMotionController.prototype.dispose = function () {
  56099. _super.prototype.dispose.call(this);
  56100. this.onTrackpadChangedObservable.clear();
  56101. };
  56102. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  56103. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  56104. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  56105. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  56106. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  56107. return WindowsMotionController;
  56108. }(BABYLON.WebVRController));
  56109. BABYLON.WindowsMotionController = WindowsMotionController;
  56110. })(BABYLON || (BABYLON = {}));
  56111. //# sourceMappingURL=babylon.windowsMotionController.js.map
  56112. var BABYLON;
  56113. (function (BABYLON) {
  56114. var FollowCamera = /** @class */ (function (_super) {
  56115. __extends(FollowCamera, _super);
  56116. function FollowCamera(name, position, scene, lockedTarget) {
  56117. if (lockedTarget === void 0) { lockedTarget = null; }
  56118. var _this = _super.call(this, name, position, scene) || this;
  56119. _this.radius = 12;
  56120. _this.rotationOffset = 0;
  56121. _this.heightOffset = 4;
  56122. _this.cameraAcceleration = 0.05;
  56123. _this.maxCameraSpeed = 20;
  56124. _this.lockedTarget = lockedTarget;
  56125. return _this;
  56126. }
  56127. FollowCamera.prototype.getRadians = function (degrees) {
  56128. return degrees * Math.PI / 180;
  56129. };
  56130. FollowCamera.prototype.follow = function (cameraTarget) {
  56131. if (!cameraTarget)
  56132. return;
  56133. var yRotation;
  56134. if (cameraTarget.rotationQuaternion) {
  56135. var rotMatrix = new BABYLON.Matrix();
  56136. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  56137. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  56138. }
  56139. else {
  56140. yRotation = cameraTarget.rotation.y;
  56141. }
  56142. var radians = this.getRadians(this.rotationOffset) + yRotation;
  56143. var targetPosition = cameraTarget.getAbsolutePosition();
  56144. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  56145. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  56146. var dx = targetX - this.position.x;
  56147. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  56148. var dz = (targetZ) - this.position.z;
  56149. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  56150. var vy = dy * this.cameraAcceleration;
  56151. var vz = dz * this.cameraAcceleration * 2;
  56152. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  56153. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56154. }
  56155. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  56156. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56157. }
  56158. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  56159. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56160. }
  56161. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  56162. this.setTarget(targetPosition);
  56163. };
  56164. FollowCamera.prototype._checkInputs = function () {
  56165. _super.prototype._checkInputs.call(this);
  56166. if (this.lockedTarget) {
  56167. this.follow(this.lockedTarget);
  56168. }
  56169. };
  56170. FollowCamera.prototype.getClassName = function () {
  56171. return "FollowCamera";
  56172. };
  56173. __decorate([
  56174. BABYLON.serialize()
  56175. ], FollowCamera.prototype, "radius", void 0);
  56176. __decorate([
  56177. BABYLON.serialize()
  56178. ], FollowCamera.prototype, "rotationOffset", void 0);
  56179. __decorate([
  56180. BABYLON.serialize()
  56181. ], FollowCamera.prototype, "heightOffset", void 0);
  56182. __decorate([
  56183. BABYLON.serialize()
  56184. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  56185. __decorate([
  56186. BABYLON.serialize()
  56187. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  56188. __decorate([
  56189. BABYLON.serializeAsMeshReference("lockedTargetId")
  56190. ], FollowCamera.prototype, "lockedTarget", void 0);
  56191. return FollowCamera;
  56192. }(BABYLON.TargetCamera));
  56193. BABYLON.FollowCamera = FollowCamera;
  56194. var ArcFollowCamera = /** @class */ (function (_super) {
  56195. __extends(ArcFollowCamera, _super);
  56196. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  56197. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  56198. _this.alpha = alpha;
  56199. _this.beta = beta;
  56200. _this.radius = radius;
  56201. _this.target = target;
  56202. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  56203. _this.follow();
  56204. return _this;
  56205. }
  56206. ArcFollowCamera.prototype.follow = function () {
  56207. if (!this.target) {
  56208. return;
  56209. }
  56210. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  56211. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  56212. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  56213. var targetPosition = this.target.getAbsolutePosition();
  56214. this.position = targetPosition.add(this._cartesianCoordinates);
  56215. this.setTarget(targetPosition);
  56216. };
  56217. ArcFollowCamera.prototype._checkInputs = function () {
  56218. _super.prototype._checkInputs.call(this);
  56219. this.follow();
  56220. };
  56221. ArcFollowCamera.prototype.getClassName = function () {
  56222. return "ArcFollowCamera";
  56223. };
  56224. return ArcFollowCamera;
  56225. }(BABYLON.TargetCamera));
  56226. BABYLON.ArcFollowCamera = ArcFollowCamera;
  56227. })(BABYLON || (BABYLON = {}));
  56228. //# sourceMappingURL=babylon.followCamera.js.map
  56229. var BABYLON;
  56230. (function (BABYLON) {
  56231. // We're mainly based on the logic defined into the FreeCamera code
  56232. var UniversalCamera = /** @class */ (function (_super) {
  56233. __extends(UniversalCamera, _super);
  56234. //-- end properties for backward compatibility for inputs
  56235. function UniversalCamera(name, position, scene) {
  56236. var _this = _super.call(this, name, position, scene) || this;
  56237. _this.inputs.addGamepad();
  56238. return _this;
  56239. }
  56240. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  56241. //-- Begin properties for backward compatibility for inputs
  56242. get: function () {
  56243. var gamepad = this.inputs.attached["gamepad"];
  56244. if (gamepad)
  56245. return gamepad.gamepadAngularSensibility;
  56246. return 0;
  56247. },
  56248. set: function (value) {
  56249. var gamepad = this.inputs.attached["gamepad"];
  56250. if (gamepad)
  56251. gamepad.gamepadAngularSensibility = value;
  56252. },
  56253. enumerable: true,
  56254. configurable: true
  56255. });
  56256. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  56257. get: function () {
  56258. var gamepad = this.inputs.attached["gamepad"];
  56259. if (gamepad)
  56260. return gamepad.gamepadMoveSensibility;
  56261. return 0;
  56262. },
  56263. set: function (value) {
  56264. var gamepad = this.inputs.attached["gamepad"];
  56265. if (gamepad)
  56266. gamepad.gamepadMoveSensibility = value;
  56267. },
  56268. enumerable: true,
  56269. configurable: true
  56270. });
  56271. UniversalCamera.prototype.getClassName = function () {
  56272. return "UniversalCamera";
  56273. };
  56274. return UniversalCamera;
  56275. }(BABYLON.TouchCamera));
  56276. BABYLON.UniversalCamera = UniversalCamera;
  56277. })(BABYLON || (BABYLON = {}));
  56278. //# sourceMappingURL=babylon.universalCamera.js.map
  56279. var BABYLON;
  56280. (function (BABYLON) {
  56281. // We're mainly based on the logic defined into the FreeCamera code
  56282. var GamepadCamera = /** @class */ (function (_super) {
  56283. __extends(GamepadCamera, _super);
  56284. //-- end properties for backward compatibility for inputs
  56285. function GamepadCamera(name, position, scene) {
  56286. return _super.call(this, name, position, scene) || this;
  56287. }
  56288. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  56289. //-- Begin properties for backward compatibility for inputs
  56290. get: function () {
  56291. var gamepad = this.inputs.attached["gamepad"];
  56292. if (gamepad)
  56293. return gamepad.gamepadAngularSensibility;
  56294. return 0;
  56295. },
  56296. set: function (value) {
  56297. var gamepad = this.inputs.attached["gamepad"];
  56298. if (gamepad)
  56299. gamepad.gamepadAngularSensibility = value;
  56300. },
  56301. enumerable: true,
  56302. configurable: true
  56303. });
  56304. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  56305. get: function () {
  56306. var gamepad = this.inputs.attached["gamepad"];
  56307. if (gamepad)
  56308. return gamepad.gamepadMoveSensibility;
  56309. return 0;
  56310. },
  56311. set: function (value) {
  56312. var gamepad = this.inputs.attached["gamepad"];
  56313. if (gamepad)
  56314. gamepad.gamepadMoveSensibility = value;
  56315. },
  56316. enumerable: true,
  56317. configurable: true
  56318. });
  56319. GamepadCamera.prototype.getClassName = function () {
  56320. return "GamepadCamera";
  56321. };
  56322. return GamepadCamera;
  56323. }(BABYLON.UniversalCamera));
  56324. BABYLON.GamepadCamera = GamepadCamera;
  56325. })(BABYLON || (BABYLON = {}));
  56326. //# sourceMappingURL=babylon.gamepadCamera.js.map
  56327. var BABYLON;
  56328. (function (BABYLON) {
  56329. var PostProcessRenderPipelineManager = /** @class */ (function () {
  56330. function PostProcessRenderPipelineManager() {
  56331. this._renderPipelines = {};
  56332. }
  56333. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  56334. this._renderPipelines[renderPipeline._name] = renderPipeline;
  56335. };
  56336. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  56337. if (unique === void 0) { unique = false; }
  56338. var renderPipeline = this._renderPipelines[renderPipelineName];
  56339. if (!renderPipeline) {
  56340. return;
  56341. }
  56342. renderPipeline._attachCameras(cameras, unique);
  56343. };
  56344. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  56345. var renderPipeline = this._renderPipelines[renderPipelineName];
  56346. if (!renderPipeline) {
  56347. return;
  56348. }
  56349. renderPipeline._detachCameras(cameras);
  56350. };
  56351. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56352. var renderPipeline = this._renderPipelines[renderPipelineName];
  56353. if (!renderPipeline) {
  56354. return;
  56355. }
  56356. renderPipeline._enableEffect(renderEffectName, cameras);
  56357. };
  56358. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56359. var renderPipeline = this._renderPipelines[renderPipelineName];
  56360. if (!renderPipeline) {
  56361. return;
  56362. }
  56363. renderPipeline._disableEffect(renderEffectName, cameras);
  56364. };
  56365. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  56366. var renderPipeline = this._renderPipelines[renderPipelineName];
  56367. if (!renderPipeline) {
  56368. return;
  56369. }
  56370. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  56371. };
  56372. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  56373. var renderPipeline = this._renderPipelines[renderPipelineName];
  56374. if (!renderPipeline) {
  56375. return;
  56376. }
  56377. renderPipeline._disableDisplayOnlyPass(cameras);
  56378. };
  56379. PostProcessRenderPipelineManager.prototype.update = function () {
  56380. for (var renderPipelineName in this._renderPipelines) {
  56381. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56382. var pipeline = this._renderPipelines[renderPipelineName];
  56383. if (!pipeline.isSupported) {
  56384. pipeline.dispose();
  56385. delete this._renderPipelines[renderPipelineName];
  56386. }
  56387. else {
  56388. pipeline._update();
  56389. }
  56390. }
  56391. }
  56392. };
  56393. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  56394. for (var renderPipelineName in this._renderPipelines) {
  56395. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56396. var pipeline = this._renderPipelines[renderPipelineName];
  56397. pipeline._rebuild();
  56398. }
  56399. }
  56400. };
  56401. PostProcessRenderPipelineManager.prototype.dispose = function () {
  56402. for (var renderPipelineName in this._renderPipelines) {
  56403. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56404. var pipeline = this._renderPipelines[renderPipelineName];
  56405. pipeline.dispose();
  56406. }
  56407. }
  56408. };
  56409. return PostProcessRenderPipelineManager;
  56410. }());
  56411. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  56412. })(BABYLON || (BABYLON = {}));
  56413. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  56414. var BABYLON;
  56415. (function (BABYLON) {
  56416. var PostProcessRenderPass = /** @class */ (function () {
  56417. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  56418. this._refCount = 0;
  56419. this._name = name;
  56420. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  56421. this.setRenderList(renderList);
  56422. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  56423. this._renderTexture.onAfterRenderObservable.add(afterRender);
  56424. this._scene = scene;
  56425. this._renderList = renderList;
  56426. }
  56427. // private
  56428. PostProcessRenderPass.prototype._incRefCount = function () {
  56429. if (this._refCount === 0) {
  56430. this._scene.customRenderTargets.push(this._renderTexture);
  56431. }
  56432. return ++this._refCount;
  56433. };
  56434. PostProcessRenderPass.prototype._decRefCount = function () {
  56435. this._refCount--;
  56436. if (this._refCount <= 0) {
  56437. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  56438. }
  56439. return this._refCount;
  56440. };
  56441. PostProcessRenderPass.prototype._update = function () {
  56442. this.setRenderList(this._renderList);
  56443. };
  56444. // public
  56445. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  56446. this._renderTexture.renderList = renderList;
  56447. };
  56448. PostProcessRenderPass.prototype.getRenderTexture = function () {
  56449. return this._renderTexture;
  56450. };
  56451. return PostProcessRenderPass;
  56452. }());
  56453. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  56454. })(BABYLON || (BABYLON = {}));
  56455. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  56456. var BABYLON;
  56457. (function (BABYLON) {
  56458. var PostProcessRenderEffect = /** @class */ (function () {
  56459. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  56460. this._engine = engine;
  56461. this._name = name;
  56462. this._singleInstance = singleInstance || true;
  56463. this._getPostProcess = getPostProcess;
  56464. this._cameras = {};
  56465. this._indicesForCamera = {};
  56466. this._postProcesses = {};
  56467. this._renderPasses = {};
  56468. this._renderEffectAsPasses = {};
  56469. }
  56470. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  56471. get: function () {
  56472. for (var index in this._postProcesses) {
  56473. if (!this._postProcesses[index].isSupported) {
  56474. return false;
  56475. }
  56476. }
  56477. return true;
  56478. },
  56479. enumerable: true,
  56480. configurable: true
  56481. });
  56482. PostProcessRenderEffect.prototype._update = function () {
  56483. for (var renderPassName in this._renderPasses) {
  56484. this._renderPasses[renderPassName]._update();
  56485. }
  56486. };
  56487. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  56488. this._renderPasses[renderPass._name] = renderPass;
  56489. this._linkParameters();
  56490. };
  56491. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  56492. delete this._renderPasses[renderPass._name];
  56493. this._linkParameters();
  56494. };
  56495. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  56496. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  56497. this._linkParameters();
  56498. };
  56499. PostProcessRenderEffect.prototype.getPass = function (passName) {
  56500. for (var renderPassName in this._renderPasses) {
  56501. if (renderPassName === passName) {
  56502. return this._renderPasses[passName];
  56503. }
  56504. }
  56505. return null;
  56506. };
  56507. PostProcessRenderEffect.prototype.emptyPasses = function () {
  56508. this._renderPasses = {};
  56509. this._linkParameters();
  56510. };
  56511. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  56512. var cameraKey;
  56513. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56514. if (!cams) {
  56515. return;
  56516. }
  56517. for (var i = 0; i < cams.length; i++) {
  56518. var camera = cams[i];
  56519. var cameraName = camera.name;
  56520. if (this._singleInstance) {
  56521. cameraKey = 0;
  56522. }
  56523. else {
  56524. cameraKey = cameraName;
  56525. }
  56526. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  56527. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  56528. if (!this._indicesForCamera[cameraName]) {
  56529. this._indicesForCamera[cameraName] = [];
  56530. }
  56531. this._indicesForCamera[cameraName].push(index);
  56532. if (!this._cameras[cameraName]) {
  56533. this._cameras[cameraName] = camera;
  56534. }
  56535. for (var passName in this._renderPasses) {
  56536. this._renderPasses[passName]._incRefCount();
  56537. }
  56538. }
  56539. this._linkParameters();
  56540. };
  56541. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  56542. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56543. if (!cams) {
  56544. return;
  56545. }
  56546. for (var i = 0; i < cams.length; i++) {
  56547. var camera = cams[i];
  56548. var cameraName = camera.name;
  56549. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56550. if (this._cameras[cameraName]) {
  56551. //this._indicesForCamera.splice(index, 1);
  56552. this._cameras[cameraName] = null;
  56553. }
  56554. for (var passName in this._renderPasses) {
  56555. this._renderPasses[passName]._decRefCount();
  56556. }
  56557. }
  56558. };
  56559. PostProcessRenderEffect.prototype._enable = function (cameras) {
  56560. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56561. if (!cams) {
  56562. return;
  56563. }
  56564. for (var i = 0; i < cams.length; i++) {
  56565. var camera = cams[i];
  56566. var cameraName = camera.name;
  56567. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  56568. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  56569. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  56570. }
  56571. }
  56572. for (var passName in this._renderPasses) {
  56573. this._renderPasses[passName]._incRefCount();
  56574. }
  56575. }
  56576. };
  56577. PostProcessRenderEffect.prototype._disable = function (cameras) {
  56578. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56579. if (!cams) {
  56580. return;
  56581. }
  56582. for (var i = 0; i < cams.length; i++) {
  56583. var camera = cams[i];
  56584. var cameraName = camera.Name;
  56585. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56586. for (var passName in this._renderPasses) {
  56587. this._renderPasses[passName]._decRefCount();
  56588. }
  56589. }
  56590. };
  56591. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  56592. if (this._singleInstance) {
  56593. return this._postProcesses[0];
  56594. }
  56595. else {
  56596. if (!camera) {
  56597. return null;
  56598. }
  56599. return this._postProcesses[camera.name];
  56600. }
  56601. };
  56602. PostProcessRenderEffect.prototype._linkParameters = function () {
  56603. var _this = this;
  56604. for (var index in this._postProcesses) {
  56605. if (this.applyParameters) {
  56606. this.applyParameters(this._postProcesses[index]);
  56607. }
  56608. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  56609. _this._linkTextures(effect);
  56610. });
  56611. }
  56612. };
  56613. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  56614. for (var renderPassName in this._renderPasses) {
  56615. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  56616. }
  56617. for (var renderEffectName in this._renderEffectAsPasses) {
  56618. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  56619. }
  56620. };
  56621. return PostProcessRenderEffect;
  56622. }());
  56623. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  56624. })(BABYLON || (BABYLON = {}));
  56625. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  56626. var BABYLON;
  56627. (function (BABYLON) {
  56628. var PostProcessRenderPipeline = /** @class */ (function () {
  56629. function PostProcessRenderPipeline(engine, name) {
  56630. this._engine = engine;
  56631. this._name = name;
  56632. this._renderEffects = {};
  56633. this._renderEffectsForIsolatedPass = new Array();
  56634. this._cameras = [];
  56635. }
  56636. PostProcessRenderPipeline.prototype.getClassName = function () {
  56637. return "PostProcessRenderPipeline";
  56638. };
  56639. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  56640. get: function () {
  56641. for (var renderEffectName in this._renderEffects) {
  56642. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56643. if (!this._renderEffects[renderEffectName].isSupported) {
  56644. return false;
  56645. }
  56646. }
  56647. }
  56648. return true;
  56649. },
  56650. enumerable: true,
  56651. configurable: true
  56652. });
  56653. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  56654. this._renderEffects[renderEffect._name] = renderEffect;
  56655. };
  56656. // private
  56657. PostProcessRenderPipeline.prototype._rebuild = function () {
  56658. };
  56659. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  56660. var renderEffects = this._renderEffects[renderEffectName];
  56661. if (!renderEffects) {
  56662. return;
  56663. }
  56664. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56665. };
  56666. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  56667. var renderEffects = this._renderEffects[renderEffectName];
  56668. if (!renderEffects) {
  56669. return;
  56670. }
  56671. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56672. };
  56673. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  56674. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56675. if (!cams) {
  56676. return;
  56677. }
  56678. var indicesToDelete = [];
  56679. var i;
  56680. for (i = 0; i < cams.length; i++) {
  56681. var camera = cams[i];
  56682. var cameraName = camera.name;
  56683. if (this._cameras.indexOf(camera) === -1) {
  56684. this._cameras[cameraName] = camera;
  56685. }
  56686. else if (unique) {
  56687. indicesToDelete.push(i);
  56688. }
  56689. }
  56690. for (i = 0; i < indicesToDelete.length; i++) {
  56691. cameras.splice(indicesToDelete[i], 1);
  56692. }
  56693. for (var renderEffectName in this._renderEffects) {
  56694. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56695. this._renderEffects[renderEffectName]._attachCameras(cams);
  56696. }
  56697. }
  56698. };
  56699. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  56700. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56701. if (!cams) {
  56702. return;
  56703. }
  56704. for (var renderEffectName in this._renderEffects) {
  56705. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56706. this._renderEffects[renderEffectName]._detachCameras(cams);
  56707. }
  56708. }
  56709. for (var i = 0; i < cams.length; i++) {
  56710. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  56711. }
  56712. };
  56713. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  56714. var _this = this;
  56715. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56716. if (!cams) {
  56717. return;
  56718. }
  56719. var pass = null;
  56720. var renderEffectName;
  56721. for (renderEffectName in this._renderEffects) {
  56722. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56723. pass = this._renderEffects[renderEffectName].getPass(passName);
  56724. if (pass != null) {
  56725. break;
  56726. }
  56727. }
  56728. }
  56729. if (pass === null) {
  56730. return;
  56731. }
  56732. for (renderEffectName in this._renderEffects) {
  56733. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56734. this._renderEffects[renderEffectName]._disable(cams);
  56735. }
  56736. }
  56737. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  56738. for (var i = 0; i < cams.length; i++) {
  56739. var camera = cams[i];
  56740. var cameraName = camera.name;
  56741. 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); });
  56742. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  56743. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  56744. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  56745. }
  56746. };
  56747. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  56748. var _this = this;
  56749. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56750. if (!cams) {
  56751. return;
  56752. }
  56753. for (var i = 0; i < cams.length; i++) {
  56754. var camera = cams[i];
  56755. var cameraName = camera.name;
  56756. 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); });
  56757. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  56758. }
  56759. for (var renderEffectName in this._renderEffects) {
  56760. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56761. this._renderEffects[renderEffectName]._enable(cams);
  56762. }
  56763. }
  56764. };
  56765. PostProcessRenderPipeline.prototype._update = function () {
  56766. for (var renderEffectName in this._renderEffects) {
  56767. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56768. this._renderEffects[renderEffectName]._update();
  56769. }
  56770. }
  56771. for (var i = 0; i < this._cameras.length; i++) {
  56772. var cameraName = this._cameras[i].name;
  56773. if (this._renderEffectsForIsolatedPass[cameraName]) {
  56774. this._renderEffectsForIsolatedPass[cameraName]._update();
  56775. }
  56776. }
  56777. };
  56778. PostProcessRenderPipeline.prototype._reset = function () {
  56779. this._renderEffects = {};
  56780. this._renderEffectsForIsolatedPass = new Array();
  56781. };
  56782. PostProcessRenderPipeline.prototype.dispose = function () {
  56783. // Must be implemented by children
  56784. };
  56785. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  56786. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  56787. __decorate([
  56788. BABYLON.serialize()
  56789. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  56790. return PostProcessRenderPipeline;
  56791. }());
  56792. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  56793. })(BABYLON || (BABYLON = {}));
  56794. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  56795. var BABYLON;
  56796. (function (BABYLON) {
  56797. var DepthRenderer = /** @class */ (function () {
  56798. function DepthRenderer(scene, type) {
  56799. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  56800. var _this = this;
  56801. this._scene = scene;
  56802. var engine = scene.getEngine();
  56803. // Render target
  56804. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  56805. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56806. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56807. this._depthMap.refreshRate = 1;
  56808. this._depthMap.renderParticles = false;
  56809. this._depthMap.renderList = null;
  56810. // set default depth value to 1.0 (far away)
  56811. this._depthMap.onClearObservable.add(function (engine) {
  56812. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56813. });
  56814. // Custom render function
  56815. var renderSubMesh = function (subMesh) {
  56816. var mesh = subMesh.getRenderingMesh();
  56817. var scene = _this._scene;
  56818. var engine = scene.getEngine();
  56819. var material = subMesh.getMaterial();
  56820. if (!material) {
  56821. return;
  56822. }
  56823. // Culling
  56824. engine.setState(material.backFaceCulling);
  56825. // Managing instances
  56826. var batch = mesh._getInstancesRenderList(subMesh._id);
  56827. if (batch.mustReturn) {
  56828. return;
  56829. }
  56830. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  56831. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  56832. engine.enableEffect(_this._effect);
  56833. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  56834. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  56835. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  56836. // Alpha test
  56837. if (material && material.needAlphaTesting()) {
  56838. var alphaTexture = material.getAlphaTestTexture();
  56839. if (alphaTexture) {
  56840. _this._effect.setTexture("diffuseSampler", alphaTexture);
  56841. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56842. }
  56843. }
  56844. // Bones
  56845. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  56846. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  56847. }
  56848. // Draw
  56849. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  56850. }
  56851. };
  56852. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56853. var index;
  56854. if (depthOnlySubMeshes.length) {
  56855. engine.setColorWrite(false);
  56856. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56857. renderSubMesh(depthOnlySubMeshes.data[index]);
  56858. }
  56859. engine.setColorWrite(true);
  56860. }
  56861. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56862. renderSubMesh(opaqueSubMeshes.data[index]);
  56863. }
  56864. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56865. renderSubMesh(alphaTestSubMeshes.data[index]);
  56866. }
  56867. };
  56868. }
  56869. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  56870. var material = subMesh.getMaterial();
  56871. if (material.disableDepthWrite) {
  56872. return false;
  56873. }
  56874. var defines = [];
  56875. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56876. var mesh = subMesh.getMesh();
  56877. // Alpha test
  56878. if (material && material.needAlphaTesting()) {
  56879. defines.push("#define ALPHATEST");
  56880. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56881. attribs.push(BABYLON.VertexBuffer.UVKind);
  56882. defines.push("#define UV1");
  56883. }
  56884. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56885. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56886. defines.push("#define UV2");
  56887. }
  56888. }
  56889. // Bones
  56890. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56891. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56892. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56893. if (mesh.numBoneInfluencers > 4) {
  56894. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56895. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56896. }
  56897. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56898. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  56899. }
  56900. else {
  56901. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56902. }
  56903. // Instances
  56904. if (useInstances) {
  56905. defines.push("#define INSTANCES");
  56906. attribs.push("world0");
  56907. attribs.push("world1");
  56908. attribs.push("world2");
  56909. attribs.push("world3");
  56910. }
  56911. // Get correct effect
  56912. var join = defines.join("\n");
  56913. if (this._cachedDefines !== join) {
  56914. this._cachedDefines = join;
  56915. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  56916. }
  56917. return this._effect.isReady();
  56918. };
  56919. DepthRenderer.prototype.getDepthMap = function () {
  56920. return this._depthMap;
  56921. };
  56922. // Methods
  56923. DepthRenderer.prototype.dispose = function () {
  56924. this._depthMap.dispose();
  56925. };
  56926. return DepthRenderer;
  56927. }());
  56928. BABYLON.DepthRenderer = DepthRenderer;
  56929. })(BABYLON || (BABYLON = {}));
  56930. //# sourceMappingURL=babylon.depthRenderer.js.map
  56931. var BABYLON;
  56932. (function (BABYLON) {
  56933. var SSAORenderingPipeline = /** @class */ (function (_super) {
  56934. __extends(SSAORenderingPipeline, _super);
  56935. /**
  56936. * @constructor
  56937. * @param {string} name - The rendering pipeline name
  56938. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56939. * @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 }
  56940. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56941. */
  56942. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  56943. var _this = _super.call(this, scene.getEngine(), name) || this;
  56944. // Members
  56945. /**
  56946. * The PassPostProcess id in the pipeline that contains the original scene color
  56947. * @type {string}
  56948. */
  56949. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  56950. /**
  56951. * The SSAO PostProcess id in the pipeline
  56952. * @type {string}
  56953. */
  56954. _this.SSAORenderEffect = "SSAORenderEffect";
  56955. /**
  56956. * The horizontal blur PostProcess id in the pipeline
  56957. * @type {string}
  56958. */
  56959. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  56960. /**
  56961. * The vertical blur PostProcess id in the pipeline
  56962. * @type {string}
  56963. */
  56964. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  56965. /**
  56966. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  56967. * @type {string}
  56968. */
  56969. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  56970. /**
  56971. * The output strength of the SSAO post-process. Default value is 1.0.
  56972. * @type {number}
  56973. */
  56974. _this.totalStrength = 1.0;
  56975. /**
  56976. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  56977. * @type {number}
  56978. */
  56979. _this.radius = 0.0001;
  56980. /**
  56981. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  56982. * Must not be equal to fallOff and superior to fallOff.
  56983. * Default value is 0.975
  56984. * @type {number}
  56985. */
  56986. _this.area = 0.0075;
  56987. /**
  56988. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  56989. * Must not be equal to area and inferior to area.
  56990. * Default value is 0.0
  56991. * @type {number}
  56992. */
  56993. _this.fallOff = 0.000001;
  56994. /**
  56995. * The base color of the SSAO post-process
  56996. * The final result is "base + ssao" between [0, 1]
  56997. * @type {number}
  56998. */
  56999. _this.base = 0.5;
  57000. _this._firstUpdate = true;
  57001. _this._scene = scene;
  57002. // Set up assets
  57003. _this._createRandomTexture();
  57004. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57005. var ssaoRatio = ratio.ssaoRatio || ratio;
  57006. var combineRatio = ratio.combineRatio || ratio;
  57007. _this._ratio = {
  57008. ssaoRatio: ssaoRatio,
  57009. combineRatio: combineRatio
  57010. };
  57011. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57012. _this._createSSAOPostProcess(ssaoRatio);
  57013. _this._createBlurPostProcess(ssaoRatio);
  57014. _this._createSSAOCombinePostProcess(combineRatio);
  57015. // Set up pipeline
  57016. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57017. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57018. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57019. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57020. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57021. // Finish
  57022. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57023. if (cameras)
  57024. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57025. return _this;
  57026. }
  57027. // Public Methods
  57028. /**
  57029. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57030. */
  57031. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57032. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57033. for (var i = 0; i < this._scene.cameras.length; i++) {
  57034. var camera = this._scene.cameras[i];
  57035. this._originalColorPostProcess.dispose(camera);
  57036. this._ssaoPostProcess.dispose(camera);
  57037. this._blurHPostProcess.dispose(camera);
  57038. this._blurVPostProcess.dispose(camera);
  57039. this._ssaoCombinePostProcess.dispose(camera);
  57040. }
  57041. this._randomTexture.dispose();
  57042. if (disableDepthRender)
  57043. this._scene.disableDepthRenderer();
  57044. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57045. _super.prototype.dispose.call(this);
  57046. };
  57047. // Private Methods
  57048. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57049. var _this = this;
  57050. /*
  57051. var samplerOffsets = [
  57052. -8.0, -6.0, -4.0, -2.0,
  57053. 0.0,
  57054. 2.0, 4.0, 6.0, 8.0
  57055. ];
  57056. */
  57057. var samplerOffsets = new Array();
  57058. for (var i = -8; i < 8; i++) {
  57059. samplerOffsets.push(i * 2);
  57060. }
  57061. 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");
  57062. this._blurHPostProcess.onApply = function (effect) {
  57063. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57064. effect.setTexture("depthSampler", _this._depthTexture);
  57065. if (_this._firstUpdate) {
  57066. effect.setArray("samplerOffsets", samplerOffsets);
  57067. }
  57068. };
  57069. 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");
  57070. this._blurVPostProcess.onApply = function (effect) {
  57071. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57072. effect.setTexture("depthSampler", _this._depthTexture);
  57073. if (_this._firstUpdate) {
  57074. effect.setArray("samplerOffsets", samplerOffsets);
  57075. _this._firstUpdate = false;
  57076. }
  57077. };
  57078. };
  57079. SSAORenderingPipeline.prototype._rebuild = function () {
  57080. this._firstUpdate = true;
  57081. _super.prototype._rebuild.call(this);
  57082. };
  57083. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57084. var _this = this;
  57085. var numSamples = 16;
  57086. var sampleSphere = [
  57087. 0.5381, 0.1856, -0.4319,
  57088. 0.1379, 0.2486, 0.4430,
  57089. 0.3371, 0.5679, -0.0057,
  57090. -0.6999, -0.0451, -0.0019,
  57091. 0.0689, -0.1598, -0.8547,
  57092. 0.0560, 0.0069, -0.1843,
  57093. -0.0146, 0.1402, 0.0762,
  57094. 0.0100, -0.1924, -0.0344,
  57095. -0.3577, -0.5301, -0.4358,
  57096. -0.3169, 0.1063, 0.0158,
  57097. 0.0103, -0.5869, 0.0046,
  57098. -0.0897, -0.4940, 0.3287,
  57099. 0.7119, -0.0154, -0.0918,
  57100. -0.0533, 0.0596, -0.5411,
  57101. 0.0352, -0.0631, 0.5460,
  57102. -0.4776, 0.2847, -0.0271
  57103. ];
  57104. var samplesFactor = 1.0 / numSamples;
  57105. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  57106. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57107. "area", "fallOff", "base", "range", "viewport"
  57108. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57109. this._ssaoPostProcess.onApply = function (effect) {
  57110. if (_this._firstUpdate) {
  57111. effect.setArray3("sampleSphere", sampleSphere);
  57112. effect.setFloat("samplesFactor", samplesFactor);
  57113. effect.setFloat("randTextureTiles", 4.0);
  57114. }
  57115. effect.setFloat("totalStrength", _this.totalStrength);
  57116. effect.setFloat("radius", _this.radius);
  57117. effect.setFloat("area", _this.area);
  57118. effect.setFloat("fallOff", _this.fallOff);
  57119. effect.setFloat("base", _this.base);
  57120. effect.setTexture("textureSampler", _this._depthTexture);
  57121. effect.setTexture("randomSampler", _this._randomTexture);
  57122. };
  57123. };
  57124. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57125. var _this = this;
  57126. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57127. this._ssaoCombinePostProcess.onApply = function (effect) {
  57128. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57129. };
  57130. };
  57131. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  57132. var size = 512;
  57133. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57134. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57135. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57136. var context = this._randomTexture.getContext();
  57137. var rand = function (min, max) {
  57138. return Math.random() * (max - min) + min;
  57139. };
  57140. var randVector = BABYLON.Vector3.Zero();
  57141. for (var x = 0; x < size; x++) {
  57142. for (var y = 0; y < size; y++) {
  57143. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  57144. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  57145. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  57146. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57147. context.fillRect(x, y, 1, 1);
  57148. }
  57149. }
  57150. this._randomTexture.update(false);
  57151. };
  57152. __decorate([
  57153. BABYLON.serialize()
  57154. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  57155. __decorate([
  57156. BABYLON.serialize()
  57157. ], SSAORenderingPipeline.prototype, "radius", void 0);
  57158. __decorate([
  57159. BABYLON.serialize()
  57160. ], SSAORenderingPipeline.prototype, "area", void 0);
  57161. __decorate([
  57162. BABYLON.serialize()
  57163. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  57164. __decorate([
  57165. BABYLON.serialize()
  57166. ], SSAORenderingPipeline.prototype, "base", void 0);
  57167. __decorate([
  57168. BABYLON.serialize()
  57169. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  57170. return SSAORenderingPipeline;
  57171. }(BABYLON.PostProcessRenderPipeline));
  57172. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  57173. })(BABYLON || (BABYLON = {}));
  57174. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  57175. var BABYLON;
  57176. (function (BABYLON) {
  57177. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  57178. __extends(SSAO2RenderingPipeline, _super);
  57179. /**
  57180. * @constructor
  57181. * @param {string} name - The rendering pipeline name
  57182. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57183. * @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 }
  57184. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57185. */
  57186. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  57187. var _this = _super.call(this, scene.getEngine(), name) || this;
  57188. // Members
  57189. /**
  57190. * The PassPostProcess id in the pipeline that contains the original scene color
  57191. * @type {string}
  57192. */
  57193. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57194. /**
  57195. * The SSAO PostProcess id in the pipeline
  57196. * @type {string}
  57197. */
  57198. _this.SSAORenderEffect = "SSAORenderEffect";
  57199. /**
  57200. * The horizontal blur PostProcess id in the pipeline
  57201. * @type {string}
  57202. */
  57203. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57204. /**
  57205. * The vertical blur PostProcess id in the pipeline
  57206. * @type {string}
  57207. */
  57208. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57209. /**
  57210. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57211. * @type {string}
  57212. */
  57213. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57214. /**
  57215. * The output strength of the SSAO post-process. Default value is 1.0.
  57216. * @type {number}
  57217. */
  57218. _this.totalStrength = 1.0;
  57219. /**
  57220. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  57221. * @type {number}
  57222. */
  57223. _this.maxZ = 100.0;
  57224. /**
  57225. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  57226. * @type {number}
  57227. */
  57228. _this.minZAspect = 0.2;
  57229. /**
  57230. * Number of samples used for the SSAO calculations. Default value is 8
  57231. * @type {number}
  57232. */
  57233. _this._samples = 8;
  57234. /**
  57235. * Are we using bilateral blur ?
  57236. * @type {boolean}
  57237. */
  57238. _this._expensiveBlur = true;
  57239. /**
  57240. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  57241. * @type {number}
  57242. */
  57243. _this.radius = 2.0;
  57244. /**
  57245. * The base color of the SSAO post-process
  57246. * The final result is "base + ssao" between [0, 1]
  57247. * @type {number}
  57248. */
  57249. _this.base = 0.1;
  57250. _this._firstUpdate = true;
  57251. _this._scene = scene;
  57252. if (!_this.isSupported) {
  57253. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  57254. return _this;
  57255. }
  57256. var ssaoRatio = ratio.ssaoRatio || ratio;
  57257. var blurRatio = ratio.blurRatio || ratio;
  57258. _this._ratio = {
  57259. ssaoRatio: ssaoRatio,
  57260. blurRatio: blurRatio
  57261. };
  57262. // Set up assets
  57263. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  57264. _this._createRandomTexture();
  57265. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  57266. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  57267. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57268. _this._createSSAOPostProcess(1.0);
  57269. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  57270. _this._createSSAOCombinePostProcess(blurRatio);
  57271. // Set up pipeline
  57272. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57273. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57274. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57275. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57276. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57277. // Finish
  57278. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57279. if (cameras)
  57280. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57281. return _this;
  57282. }
  57283. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  57284. get: function () {
  57285. return this._samples;
  57286. },
  57287. set: function (n) {
  57288. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  57289. this._samples = n;
  57290. this._sampleSphere = this._generateHemisphere();
  57291. this._firstUpdate = true;
  57292. },
  57293. enumerable: true,
  57294. configurable: true
  57295. });
  57296. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  57297. get: function () {
  57298. return this._expensiveBlur;
  57299. },
  57300. set: function (b) {
  57301. 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"]);
  57302. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  57303. this._expensiveBlur = b;
  57304. this._firstUpdate = true;
  57305. },
  57306. enumerable: true,
  57307. configurable: true
  57308. });
  57309. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  57310. /**
  57311. * Support test.
  57312. * @type {boolean}
  57313. */
  57314. get: function () {
  57315. var engine = BABYLON.Engine.LastCreatedEngine;
  57316. if (!engine) {
  57317. return false;
  57318. }
  57319. return engine.getCaps().drawBuffersExtension;
  57320. },
  57321. enumerable: true,
  57322. configurable: true
  57323. });
  57324. // Public Methods
  57325. /**
  57326. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57327. */
  57328. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  57329. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  57330. for (var i = 0; i < this._scene.cameras.length; i++) {
  57331. var camera = this._scene.cameras[i];
  57332. this._originalColorPostProcess.dispose(camera);
  57333. this._ssaoPostProcess.dispose(camera);
  57334. this._blurHPostProcess.dispose(camera);
  57335. this._blurVPostProcess.dispose(camera);
  57336. this._ssaoCombinePostProcess.dispose(camera);
  57337. }
  57338. this._randomTexture.dispose();
  57339. if (disableGeometryBufferRenderer)
  57340. this._scene.disableGeometryBufferRenderer();
  57341. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57342. _super.prototype.dispose.call(this);
  57343. };
  57344. // Private Methods
  57345. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  57346. var _this = this;
  57347. this._samplerOffsets = [];
  57348. var expensive = this.expensiveBlur;
  57349. for (var i = -8; i < 8; i++) {
  57350. this._samplerOffsets.push(i * 2 + 0.5);
  57351. }
  57352. 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");
  57353. this._blurHPostProcess.onApply = function (effect) {
  57354. if (!_this._scene.activeCamera) {
  57355. return;
  57356. }
  57357. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57358. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57359. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57360. effect.setFloat("radius", _this.radius);
  57361. effect.setTexture("depthSampler", _this._depthTexture);
  57362. if (_this._firstUpdate) {
  57363. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57364. }
  57365. };
  57366. 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");
  57367. this._blurVPostProcess.onApply = function (effect) {
  57368. if (!_this._scene.activeCamera) {
  57369. return;
  57370. }
  57371. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57372. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57373. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57374. effect.setFloat("radius", _this.radius);
  57375. effect.setTexture("depthSampler", _this._depthTexture);
  57376. if (_this._firstUpdate) {
  57377. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57378. _this._firstUpdate = false;
  57379. }
  57380. };
  57381. };
  57382. SSAO2RenderingPipeline.prototype._rebuild = function () {
  57383. this._firstUpdate = true;
  57384. _super.prototype._rebuild.call(this);
  57385. };
  57386. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  57387. var numSamples = this.samples;
  57388. var result = [];
  57389. var vector, scale;
  57390. var rand = function (min, max) {
  57391. return Math.random() * (max - min) + min;
  57392. };
  57393. var i = 0;
  57394. while (i < numSamples) {
  57395. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  57396. vector.normalize();
  57397. scale = i / numSamples;
  57398. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  57399. vector.scaleInPlace(scale);
  57400. result.push(vector.x, vector.y, vector.z);
  57401. i++;
  57402. }
  57403. return result;
  57404. };
  57405. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57406. var _this = this;
  57407. var numSamples = this.samples;
  57408. this._sampleSphere = this._generateHemisphere();
  57409. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  57410. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57411. "base", "range", "projection", "near", "far", "texelSize",
  57412. "xViewport", "yViewport", "maxZ", "minZAspect"
  57413. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57414. this._ssaoPostProcess.onApply = function (effect) {
  57415. if (_this._firstUpdate) {
  57416. effect.setArray3("sampleSphere", _this._sampleSphere);
  57417. effect.setFloat("randTextureTiles", 4.0);
  57418. }
  57419. if (!_this._scene.activeCamera) {
  57420. return;
  57421. }
  57422. effect.setFloat("samplesFactor", 1 / _this.samples);
  57423. effect.setFloat("totalStrength", _this.totalStrength);
  57424. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  57425. effect.setFloat("radius", _this.radius);
  57426. effect.setFloat("maxZ", _this.maxZ);
  57427. effect.setFloat("minZAspect", _this.minZAspect);
  57428. effect.setFloat("base", _this.base);
  57429. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57430. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57431. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  57432. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  57433. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  57434. effect.setTexture("textureSampler", _this._depthTexture);
  57435. effect.setTexture("normalSampler", _this._normalTexture);
  57436. effect.setTexture("randomSampler", _this._randomTexture);
  57437. };
  57438. };
  57439. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57440. var _this = this;
  57441. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57442. this._ssaoCombinePostProcess.onApply = function (effect) {
  57443. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57444. };
  57445. };
  57446. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  57447. var size = 512;
  57448. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57449. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57450. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57451. var context = this._randomTexture.getContext();
  57452. var rand = function (min, max) {
  57453. return Math.random() * (max - min) + min;
  57454. };
  57455. var randVector = BABYLON.Vector3.Zero();
  57456. for (var x = 0; x < size; x++) {
  57457. for (var y = 0; y < size; y++) {
  57458. randVector.x = rand(0.0, 1.0);
  57459. randVector.y = rand(0.0, 1.0);
  57460. randVector.z = 0.0;
  57461. randVector.normalize();
  57462. randVector.scaleInPlace(255);
  57463. randVector.x = Math.floor(randVector.x);
  57464. randVector.y = Math.floor(randVector.y);
  57465. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57466. context.fillRect(x, y, 1, 1);
  57467. }
  57468. }
  57469. this._randomTexture.update(false);
  57470. };
  57471. __decorate([
  57472. BABYLON.serialize()
  57473. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  57474. __decorate([
  57475. BABYLON.serialize()
  57476. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  57477. __decorate([
  57478. BABYLON.serialize()
  57479. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  57480. __decorate([
  57481. BABYLON.serialize("samples")
  57482. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  57483. __decorate([
  57484. BABYLON.serialize("expensiveBlur")
  57485. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  57486. __decorate([
  57487. BABYLON.serialize()
  57488. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  57489. __decorate([
  57490. BABYLON.serialize()
  57491. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  57492. __decorate([
  57493. BABYLON.serialize()
  57494. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  57495. return SSAO2RenderingPipeline;
  57496. }(BABYLON.PostProcessRenderPipeline));
  57497. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  57498. })(BABYLON || (BABYLON = {}));
  57499. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  57500. // BABYLON.JS Chromatic Aberration GLSL Shader
  57501. // Author: Olivier Guyot
  57502. // Separates very slightly R, G and B colors on the edges of the screen
  57503. // Inspired by Francois Tarlier & Martins Upitis
  57504. var BABYLON;
  57505. (function (BABYLON) {
  57506. var LensRenderingPipeline = /** @class */ (function (_super) {
  57507. __extends(LensRenderingPipeline, _super);
  57508. /**
  57509. * @constructor
  57510. *
  57511. * Effect parameters are as follow:
  57512. * {
  57513. * chromatic_aberration: number; // from 0 to x (1 for realism)
  57514. * edge_blur: number; // from 0 to x (1 for realism)
  57515. * distortion: number; // from 0 to x (1 for realism)
  57516. * grain_amount: number; // from 0 to 1
  57517. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  57518. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  57519. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  57520. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  57521. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  57522. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  57523. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  57524. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  57525. * }
  57526. * Note: if an effect parameter is unset, effect is disabled
  57527. *
  57528. * @param {string} name - The rendering pipeline name
  57529. * @param {object} parameters - An object containing all parameters (see above)
  57530. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57531. * @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)
  57532. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57533. */
  57534. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  57535. if (ratio === void 0) { ratio = 1.0; }
  57536. var _this = _super.call(this, scene.getEngine(), name) || this;
  57537. // Lens effects can be of the following:
  57538. // - chromatic aberration (slight shift of RGB colors)
  57539. // - blur on the edge of the lens
  57540. // - lens distortion
  57541. // - depth-of-field blur & highlights enhancing
  57542. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  57543. // - grain effect (noise or custom texture)
  57544. // Two additional texture samplers are needed:
  57545. // - depth map (for depth-of-field)
  57546. // - grain texture
  57547. /**
  57548. * The chromatic aberration PostProcess id in the pipeline
  57549. * @type {string}
  57550. */
  57551. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  57552. /**
  57553. * The highlights enhancing PostProcess id in the pipeline
  57554. * @type {string}
  57555. */
  57556. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  57557. /**
  57558. * The depth-of-field PostProcess id in the pipeline
  57559. * @type {string}
  57560. */
  57561. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  57562. _this._scene = scene;
  57563. // Fetch texture samplers
  57564. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57565. if (parameters.grain_texture) {
  57566. _this._grainTexture = parameters.grain_texture;
  57567. }
  57568. else {
  57569. _this._createGrainTexture();
  57570. }
  57571. // save parameters
  57572. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  57573. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  57574. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  57575. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  57576. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  57577. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  57578. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  57579. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  57580. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  57581. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  57582. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  57583. // Create effects
  57584. _this._createChromaticAberrationPostProcess(ratio);
  57585. _this._createHighlightsPostProcess(ratio);
  57586. _this._createDepthOfFieldPostProcess(ratio / 4);
  57587. // Set up pipeline
  57588. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  57589. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  57590. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  57591. if (_this._highlightsGain === -1) {
  57592. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  57593. }
  57594. // Finish
  57595. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57596. if (cameras) {
  57597. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57598. }
  57599. return _this;
  57600. }
  57601. // public methods (self explanatory)
  57602. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  57603. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  57604. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  57605. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  57606. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  57607. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  57608. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  57609. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  57610. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  57611. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  57612. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  57613. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  57614. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  57615. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  57616. };
  57617. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  57618. this._highlightsPostProcess.updateEffect();
  57619. };
  57620. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  57621. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  57622. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  57623. this._highlightsGain = amount;
  57624. };
  57625. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  57626. if (this._highlightsGain === -1) {
  57627. this._highlightsGain = 1.0;
  57628. }
  57629. this._highlightsThreshold = amount;
  57630. };
  57631. LensRenderingPipeline.prototype.disableHighlights = function () {
  57632. this._highlightsGain = -1;
  57633. };
  57634. /**
  57635. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  57636. */
  57637. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57638. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57639. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57640. this._chromaticAberrationPostProcess = null;
  57641. this._highlightsPostProcess = null;
  57642. this._depthOfFieldPostProcess = null;
  57643. this._grainTexture.dispose();
  57644. if (disableDepthRender)
  57645. this._scene.disableDepthRenderer();
  57646. };
  57647. // colors shifting and distortion
  57648. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  57649. var _this = this;
  57650. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  57651. [], // samplers
  57652. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57653. this._chromaticAberrationPostProcess.onApply = function (effect) {
  57654. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  57655. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57656. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57657. };
  57658. };
  57659. // highlights enhancing
  57660. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  57661. var _this = this;
  57662. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  57663. [], // samplers
  57664. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  57665. this._highlightsPostProcess.onApply = function (effect) {
  57666. effect.setFloat('gain', _this._highlightsGain);
  57667. effect.setFloat('threshold', _this._highlightsThreshold);
  57668. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  57669. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57670. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57671. };
  57672. };
  57673. // colors shifting and distortion
  57674. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  57675. var _this = this;
  57676. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  57677. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  57678. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  57679. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57680. this._depthOfFieldPostProcess.onApply = function (effect) {
  57681. effect.setTexture("depthSampler", _this._depthTexture);
  57682. effect.setTexture("grainSampler", _this._grainTexture);
  57683. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  57684. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  57685. effect.setFloat('grain_amount', _this._grainAmount);
  57686. effect.setBool('blur_noise', _this._blurNoise);
  57687. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57688. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57689. effect.setFloat('distortion', _this._distortion);
  57690. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  57691. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  57692. effect.setFloat('aperture', _this._dofAperture);
  57693. effect.setFloat('darken', _this._dofDarken);
  57694. effect.setFloat('edge_blur', _this._edgeBlur);
  57695. effect.setBool('highlights', (_this._highlightsGain !== -1));
  57696. if (_this._scene.activeCamera) {
  57697. effect.setFloat('near', _this._scene.activeCamera.minZ);
  57698. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  57699. }
  57700. };
  57701. };
  57702. // creates a black and white random noise texture, 512x512
  57703. LensRenderingPipeline.prototype._createGrainTexture = function () {
  57704. var size = 512;
  57705. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57706. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57707. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57708. var context = this._grainTexture.getContext();
  57709. var rand = function (min, max) {
  57710. return Math.random() * (max - min) + min;
  57711. };
  57712. var value;
  57713. for (var x = 0; x < size; x++) {
  57714. for (var y = 0; y < size; y++) {
  57715. value = Math.floor(rand(0.42, 0.58) * 255);
  57716. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  57717. context.fillRect(x, y, 1, 1);
  57718. }
  57719. }
  57720. this._grainTexture.update(false);
  57721. };
  57722. return LensRenderingPipeline;
  57723. }(BABYLON.PostProcessRenderPipeline));
  57724. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  57725. })(BABYLON || (BABYLON = {}));
  57726. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  57727. var BABYLON;
  57728. (function (BABYLON) {
  57729. var StandardRenderingPipeline = /** @class */ (function (_super) {
  57730. __extends(StandardRenderingPipeline, _super);
  57731. /**
  57732. * @constructor
  57733. * @param {string} name - The rendering pipeline name
  57734. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57735. * @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)
  57736. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  57737. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57738. */
  57739. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  57740. if (originalPostProcess === void 0) { originalPostProcess = null; }
  57741. var _this = _super.call(this, scene.getEngine(), name) || this;
  57742. _this.downSampleX4PostProcess = null;
  57743. _this.brightPassPostProcess = null;
  57744. _this.blurHPostProcesses = [];
  57745. _this.blurVPostProcesses = [];
  57746. _this.textureAdderPostProcess = null;
  57747. _this.volumetricLightPostProcess = null;
  57748. _this.volumetricLightSmoothXPostProcess = null;
  57749. _this.volumetricLightSmoothYPostProcess = null;
  57750. _this.volumetricLightMergePostProces = null;
  57751. _this.volumetricLightFinalPostProcess = null;
  57752. _this.luminancePostProcess = null;
  57753. _this.luminanceDownSamplePostProcesses = [];
  57754. _this.hdrPostProcess = null;
  57755. _this.textureAdderFinalPostProcess = null;
  57756. _this.lensFlareFinalPostProcess = null;
  57757. _this.hdrFinalPostProcess = null;
  57758. _this.lensFlarePostProcess = null;
  57759. _this.lensFlareComposePostProcess = null;
  57760. _this.motionBlurPostProcess = null;
  57761. _this.depthOfFieldPostProcess = null;
  57762. // Values
  57763. _this.brightThreshold = 1.0;
  57764. _this.blurWidth = 512.0;
  57765. _this.horizontalBlur = false;
  57766. _this.exposure = 1.0;
  57767. _this.lensTexture = null;
  57768. _this.volumetricLightCoefficient = 0.2;
  57769. _this.volumetricLightPower = 4.0;
  57770. _this.volumetricLightBlurScale = 64.0;
  57771. _this.sourceLight = null;
  57772. _this.hdrMinimumLuminance = 1.0;
  57773. _this.hdrDecreaseRate = 0.5;
  57774. _this.hdrIncreaseRate = 0.5;
  57775. _this.lensColorTexture = null;
  57776. _this.lensFlareStrength = 20.0;
  57777. _this.lensFlareGhostDispersal = 1.4;
  57778. _this.lensFlareHaloWidth = 0.7;
  57779. _this.lensFlareDistortionStrength = 16.0;
  57780. _this.lensStarTexture = null;
  57781. _this.lensFlareDirtTexture = null;
  57782. _this.depthOfFieldDistance = 10.0;
  57783. _this.depthOfFieldBlurWidth = 64.0;
  57784. _this.motionStrength = 1.0;
  57785. // IAnimatable
  57786. _this.animations = [];
  57787. _this._currentDepthOfFieldSource = null;
  57788. _this._hdrCurrentLuminance = 1.0;
  57789. // Getters and setters
  57790. _this._bloomEnabled = true;
  57791. _this._depthOfFieldEnabled = false;
  57792. _this._vlsEnabled = false;
  57793. _this._lensFlareEnabled = false;
  57794. _this._hdrEnabled = false;
  57795. _this._motionBlurEnabled = false;
  57796. _this._motionBlurSamples = 64.0;
  57797. _this._volumetricLightStepsCount = 50.0;
  57798. _this._cameras = cameras || [];
  57799. // Initialize
  57800. _this._scene = scene;
  57801. _this._basePostProcess = originalPostProcess;
  57802. _this._ratio = ratio;
  57803. // Misc
  57804. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57805. // Finish
  57806. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57807. _this._buildPipeline();
  57808. return _this;
  57809. }
  57810. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  57811. get: function () {
  57812. return this._bloomEnabled;
  57813. },
  57814. set: function (enabled) {
  57815. if (this._bloomEnabled === enabled) {
  57816. return;
  57817. }
  57818. this._bloomEnabled = enabled;
  57819. this._buildPipeline();
  57820. },
  57821. enumerable: true,
  57822. configurable: true
  57823. });
  57824. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  57825. get: function () {
  57826. return this._depthOfFieldEnabled;
  57827. },
  57828. set: function (enabled) {
  57829. if (this._depthOfFieldEnabled === enabled) {
  57830. return;
  57831. }
  57832. this._depthOfFieldEnabled = enabled;
  57833. this._buildPipeline();
  57834. },
  57835. enumerable: true,
  57836. configurable: true
  57837. });
  57838. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  57839. get: function () {
  57840. return this._lensFlareEnabled;
  57841. },
  57842. set: function (enabled) {
  57843. if (this._lensFlareEnabled === enabled) {
  57844. return;
  57845. }
  57846. this._lensFlareEnabled = enabled;
  57847. this._buildPipeline();
  57848. },
  57849. enumerable: true,
  57850. configurable: true
  57851. });
  57852. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  57853. get: function () {
  57854. return this._hdrEnabled;
  57855. },
  57856. set: function (enabled) {
  57857. if (this._hdrEnabled === enabled) {
  57858. return;
  57859. }
  57860. this._hdrEnabled = enabled;
  57861. this._buildPipeline();
  57862. },
  57863. enumerable: true,
  57864. configurable: true
  57865. });
  57866. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  57867. get: function () {
  57868. return this._vlsEnabled;
  57869. },
  57870. set: function (enabled) {
  57871. if (this._vlsEnabled === enabled) {
  57872. return;
  57873. }
  57874. if (enabled) {
  57875. var geometry = this._scene.enableGeometryBufferRenderer();
  57876. if (!geometry) {
  57877. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  57878. return;
  57879. }
  57880. }
  57881. this._vlsEnabled = enabled;
  57882. this._buildPipeline();
  57883. },
  57884. enumerable: true,
  57885. configurable: true
  57886. });
  57887. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  57888. get: function () {
  57889. return this._motionBlurEnabled;
  57890. },
  57891. set: function (enabled) {
  57892. if (this._motionBlurEnabled === enabled) {
  57893. return;
  57894. }
  57895. this._motionBlurEnabled = enabled;
  57896. this._buildPipeline();
  57897. },
  57898. enumerable: true,
  57899. configurable: true
  57900. });
  57901. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  57902. get: function () {
  57903. return this._volumetricLightStepsCount;
  57904. },
  57905. set: function (count) {
  57906. if (this.volumetricLightPostProcess) {
  57907. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  57908. }
  57909. this._volumetricLightStepsCount = count;
  57910. },
  57911. enumerable: true,
  57912. configurable: true
  57913. });
  57914. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  57915. get: function () {
  57916. return this._motionBlurSamples;
  57917. },
  57918. set: function (samples) {
  57919. if (this.motionBlurPostProcess) {
  57920. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  57921. }
  57922. this._motionBlurSamples = samples;
  57923. },
  57924. enumerable: true,
  57925. configurable: true
  57926. });
  57927. StandardRenderingPipeline.prototype._buildPipeline = function () {
  57928. var _this = this;
  57929. var ratio = this._ratio;
  57930. var scene = this._scene;
  57931. this._disposePostProcesses();
  57932. this._reset();
  57933. // Create pass post-process
  57934. if (!this._basePostProcess) {
  57935. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  57936. this.originalPostProcess.onApply = function (effect) {
  57937. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  57938. };
  57939. }
  57940. else {
  57941. this.originalPostProcess = this._basePostProcess;
  57942. }
  57943. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  57944. this._currentDepthOfFieldSource = this.originalPostProcess;
  57945. if (this._vlsEnabled) {
  57946. // Create volumetric light
  57947. this._createVolumetricLightPostProcess(scene, ratio);
  57948. // Create volumetric light final post-process
  57949. 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);
  57950. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  57951. }
  57952. if (this._bloomEnabled) {
  57953. // Create down sample X4 post-process
  57954. this._createDownSampleX4PostProcess(scene, ratio / 2);
  57955. // Create bright pass post-process
  57956. this._createBrightPassPostProcess(scene, ratio / 2);
  57957. // Create gaussian blur post-processes (down sampling blurs)
  57958. this._createBlurPostProcesses(scene, ratio / 4, 1);
  57959. // Create texture adder post-process
  57960. this._createTextureAdderPostProcess(scene, ratio);
  57961. // Create depth-of-field source post-process
  57962. 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);
  57963. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  57964. }
  57965. if (this._lensFlareEnabled) {
  57966. // Create lens flare post-process
  57967. this._createLensFlarePostProcess(scene, ratio);
  57968. // Create depth-of-field source post-process post lens-flare and disable it now
  57969. 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);
  57970. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  57971. }
  57972. if (this._hdrEnabled) {
  57973. // Create luminance
  57974. this._createLuminancePostProcesses(scene, this._floatTextureType);
  57975. // Create HDR
  57976. this._createHdrPostProcess(scene, ratio);
  57977. // Create depth-of-field source post-process post hdr and disable it now
  57978. 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);
  57979. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  57980. }
  57981. if (this._depthOfFieldEnabled) {
  57982. // Create gaussian blur used by depth-of-field
  57983. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  57984. // Create depth-of-field post-process
  57985. this._createDepthOfFieldPostProcess(scene, ratio);
  57986. }
  57987. if (this._motionBlurEnabled) {
  57988. // Create motion blur post-process
  57989. this._createMotionBlurPostProcess(scene, ratio);
  57990. }
  57991. if (this._cameras !== null) {
  57992. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  57993. }
  57994. };
  57995. // Down Sample X4 Post-Processs
  57996. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  57997. var _this = this;
  57998. var downSampleX4Offsets = new Array(32);
  57999. 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);
  58000. this.downSampleX4PostProcess.onApply = function (effect) {
  58001. var id = 0;
  58002. var width = _this.downSampleX4PostProcess.width;
  58003. var height = _this.downSampleX4PostProcess.height;
  58004. for (var i = -2; i < 2; i++) {
  58005. for (var j = -2; j < 2; j++) {
  58006. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58007. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58008. id += 2;
  58009. }
  58010. }
  58011. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58012. };
  58013. // Add to pipeline
  58014. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58015. };
  58016. // Brightpass Post-Process
  58017. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58018. var _this = this;
  58019. var brightOffsets = new Array(8);
  58020. 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);
  58021. this.brightPassPostProcess.onApply = function (effect) {
  58022. var sU = (1.0 / _this.brightPassPostProcess.width);
  58023. var sV = (1.0 / _this.brightPassPostProcess.height);
  58024. brightOffsets[0] = -0.5 * sU;
  58025. brightOffsets[1] = 0.5 * sV;
  58026. brightOffsets[2] = 0.5 * sU;
  58027. brightOffsets[3] = 0.5 * sV;
  58028. brightOffsets[4] = -0.5 * sU;
  58029. brightOffsets[5] = -0.5 * sV;
  58030. brightOffsets[6] = 0.5 * sU;
  58031. brightOffsets[7] = -0.5 * sV;
  58032. effect.setArray2("dsOffsets", brightOffsets);
  58033. effect.setFloat("brightThreshold", _this.brightThreshold);
  58034. };
  58035. // Add to pipeline
  58036. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58037. };
  58038. // Create blur H&V post-processes
  58039. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58040. var _this = this;
  58041. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58042. var engine = scene.getEngine();
  58043. 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);
  58044. 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);
  58045. blurX.onActivateObservable.add(function () {
  58046. var dw = blurX.width / engine.getRenderWidth();
  58047. blurX.kernel = _this[blurWidthKey] * dw;
  58048. });
  58049. blurY.onActivateObservable.add(function () {
  58050. var dw = blurY.height / engine.getRenderHeight();
  58051. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58052. });
  58053. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58054. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58055. this.blurHPostProcesses.push(blurX);
  58056. this.blurVPostProcesses.push(blurY);
  58057. };
  58058. // Create texture adder post-process
  58059. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58060. var _this = this;
  58061. 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);
  58062. this.textureAdderPostProcess.onApply = function (effect) {
  58063. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58064. effect.setTexture("lensSampler", _this.lensTexture);
  58065. effect.setFloat("exposure", _this.exposure);
  58066. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58067. };
  58068. // Add to pipeline
  58069. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58070. };
  58071. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58072. var _this = this;
  58073. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58074. geometryRenderer.enablePosition = true;
  58075. var geometry = geometryRenderer.getGBuffer();
  58076. // Base post-process
  58077. 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));
  58078. var depthValues = BABYLON.Vector2.Zero();
  58079. this.volumetricLightPostProcess.onApply = function (effect) {
  58080. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  58081. var generator = _this.sourceLight.getShadowGenerator();
  58082. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  58083. effect.setTexture("positionSampler", geometry.textures[2]);
  58084. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  58085. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  58086. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  58087. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  58088. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  58089. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  58090. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  58091. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  58092. effect.setVector2("depthValues", depthValues);
  58093. }
  58094. };
  58095. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  58096. // Smooth
  58097. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  58098. // Merge
  58099. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  58100. this.volumetricLightMergePostProces.onApply = function (effect) {
  58101. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  58102. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  58103. };
  58104. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  58105. };
  58106. // Create luminance
  58107. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  58108. var _this = this;
  58109. // Create luminance
  58110. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  58111. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  58112. var offsets = [];
  58113. this.luminancePostProcess.onApply = function (effect) {
  58114. var sU = (1.0 / _this.luminancePostProcess.width);
  58115. var sV = (1.0 / _this.luminancePostProcess.height);
  58116. offsets[0] = -0.5 * sU;
  58117. offsets[1] = 0.5 * sV;
  58118. offsets[2] = 0.5 * sU;
  58119. offsets[3] = 0.5 * sV;
  58120. offsets[4] = -0.5 * sU;
  58121. offsets[5] = -0.5 * sV;
  58122. offsets[6] = 0.5 * sU;
  58123. offsets[7] = -0.5 * sV;
  58124. effect.setArray2("lumOffsets", offsets);
  58125. };
  58126. // Add to pipeline
  58127. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  58128. // Create down sample luminance
  58129. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  58130. var size = Math.pow(3, i);
  58131. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  58132. if (i === 0) {
  58133. defines += "#define FINAL_DOWN_SAMPLER";
  58134. }
  58135. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  58136. this.luminanceDownSamplePostProcesses.push(postProcess);
  58137. }
  58138. // Create callbacks and add effects
  58139. var lastLuminance = this.luminancePostProcess;
  58140. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  58141. var downSampleOffsets = new Array(18);
  58142. pp.onApply = function (effect) {
  58143. if (!lastLuminance) {
  58144. return;
  58145. }
  58146. var id = 0;
  58147. for (var x = -1; x < 2; x++) {
  58148. for (var y = -1; y < 2; y++) {
  58149. downSampleOffsets[id] = x / lastLuminance.width;
  58150. downSampleOffsets[id + 1] = y / lastLuminance.height;
  58151. id += 2;
  58152. }
  58153. }
  58154. effect.setArray2("dsOffsets", downSampleOffsets);
  58155. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  58156. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58157. lastLuminance = _this.luminancePostProcess;
  58158. }
  58159. else {
  58160. lastLuminance = pp;
  58161. }
  58162. };
  58163. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58164. pp.onAfterRender = function (effect) {
  58165. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  58166. 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);
  58167. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  58168. };
  58169. }
  58170. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  58171. });
  58172. };
  58173. // Create HDR post-process
  58174. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  58175. var _this = this;
  58176. 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);
  58177. var outputLiminance = 1;
  58178. var time = 0;
  58179. var lastTime = 0;
  58180. this.hdrPostProcess.onApply = function (effect) {
  58181. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  58182. time += scene.getEngine().getDeltaTime();
  58183. if (outputLiminance < 0) {
  58184. outputLiminance = _this._hdrCurrentLuminance;
  58185. }
  58186. else {
  58187. var dt = (lastTime - time) / 1000.0;
  58188. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  58189. outputLiminance += _this.hdrDecreaseRate * dt;
  58190. }
  58191. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  58192. outputLiminance -= _this.hdrIncreaseRate * dt;
  58193. }
  58194. else {
  58195. outputLiminance = _this._hdrCurrentLuminance;
  58196. }
  58197. }
  58198. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  58199. effect.setFloat("averageLuminance", outputLiminance);
  58200. lastTime = time;
  58201. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  58202. };
  58203. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  58204. };
  58205. // Create lens flare post-process
  58206. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58207. var _this = this;
  58208. 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);
  58209. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58210. this._createBlurPostProcesses(scene, ratio / 4, 2);
  58211. 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);
  58212. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58213. var resolution = new BABYLON.Vector2(0, 0);
  58214. // Lens flare
  58215. this.lensFlarePostProcess.onApply = function (effect) {
  58216. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  58217. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58218. effect.setFloat("strength", _this.lensFlareStrength);
  58219. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58220. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58221. // Shift
  58222. resolution.x = _this.lensFlarePostProcess.width;
  58223. resolution.y = _this.lensFlarePostProcess.height;
  58224. effect.setVector2("resolution", resolution);
  58225. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58226. };
  58227. // Compose
  58228. 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);
  58229. 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);
  58230. this.lensFlareComposePostProcess.onApply = function (effect) {
  58231. if (!_this._scene.activeCamera) {
  58232. return;
  58233. }
  58234. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58235. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58236. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58237. // Lens start rotation matrix
  58238. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58239. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58240. 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));
  58241. camRot *= 4.0;
  58242. 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);
  58243. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58244. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58245. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  58246. };
  58247. };
  58248. // Create depth-of-field post-process
  58249. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58250. var _this = this;
  58251. 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);
  58252. this.depthOfFieldPostProcess.onApply = function (effect) {
  58253. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58254. effect.setTexture("depthSampler", _this._getDepthTexture());
  58255. effect.setFloat("distance", _this.depthOfFieldDistance);
  58256. };
  58257. // Add to pipeline
  58258. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58259. };
  58260. // Create motion blur post-process
  58261. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  58262. var _this = this;
  58263. 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);
  58264. var motionScale = 0;
  58265. var prevViewProjection = BABYLON.Matrix.Identity();
  58266. var invViewProjection = BABYLON.Matrix.Identity();
  58267. var viewProjection = BABYLON.Matrix.Identity();
  58268. var screenSize = BABYLON.Vector2.Zero();
  58269. this.motionBlurPostProcess.onApply = function (effect) {
  58270. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  58271. viewProjection.invertToRef(invViewProjection);
  58272. effect.setMatrix("inverseViewProjection", invViewProjection);
  58273. effect.setMatrix("prevViewProjection", prevViewProjection);
  58274. prevViewProjection = viewProjection;
  58275. screenSize.x = _this.motionBlurPostProcess.width;
  58276. screenSize.y = _this.motionBlurPostProcess.height;
  58277. effect.setVector2("screenSize", screenSize);
  58278. motionScale = scene.getEngine().getFps() / 60.0;
  58279. effect.setFloat("motionScale", motionScale);
  58280. effect.setFloat("motionStrength", _this.motionStrength);
  58281. effect.setTexture("depthSampler", _this._getDepthTexture());
  58282. };
  58283. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  58284. };
  58285. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  58286. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  58287. var renderer = this._scene.enableGeometryBufferRenderer();
  58288. return renderer.getGBuffer().textures[0];
  58289. }
  58290. return this._scene.enableDepthRenderer().getDepthMap();
  58291. };
  58292. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  58293. for (var i = 0; i < this._cameras.length; i++) {
  58294. var camera = this._cameras[i];
  58295. if (this.originalPostProcess) {
  58296. this.originalPostProcess.dispose(camera);
  58297. }
  58298. if (this.downSampleX4PostProcess) {
  58299. this.downSampleX4PostProcess.dispose(camera);
  58300. }
  58301. if (this.brightPassPostProcess) {
  58302. this.brightPassPostProcess.dispose(camera);
  58303. }
  58304. if (this.textureAdderPostProcess) {
  58305. this.textureAdderPostProcess.dispose(camera);
  58306. }
  58307. if (this.textureAdderFinalPostProcess) {
  58308. this.textureAdderFinalPostProcess.dispose(camera);
  58309. }
  58310. if (this.volumetricLightPostProcess) {
  58311. this.volumetricLightPostProcess.dispose(camera);
  58312. }
  58313. if (this.volumetricLightSmoothXPostProcess) {
  58314. this.volumetricLightSmoothXPostProcess.dispose(camera);
  58315. }
  58316. if (this.volumetricLightSmoothYPostProcess) {
  58317. this.volumetricLightSmoothYPostProcess.dispose(camera);
  58318. }
  58319. if (this.volumetricLightMergePostProces) {
  58320. this.volumetricLightMergePostProces.dispose(camera);
  58321. }
  58322. if (this.volumetricLightFinalPostProcess) {
  58323. this.volumetricLightFinalPostProcess.dispose(camera);
  58324. }
  58325. if (this.lensFlarePostProcess) {
  58326. this.lensFlarePostProcess.dispose(camera);
  58327. }
  58328. if (this.lensFlareComposePostProcess) {
  58329. this.lensFlareComposePostProcess.dispose(camera);
  58330. }
  58331. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  58332. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  58333. }
  58334. if (this.luminancePostProcess) {
  58335. this.luminancePostProcess.dispose(camera);
  58336. }
  58337. if (this.hdrPostProcess) {
  58338. this.hdrPostProcess.dispose(camera);
  58339. }
  58340. if (this.hdrFinalPostProcess) {
  58341. this.hdrFinalPostProcess.dispose(camera);
  58342. }
  58343. if (this.depthOfFieldPostProcess) {
  58344. this.depthOfFieldPostProcess.dispose(camera);
  58345. }
  58346. if (this.motionBlurPostProcess) {
  58347. this.motionBlurPostProcess.dispose(camera);
  58348. }
  58349. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  58350. this.blurHPostProcesses[j].dispose(camera);
  58351. }
  58352. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  58353. this.blurVPostProcesses[j].dispose(camera);
  58354. }
  58355. }
  58356. this.originalPostProcess = null;
  58357. this.downSampleX4PostProcess = null;
  58358. this.brightPassPostProcess = null;
  58359. this.textureAdderPostProcess = null;
  58360. this.textureAdderFinalPostProcess = null;
  58361. this.volumetricLightPostProcess = null;
  58362. this.volumetricLightSmoothXPostProcess = null;
  58363. this.volumetricLightSmoothYPostProcess = null;
  58364. this.volumetricLightMergePostProces = null;
  58365. this.volumetricLightFinalPostProcess = null;
  58366. this.lensFlarePostProcess = null;
  58367. this.lensFlareComposePostProcess = null;
  58368. this.luminancePostProcess = null;
  58369. this.hdrPostProcess = null;
  58370. this.hdrFinalPostProcess = null;
  58371. this.depthOfFieldPostProcess = null;
  58372. this.motionBlurPostProcess = null;
  58373. this.luminanceDownSamplePostProcesses = [];
  58374. this.blurHPostProcesses = [];
  58375. this.blurVPostProcesses = [];
  58376. };
  58377. // Dispose
  58378. StandardRenderingPipeline.prototype.dispose = function () {
  58379. this._disposePostProcesses();
  58380. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58381. _super.prototype.dispose.call(this);
  58382. };
  58383. // Serialize rendering pipeline
  58384. StandardRenderingPipeline.prototype.serialize = function () {
  58385. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58386. serializationObject.customType = "StandardRenderingPipeline";
  58387. return serializationObject;
  58388. };
  58389. /**
  58390. * Static members
  58391. */
  58392. // Parse serialized pipeline
  58393. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58394. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58395. };
  58396. // Luminance steps
  58397. StandardRenderingPipeline.LuminanceSteps = 6;
  58398. __decorate([
  58399. BABYLON.serialize()
  58400. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58401. __decorate([
  58402. BABYLON.serialize()
  58403. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58404. __decorate([
  58405. BABYLON.serialize()
  58406. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58407. __decorate([
  58408. BABYLON.serialize()
  58409. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58410. __decorate([
  58411. BABYLON.serializeAsTexture("lensTexture")
  58412. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58413. __decorate([
  58414. BABYLON.serialize()
  58415. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  58416. __decorate([
  58417. BABYLON.serialize()
  58418. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  58419. __decorate([
  58420. BABYLON.serialize()
  58421. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  58422. __decorate([
  58423. BABYLON.serialize()
  58424. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  58425. __decorate([
  58426. BABYLON.serialize()
  58427. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  58428. __decorate([
  58429. BABYLON.serialize()
  58430. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  58431. __decorate([
  58432. BABYLON.serializeAsTexture("lensColorTexture")
  58433. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  58434. __decorate([
  58435. BABYLON.serialize()
  58436. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  58437. __decorate([
  58438. BABYLON.serialize()
  58439. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  58440. __decorate([
  58441. BABYLON.serialize()
  58442. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  58443. __decorate([
  58444. BABYLON.serialize()
  58445. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  58446. __decorate([
  58447. BABYLON.serializeAsTexture("lensStarTexture")
  58448. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  58449. __decorate([
  58450. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  58451. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  58452. __decorate([
  58453. BABYLON.serialize()
  58454. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  58455. __decorate([
  58456. BABYLON.serialize()
  58457. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  58458. __decorate([
  58459. BABYLON.serialize()
  58460. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  58461. __decorate([
  58462. BABYLON.serialize()
  58463. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  58464. __decorate([
  58465. BABYLON.serialize()
  58466. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  58467. __decorate([
  58468. BABYLON.serialize()
  58469. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  58470. __decorate([
  58471. BABYLON.serialize()
  58472. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  58473. __decorate([
  58474. BABYLON.serialize()
  58475. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  58476. __decorate([
  58477. BABYLON.serialize()
  58478. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  58479. __decorate([
  58480. BABYLON.serialize()
  58481. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  58482. __decorate([
  58483. BABYLON.serialize()
  58484. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  58485. return StandardRenderingPipeline;
  58486. }(BABYLON.PostProcessRenderPipeline));
  58487. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  58488. })(BABYLON || (BABYLON = {}));
  58489. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  58490. var BABYLON;
  58491. (function (BABYLON) {
  58492. var FxaaPostProcess = /** @class */ (function (_super) {
  58493. __extends(FxaaPostProcess, _super);
  58494. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58495. if (camera === void 0) { camera = null; }
  58496. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58497. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  58498. _this.onApplyObservable.add(function (effect) {
  58499. var texelSize = _this.texelSize;
  58500. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  58501. });
  58502. return _this;
  58503. }
  58504. return FxaaPostProcess;
  58505. }(BABYLON.PostProcess));
  58506. BABYLON.FxaaPostProcess = FxaaPostProcess;
  58507. })(BABYLON || (BABYLON = {}));
  58508. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  58509. var BABYLON;
  58510. (function (BABYLON) {
  58511. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  58512. __extends(DefaultRenderingPipeline, _super);
  58513. /**
  58514. * @constructor
  58515. * @param {string} name - The rendering pipeline name
  58516. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58517. * @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)
  58518. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58519. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  58520. */
  58521. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  58522. if (automaticBuild === void 0) { automaticBuild = true; }
  58523. var _this = _super.call(this, scene.getEngine(), name) || this;
  58524. _this.PassPostProcessId = "PassPostProcessEffect";
  58525. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  58526. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  58527. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  58528. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  58529. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  58530. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  58531. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  58532. // IAnimatable
  58533. _this.animations = [];
  58534. // Values
  58535. _this._bloomEnabled = false;
  58536. _this._fxaaEnabled = false;
  58537. _this._imageProcessingEnabled = true;
  58538. _this._bloomScale = 0.6;
  58539. _this._buildAllowed = true;
  58540. /**
  58541. * Specifies the size of the bloom blur kernel, relative to the final output size
  58542. */
  58543. _this.bloomKernel = 64;
  58544. /**
  58545. * Specifies the weight of the bloom in the final rendering
  58546. */
  58547. _this._bloomWeight = 0.15;
  58548. _this._cameras = cameras || [];
  58549. _this._buildAllowed = automaticBuild;
  58550. // Initialize
  58551. _this._scene = scene;
  58552. var caps = _this._scene.getEngine().getCaps();
  58553. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  58554. // Misc
  58555. if (_this._hdr) {
  58556. if (caps.textureHalfFloatRender) {
  58557. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58558. }
  58559. else if (caps.textureFloatRender) {
  58560. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58561. }
  58562. }
  58563. else {
  58564. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58565. }
  58566. // Attach
  58567. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58568. _this._buildPipeline();
  58569. return _this;
  58570. }
  58571. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  58572. get: function () {
  58573. return this._bloomWeight;
  58574. },
  58575. set: function (value) {
  58576. if (this._bloomWeight === value) {
  58577. return;
  58578. }
  58579. this._bloomWeight = value;
  58580. if (this._hdr && this.copyBack) {
  58581. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  58582. }
  58583. },
  58584. enumerable: true,
  58585. configurable: true
  58586. });
  58587. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  58588. get: function () {
  58589. return this._bloomScale;
  58590. },
  58591. set: function (value) {
  58592. if (this._bloomScale === value) {
  58593. return;
  58594. }
  58595. this._bloomScale = value;
  58596. this._buildPipeline();
  58597. },
  58598. enumerable: true,
  58599. configurable: true
  58600. });
  58601. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  58602. get: function () {
  58603. return this._bloomEnabled;
  58604. },
  58605. set: function (enabled) {
  58606. if (this._bloomEnabled === enabled) {
  58607. return;
  58608. }
  58609. this._bloomEnabled = enabled;
  58610. this._buildPipeline();
  58611. },
  58612. enumerable: true,
  58613. configurable: true
  58614. });
  58615. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  58616. get: function () {
  58617. return this._fxaaEnabled;
  58618. },
  58619. set: function (enabled) {
  58620. if (this._fxaaEnabled === enabled) {
  58621. return;
  58622. }
  58623. this._fxaaEnabled = enabled;
  58624. this._buildPipeline();
  58625. },
  58626. enumerable: true,
  58627. configurable: true
  58628. });
  58629. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  58630. get: function () {
  58631. return this._imageProcessingEnabled;
  58632. },
  58633. set: function (enabled) {
  58634. if (this._imageProcessingEnabled === enabled) {
  58635. return;
  58636. }
  58637. this._imageProcessingEnabled = enabled;
  58638. this._buildPipeline();
  58639. },
  58640. enumerable: true,
  58641. configurable: true
  58642. });
  58643. /**
  58644. * Force the compilation of the entire pipeline.
  58645. */
  58646. DefaultRenderingPipeline.prototype.prepare = function () {
  58647. var previousState = this._buildAllowed;
  58648. this._buildAllowed = true;
  58649. this._buildPipeline();
  58650. this._buildAllowed = previousState;
  58651. };
  58652. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  58653. var _this = this;
  58654. if (!this._buildAllowed) {
  58655. return;
  58656. }
  58657. var engine = this._scene.getEngine();
  58658. this._disposePostProcesses();
  58659. this._reset();
  58660. if (this.bloomEnabled) {
  58661. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58662. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  58663. if (!this._hdr) {
  58664. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58665. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  58666. this.highlights.autoClear = false;
  58667. this.highlights.alwaysForcePOT = true;
  58668. }
  58669. 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);
  58670. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  58671. this.blurX.alwaysForcePOT = true;
  58672. this.blurX.autoClear = false;
  58673. this.blurX.onActivateObservable.add(function () {
  58674. var dw = _this.blurX.width / engine.getRenderWidth(true);
  58675. _this.blurX.kernel = _this.bloomKernel * dw;
  58676. });
  58677. 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);
  58678. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  58679. this.blurY.alwaysForcePOT = true;
  58680. this.blurY.autoClear = false;
  58681. this.blurY.onActivateObservable.add(function () {
  58682. var dh = _this.blurY.height / engine.getRenderHeight(true);
  58683. _this.blurY.kernel = _this.bloomKernel * dh;
  58684. });
  58685. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58686. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  58687. this.copyBack.alwaysForcePOT = true;
  58688. if (this._hdr) {
  58689. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  58690. var w = this.bloomWeight;
  58691. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  58692. }
  58693. else {
  58694. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  58695. }
  58696. this.copyBack.autoClear = false;
  58697. }
  58698. if (this._imageProcessingEnabled) {
  58699. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58700. if (this._hdr) {
  58701. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  58702. }
  58703. else {
  58704. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  58705. }
  58706. }
  58707. if (this.fxaaEnabled) {
  58708. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58709. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  58710. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58711. }
  58712. else {
  58713. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58714. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  58715. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58716. }
  58717. if (this.bloomEnabled) {
  58718. if (this._hdr) {
  58719. this.copyBack.shareOutputWith(this.blurX);
  58720. if (this.imageProcessing) {
  58721. this.imageProcessing.shareOutputWith(this.pass);
  58722. this.imageProcessing.autoClear = false;
  58723. }
  58724. else if (this.fxaa) {
  58725. this.fxaa.shareOutputWith(this.pass);
  58726. }
  58727. else {
  58728. this.finalMerge.shareOutputWith(this.pass);
  58729. }
  58730. }
  58731. else {
  58732. if (this.fxaa) {
  58733. this.fxaa.shareOutputWith(this.pass);
  58734. }
  58735. else {
  58736. this.finalMerge.shareOutputWith(this.pass);
  58737. }
  58738. }
  58739. }
  58740. if (this._cameras !== null) {
  58741. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58742. }
  58743. };
  58744. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  58745. for (var i = 0; i < this._cameras.length; i++) {
  58746. var camera = this._cameras[i];
  58747. if (this.pass) {
  58748. this.pass.dispose(camera);
  58749. }
  58750. if (this.highlights) {
  58751. this.highlights.dispose(camera);
  58752. }
  58753. if (this.blurX) {
  58754. this.blurX.dispose(camera);
  58755. }
  58756. if (this.blurY) {
  58757. this.blurY.dispose(camera);
  58758. }
  58759. if (this.copyBack) {
  58760. this.copyBack.dispose(camera);
  58761. }
  58762. if (this.imageProcessing) {
  58763. this.imageProcessing.dispose(camera);
  58764. }
  58765. if (this.fxaa) {
  58766. this.fxaa.dispose(camera);
  58767. }
  58768. if (this.finalMerge) {
  58769. this.finalMerge.dispose(camera);
  58770. }
  58771. }
  58772. this.pass = null;
  58773. this.highlights = null;
  58774. this.blurX = null;
  58775. this.blurY = null;
  58776. this.copyBack = null;
  58777. this.imageProcessing = null;
  58778. this.fxaa = null;
  58779. this.finalMerge = null;
  58780. };
  58781. // Dispose
  58782. DefaultRenderingPipeline.prototype.dispose = function () {
  58783. this._disposePostProcesses();
  58784. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58785. _super.prototype.dispose.call(this);
  58786. };
  58787. // Serialize rendering pipeline
  58788. DefaultRenderingPipeline.prototype.serialize = function () {
  58789. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58790. serializationObject.customType = "DefaultRenderingPipeline";
  58791. return serializationObject;
  58792. };
  58793. // Parse serialized pipeline
  58794. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58795. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  58796. };
  58797. __decorate([
  58798. BABYLON.serialize()
  58799. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  58800. __decorate([
  58801. BABYLON.serialize()
  58802. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  58803. __decorate([
  58804. BABYLON.serialize()
  58805. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  58806. __decorate([
  58807. BABYLON.serialize()
  58808. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  58809. __decorate([
  58810. BABYLON.serialize()
  58811. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  58812. __decorate([
  58813. BABYLON.serialize()
  58814. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  58815. __decorate([
  58816. BABYLON.serialize()
  58817. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  58818. __decorate([
  58819. BABYLON.serialize()
  58820. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  58821. return DefaultRenderingPipeline;
  58822. }(BABYLON.PostProcessRenderPipeline));
  58823. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  58824. })(BABYLON || (BABYLON = {}));
  58825. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  58826. var BABYLON;
  58827. (function (BABYLON) {
  58828. var GeometryBufferRenderer = /** @class */ (function () {
  58829. function GeometryBufferRenderer(scene, ratio) {
  58830. if (ratio === void 0) { ratio = 1; }
  58831. this._enablePosition = false;
  58832. this._scene = scene;
  58833. this._ratio = ratio;
  58834. // Render target
  58835. this._createRenderTargets();
  58836. }
  58837. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  58838. set: function (meshes) {
  58839. this._multiRenderTarget.renderList = meshes;
  58840. },
  58841. enumerable: true,
  58842. configurable: true
  58843. });
  58844. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  58845. get: function () {
  58846. return this._multiRenderTarget.isSupported;
  58847. },
  58848. enumerable: true,
  58849. configurable: true
  58850. });
  58851. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  58852. get: function () {
  58853. return this._enablePosition;
  58854. },
  58855. set: function (enable) {
  58856. this._enablePosition = enable;
  58857. this.dispose();
  58858. this._createRenderTargets();
  58859. },
  58860. enumerable: true,
  58861. configurable: true
  58862. });
  58863. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  58864. var material = subMesh.getMaterial();
  58865. if (material && material.disableDepthWrite) {
  58866. return false;
  58867. }
  58868. var defines = [];
  58869. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  58870. var mesh = subMesh.getMesh();
  58871. // Alpha test
  58872. if (material && material.needAlphaTesting()) {
  58873. defines.push("#define ALPHATEST");
  58874. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58875. attribs.push(BABYLON.VertexBuffer.UVKind);
  58876. defines.push("#define UV1");
  58877. }
  58878. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58879. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58880. defines.push("#define UV2");
  58881. }
  58882. }
  58883. // Buffers
  58884. if (this._enablePosition) {
  58885. defines.push("#define POSITION");
  58886. }
  58887. // Bones
  58888. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58889. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58890. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58891. if (mesh.numBoneInfluencers > 4) {
  58892. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58893. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58894. }
  58895. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58896. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  58897. }
  58898. else {
  58899. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58900. }
  58901. // Instances
  58902. if (useInstances) {
  58903. defines.push("#define INSTANCES");
  58904. attribs.push("world0");
  58905. attribs.push("world1");
  58906. attribs.push("world2");
  58907. attribs.push("world3");
  58908. }
  58909. // Get correct effect
  58910. var join = defines.join("\n");
  58911. if (this._cachedDefines !== join) {
  58912. this._cachedDefines = join;
  58913. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  58914. }
  58915. return this._effect.isReady();
  58916. };
  58917. GeometryBufferRenderer.prototype.getGBuffer = function () {
  58918. return this._multiRenderTarget;
  58919. };
  58920. // Methods
  58921. GeometryBufferRenderer.prototype.dispose = function () {
  58922. this.getGBuffer().dispose();
  58923. };
  58924. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  58925. var _this = this;
  58926. var engine = this._scene.getEngine();
  58927. var count = this._enablePosition ? 3 : 2;
  58928. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  58929. if (!this.isSupported) {
  58930. return;
  58931. }
  58932. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58933. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58934. this._multiRenderTarget.refreshRate = 1;
  58935. this._multiRenderTarget.renderParticles = false;
  58936. this._multiRenderTarget.renderList = null;
  58937. // set default depth value to 1.0 (far away)
  58938. this._multiRenderTarget.onClearObservable.add(function (engine) {
  58939. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  58940. });
  58941. // Custom render function
  58942. var renderSubMesh = function (subMesh) {
  58943. var mesh = subMesh.getRenderingMesh();
  58944. var scene = _this._scene;
  58945. var engine = scene.getEngine();
  58946. var material = subMesh.getMaterial();
  58947. if (!material) {
  58948. return;
  58949. }
  58950. // Culling
  58951. engine.setState(material.backFaceCulling);
  58952. // Managing instances
  58953. var batch = mesh._getInstancesRenderList(subMesh._id);
  58954. if (batch.mustReturn) {
  58955. return;
  58956. }
  58957. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  58958. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  58959. engine.enableEffect(_this._effect);
  58960. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  58961. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  58962. _this._effect.setMatrix("view", scene.getViewMatrix());
  58963. // Alpha test
  58964. if (material && material.needAlphaTesting()) {
  58965. var alphaTexture = material.getAlphaTestTexture();
  58966. if (alphaTexture) {
  58967. _this._effect.setTexture("diffuseSampler", alphaTexture);
  58968. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  58969. }
  58970. }
  58971. // Bones
  58972. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58973. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  58974. }
  58975. // Draw
  58976. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58977. }
  58978. };
  58979. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58980. var index;
  58981. if (depthOnlySubMeshes.length) {
  58982. engine.setColorWrite(false);
  58983. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58984. renderSubMesh(depthOnlySubMeshes.data[index]);
  58985. }
  58986. engine.setColorWrite(true);
  58987. }
  58988. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58989. renderSubMesh(opaqueSubMeshes.data[index]);
  58990. }
  58991. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58992. renderSubMesh(alphaTestSubMeshes.data[index]);
  58993. }
  58994. };
  58995. };
  58996. return GeometryBufferRenderer;
  58997. }());
  58998. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  58999. })(BABYLON || (BABYLON = {}));
  59000. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59001. var BABYLON;
  59002. (function (BABYLON) {
  59003. var RefractionPostProcess = /** @class */ (function (_super) {
  59004. __extends(RefractionPostProcess, _super);
  59005. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59006. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59007. _this.color = color;
  59008. _this.depth = depth;
  59009. _this.colorLevel = colorLevel;
  59010. _this.onActivateObservable.add(function (cam) {
  59011. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59012. });
  59013. _this.onApplyObservable.add(function (effect) {
  59014. effect.setColor3("baseColor", _this.color);
  59015. effect.setFloat("depth", _this.depth);
  59016. effect.setFloat("colorLevel", _this.colorLevel);
  59017. effect.setTexture("refractionSampler", _this._refRexture);
  59018. });
  59019. return _this;
  59020. }
  59021. // Methods
  59022. RefractionPostProcess.prototype.dispose = function (camera) {
  59023. if (this._refRexture) {
  59024. this._refRexture.dispose();
  59025. }
  59026. _super.prototype.dispose.call(this, camera);
  59027. };
  59028. return RefractionPostProcess;
  59029. }(BABYLON.PostProcess));
  59030. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59031. })(BABYLON || (BABYLON = {}));
  59032. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59033. var BABYLON;
  59034. (function (BABYLON) {
  59035. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59036. __extends(BlackAndWhitePostProcess, _super);
  59037. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59038. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59039. _this.degree = 1;
  59040. _this.onApplyObservable.add(function (effect) {
  59041. effect.setFloat("degree", _this.degree);
  59042. });
  59043. return _this;
  59044. }
  59045. return BlackAndWhitePostProcess;
  59046. }(BABYLON.PostProcess));
  59047. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59048. })(BABYLON || (BABYLON = {}));
  59049. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59050. var BABYLON;
  59051. (function (BABYLON) {
  59052. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59053. __extends(ConvolutionPostProcess, _super);
  59054. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59055. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59056. _this.kernel = kernel;
  59057. _this.onApply = function (effect) {
  59058. effect.setFloat2("screenSize", _this.width, _this.height);
  59059. effect.setArray("kernel", _this.kernel);
  59060. };
  59061. return _this;
  59062. }
  59063. // Statics
  59064. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59065. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59066. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59067. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59068. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59069. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59070. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59071. return ConvolutionPostProcess;
  59072. }(BABYLON.PostProcess));
  59073. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59074. })(BABYLON || (BABYLON = {}));
  59075. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59076. var BABYLON;
  59077. (function (BABYLON) {
  59078. var FilterPostProcess = /** @class */ (function (_super) {
  59079. __extends(FilterPostProcess, _super);
  59080. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  59081. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  59082. _this.kernelMatrix = kernelMatrix;
  59083. _this.onApply = function (effect) {
  59084. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  59085. };
  59086. return _this;
  59087. }
  59088. return FilterPostProcess;
  59089. }(BABYLON.PostProcess));
  59090. BABYLON.FilterPostProcess = FilterPostProcess;
  59091. })(BABYLON || (BABYLON = {}));
  59092. //# sourceMappingURL=babylon.filterPostProcess.js.map
  59093. var BABYLON;
  59094. (function (BABYLON) {
  59095. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  59096. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  59097. __extends(VolumetricLightScatteringPostProcess, _super);
  59098. /**
  59099. * @constructor
  59100. * @param {string} name - The post-process name
  59101. * @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)
  59102. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  59103. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  59104. * @param {number} samples - The post-process quality, default 100
  59105. * @param {number} samplingMode - The post-process filtering mode
  59106. * @param {BABYLON.Engine} engine - The babylon engine
  59107. * @param {boolean} reusable - If the post-process is reusable
  59108. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  59109. */
  59110. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  59111. if (samples === void 0) { samples = 100; }
  59112. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59113. 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;
  59114. _this._screenCoordinates = BABYLON.Vector2.Zero();
  59115. /**
  59116. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  59117. * @type {Vector3}
  59118. */
  59119. _this.customMeshPosition = BABYLON.Vector3.Zero();
  59120. /**
  59121. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  59122. * @type {boolean}
  59123. */
  59124. _this.useCustomMeshPosition = false;
  59125. /**
  59126. * If the post-process should inverse the light scattering direction
  59127. * @type {boolean}
  59128. */
  59129. _this.invert = true;
  59130. /**
  59131. * Array containing the excluded meshes not rendered in the internal pass
  59132. */
  59133. _this.excludedMeshes = new Array();
  59134. /**
  59135. * Controls the overall intensity of the post-process
  59136. * @type {number}
  59137. */
  59138. _this.exposure = 0.3;
  59139. /**
  59140. * Dissipates each sample's contribution in range [0, 1]
  59141. * @type {number}
  59142. */
  59143. _this.decay = 0.96815;
  59144. /**
  59145. * Controls the overall intensity of each sample
  59146. * @type {number}
  59147. */
  59148. _this.weight = 0.58767;
  59149. /**
  59150. * Controls the density of each sample
  59151. * @type {number}
  59152. */
  59153. _this.density = 0.926;
  59154. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  59155. engine = scene.getEngine();
  59156. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59157. // Configure mesh
  59158. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  59159. // Configure
  59160. _this._createPass(scene, ratio.passRatio || ratio);
  59161. _this.onActivate = function (camera) {
  59162. if (!_this.isSupported) {
  59163. _this.dispose(camera);
  59164. }
  59165. _this.onActivate = null;
  59166. };
  59167. _this.onApplyObservable.add(function (effect) {
  59168. _this._updateMeshScreenCoordinates(scene);
  59169. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  59170. effect.setFloat("exposure", _this.exposure);
  59171. effect.setFloat("decay", _this.decay);
  59172. effect.setFloat("weight", _this.weight);
  59173. effect.setFloat("density", _this.density);
  59174. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  59175. });
  59176. return _this;
  59177. }
  59178. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  59179. get: function () {
  59180. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59181. return false;
  59182. },
  59183. set: function (useDiffuseColor) {
  59184. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59185. },
  59186. enumerable: true,
  59187. configurable: true
  59188. });
  59189. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  59190. return "VolumetricLightScatteringPostProcess";
  59191. };
  59192. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  59193. var mesh = subMesh.getMesh();
  59194. // Render this.mesh as default
  59195. if (mesh === this.mesh && mesh.material) {
  59196. return mesh.material.isReady(mesh);
  59197. }
  59198. var defines = [];
  59199. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59200. var material = subMesh.getMaterial();
  59201. // Alpha test
  59202. if (material) {
  59203. if (material.needAlphaTesting()) {
  59204. defines.push("#define ALPHATEST");
  59205. }
  59206. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59207. attribs.push(BABYLON.VertexBuffer.UVKind);
  59208. defines.push("#define UV1");
  59209. }
  59210. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59211. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59212. defines.push("#define UV2");
  59213. }
  59214. }
  59215. // Bones
  59216. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59217. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59218. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59219. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59220. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  59221. }
  59222. else {
  59223. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59224. }
  59225. // Instances
  59226. if (useInstances) {
  59227. defines.push("#define INSTANCES");
  59228. attribs.push("world0");
  59229. attribs.push("world1");
  59230. attribs.push("world2");
  59231. attribs.push("world3");
  59232. }
  59233. // Get correct effect
  59234. var join = defines.join("\n");
  59235. if (this._cachedDefines !== join) {
  59236. this._cachedDefines = join;
  59237. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  59238. }
  59239. return this._volumetricLightScatteringPass.isReady();
  59240. };
  59241. /**
  59242. * Sets the new light position for light scattering effect
  59243. * @param {BABYLON.Vector3} The new custom light position
  59244. */
  59245. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  59246. this.customMeshPosition = position;
  59247. };
  59248. /**
  59249. * Returns the light position for light scattering effect
  59250. * @return {BABYLON.Vector3} The custom light position
  59251. */
  59252. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  59253. return this.customMeshPosition;
  59254. };
  59255. /**
  59256. * Disposes the internal assets and detaches the post-process from the camera
  59257. */
  59258. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  59259. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  59260. if (rttIndex !== -1) {
  59261. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  59262. }
  59263. this._volumetricLightScatteringRTT.dispose();
  59264. _super.prototype.dispose.call(this, camera);
  59265. };
  59266. /**
  59267. * Returns the render target texture used by the post-process
  59268. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  59269. */
  59270. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  59271. return this._volumetricLightScatteringRTT;
  59272. };
  59273. // Private methods
  59274. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  59275. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  59276. return true;
  59277. }
  59278. return false;
  59279. };
  59280. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  59281. var _this = this;
  59282. var engine = scene.getEngine();
  59283. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59284. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59285. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59286. this._volumetricLightScatteringRTT.renderList = null;
  59287. this._volumetricLightScatteringRTT.renderParticles = false;
  59288. var camera = this.getCamera();
  59289. if (camera) {
  59290. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59291. }
  59292. else {
  59293. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59294. }
  59295. // Custom render function for submeshes
  59296. var renderSubMesh = function (subMesh) {
  59297. var mesh = subMesh.getRenderingMesh();
  59298. if (_this._meshExcluded(mesh)) {
  59299. return;
  59300. }
  59301. var material = subMesh.getMaterial();
  59302. if (!material) {
  59303. return;
  59304. }
  59305. var scene = mesh.getScene();
  59306. var engine = scene.getEngine();
  59307. // Culling
  59308. engine.setState(material.backFaceCulling);
  59309. // Managing instances
  59310. var batch = mesh._getInstancesRenderList(subMesh._id);
  59311. if (batch.mustReturn) {
  59312. return;
  59313. }
  59314. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59315. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59316. var effect = _this._volumetricLightScatteringPass;
  59317. if (mesh === _this.mesh) {
  59318. if (subMesh.effect) {
  59319. effect = subMesh.effect;
  59320. }
  59321. else {
  59322. effect = material.getEffect();
  59323. }
  59324. }
  59325. engine.enableEffect(effect);
  59326. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  59327. if (mesh === _this.mesh) {
  59328. material.bind(mesh.getWorldMatrix(), mesh);
  59329. }
  59330. else {
  59331. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  59332. // Alpha test
  59333. if (material && material.needAlphaTesting()) {
  59334. var alphaTexture = material.getAlphaTestTexture();
  59335. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  59336. if (alphaTexture) {
  59337. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59338. }
  59339. }
  59340. // Bones
  59341. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59342. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59343. }
  59344. }
  59345. // Draw
  59346. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  59347. }
  59348. };
  59349. // Render target texture callbacks
  59350. var savedSceneClearColor;
  59351. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  59352. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  59353. savedSceneClearColor = scene.clearColor;
  59354. scene.clearColor = sceneClearColor;
  59355. });
  59356. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  59357. scene.clearColor = savedSceneClearColor;
  59358. });
  59359. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59360. var engine = scene.getEngine();
  59361. var index;
  59362. if (depthOnlySubMeshes.length) {
  59363. engine.setColorWrite(false);
  59364. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59365. renderSubMesh(depthOnlySubMeshes.data[index]);
  59366. }
  59367. engine.setColorWrite(true);
  59368. }
  59369. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59370. renderSubMesh(opaqueSubMeshes.data[index]);
  59371. }
  59372. engine.setAlphaTesting(true);
  59373. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59374. renderSubMesh(alphaTestSubMeshes.data[index]);
  59375. }
  59376. engine.setAlphaTesting(false);
  59377. if (transparentSubMeshes.length) {
  59378. // Sort sub meshes
  59379. for (index = 0; index < transparentSubMeshes.length; index++) {
  59380. var submesh = transparentSubMeshes.data[index];
  59381. var boundingInfo = submesh.getBoundingInfo();
  59382. if (boundingInfo && scene.activeCamera) {
  59383. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  59384. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  59385. }
  59386. }
  59387. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  59388. sortedArray.sort(function (a, b) {
  59389. // Alpha index first
  59390. if (a._alphaIndex > b._alphaIndex) {
  59391. return 1;
  59392. }
  59393. if (a._alphaIndex < b._alphaIndex) {
  59394. return -1;
  59395. }
  59396. // Then distance to camera
  59397. if (a._distanceToCamera < b._distanceToCamera) {
  59398. return 1;
  59399. }
  59400. if (a._distanceToCamera > b._distanceToCamera) {
  59401. return -1;
  59402. }
  59403. return 0;
  59404. });
  59405. // Render sub meshes
  59406. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59407. for (index = 0; index < sortedArray.length; index++) {
  59408. renderSubMesh(sortedArray[index]);
  59409. }
  59410. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59411. }
  59412. };
  59413. };
  59414. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  59415. var transform = scene.getTransformMatrix();
  59416. var meshPosition;
  59417. if (this.useCustomMeshPosition) {
  59418. meshPosition = this.customMeshPosition;
  59419. }
  59420. else if (this.attachedNode) {
  59421. meshPosition = this.attachedNode.position;
  59422. }
  59423. else {
  59424. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  59425. }
  59426. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  59427. this._screenCoordinates.x = pos.x / this._viewPort.width;
  59428. this._screenCoordinates.y = pos.y / this._viewPort.height;
  59429. if (this.invert)
  59430. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  59431. };
  59432. // Static methods
  59433. /**
  59434. * Creates a default mesh for the Volumeric Light Scattering post-process
  59435. * @param {string} The mesh name
  59436. * @param {BABYLON.Scene} The scene where to create the mesh
  59437. * @return {BABYLON.Mesh} the default mesh
  59438. */
  59439. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  59440. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  59441. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59442. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  59443. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  59444. mesh.material = material;
  59445. return mesh;
  59446. };
  59447. __decorate([
  59448. BABYLON.serializeAsVector3()
  59449. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  59450. __decorate([
  59451. BABYLON.serialize()
  59452. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  59453. __decorate([
  59454. BABYLON.serialize()
  59455. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  59456. __decorate([
  59457. BABYLON.serializeAsMeshReference()
  59458. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  59459. __decorate([
  59460. BABYLON.serialize()
  59461. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  59462. __decorate([
  59463. BABYLON.serialize()
  59464. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  59465. __decorate([
  59466. BABYLON.serialize()
  59467. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  59468. __decorate([
  59469. BABYLON.serialize()
  59470. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  59471. __decorate([
  59472. BABYLON.serialize()
  59473. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  59474. return VolumetricLightScatteringPostProcess;
  59475. }(BABYLON.PostProcess));
  59476. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  59477. })(BABYLON || (BABYLON = {}));
  59478. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  59479. //
  59480. // This post-process allows the modification of rendered colors by using
  59481. // a 'look-up table' (LUT). This effect is also called Color Grading.
  59482. //
  59483. // The object needs to be provided an url to a texture containing the color
  59484. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  59485. // Use an image editing software to tweak the LUT to match your needs.
  59486. //
  59487. // For an example of a color LUT, see here:
  59488. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  59489. // For explanations on color grading, see here:
  59490. // http://udn.epicgames.com/Three/ColorGrading.html
  59491. //
  59492. var BABYLON;
  59493. (function (BABYLON) {
  59494. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  59495. __extends(ColorCorrectionPostProcess, _super);
  59496. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  59497. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  59498. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59499. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  59500. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59501. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59502. _this.onApply = function (effect) {
  59503. effect.setTexture("colorTable", _this._colorTableTexture);
  59504. };
  59505. return _this;
  59506. }
  59507. return ColorCorrectionPostProcess;
  59508. }(BABYLON.PostProcess));
  59509. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  59510. })(BABYLON || (BABYLON = {}));
  59511. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  59512. var BABYLON;
  59513. (function (BABYLON) {
  59514. var TonemappingOperator;
  59515. (function (TonemappingOperator) {
  59516. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  59517. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  59518. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  59519. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  59520. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  59521. ;
  59522. var TonemapPostProcess = /** @class */ (function (_super) {
  59523. __extends(TonemapPostProcess, _super);
  59524. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  59525. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59526. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59527. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  59528. _this._operator = _operator;
  59529. _this.exposureAdjustment = exposureAdjustment;
  59530. var defines = "#define ";
  59531. if (_this._operator === TonemappingOperator.Hable)
  59532. defines += "HABLE_TONEMAPPING";
  59533. else if (_this._operator === TonemappingOperator.Reinhard)
  59534. defines += "REINHARD_TONEMAPPING";
  59535. else if (_this._operator === TonemappingOperator.HejiDawson)
  59536. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  59537. else if (_this._operator === TonemappingOperator.Photographic)
  59538. defines += "PHOTOGRAPHIC_TONEMAPPING";
  59539. //sadly a second call to create the effect.
  59540. _this.updateEffect(defines);
  59541. _this.onApply = function (effect) {
  59542. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  59543. };
  59544. return _this;
  59545. }
  59546. return TonemapPostProcess;
  59547. }(BABYLON.PostProcess));
  59548. BABYLON.TonemapPostProcess = TonemapPostProcess;
  59549. })(BABYLON || (BABYLON = {}));
  59550. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  59551. var BABYLON;
  59552. (function (BABYLON) {
  59553. var DisplayPassPostProcess = /** @class */ (function (_super) {
  59554. __extends(DisplayPassPostProcess, _super);
  59555. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  59556. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  59557. }
  59558. return DisplayPassPostProcess;
  59559. }(BABYLON.PostProcess));
  59560. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  59561. })(BABYLON || (BABYLON = {}));
  59562. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  59563. var BABYLON;
  59564. (function (BABYLON) {
  59565. var HighlightsPostProcess = /** @class */ (function (_super) {
  59566. __extends(HighlightsPostProcess, _super);
  59567. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59568. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59569. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  59570. }
  59571. return HighlightsPostProcess;
  59572. }(BABYLON.PostProcess));
  59573. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  59574. })(BABYLON || (BABYLON = {}));
  59575. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  59576. var BABYLON;
  59577. (function (BABYLON) {
  59578. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  59579. __extends(ImageProcessingPostProcess, _super);
  59580. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59581. if (camera === void 0) { camera = null; }
  59582. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59583. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  59584. _this._fromLinearSpace = true;
  59585. /**
  59586. * Defines cache preventing GC.
  59587. */
  59588. _this._defines = {
  59589. IMAGEPROCESSING: false,
  59590. VIGNETTE: false,
  59591. VIGNETTEBLENDMODEMULTIPLY: false,
  59592. VIGNETTEBLENDMODEOPAQUE: false,
  59593. TONEMAPPING: false,
  59594. CONTRAST: false,
  59595. COLORCURVES: false,
  59596. COLORGRADING: false,
  59597. COLORGRADING3D: false,
  59598. FROMLINEARSPACE: false,
  59599. SAMPLER3DGREENDEPTH: false,
  59600. SAMPLER3DBGRMAP: false,
  59601. IMAGEPROCESSINGPOSTPROCESS: false,
  59602. EXPOSURE: false,
  59603. };
  59604. // Setup the default processing configuration to the scene.
  59605. _this._attachImageProcessingConfiguration(null, true);
  59606. _this.imageProcessingConfiguration.applyByPostProcess = true;
  59607. _this.onApply = function (effect) {
  59608. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  59609. };
  59610. return _this;
  59611. }
  59612. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  59613. /**
  59614. * Gets the image processing configuration used either in this material.
  59615. */
  59616. get: function () {
  59617. return this._imageProcessingConfiguration;
  59618. },
  59619. /**
  59620. * Sets the Default image processing configuration used either in the this material.
  59621. *
  59622. * If sets to null, the scene one is in use.
  59623. */
  59624. set: function (value) {
  59625. this._attachImageProcessingConfiguration(value);
  59626. },
  59627. enumerable: true,
  59628. configurable: true
  59629. });
  59630. /**
  59631. * Attaches a new image processing configuration to the PBR Material.
  59632. * @param configuration
  59633. */
  59634. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  59635. var _this = this;
  59636. if (doNotBuild === void 0) { doNotBuild = false; }
  59637. if (configuration === this._imageProcessingConfiguration) {
  59638. return;
  59639. }
  59640. // Detaches observer.
  59641. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59642. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59643. }
  59644. // Pick the scene configuration if needed.
  59645. if (!configuration) {
  59646. var scene = null;
  59647. var engine = this.getEngine();
  59648. var camera = this.getCamera();
  59649. if (camera) {
  59650. scene = camera.getScene();
  59651. }
  59652. else if (engine && engine.scenes) {
  59653. var scenes = engine.scenes;
  59654. scene = scenes[scenes.length - 1];
  59655. }
  59656. else {
  59657. scene = BABYLON.Engine.LastCreatedScene;
  59658. }
  59659. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  59660. }
  59661. else {
  59662. this._imageProcessingConfiguration = configuration;
  59663. }
  59664. // Attaches observer.
  59665. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  59666. _this._updateParameters();
  59667. });
  59668. // Ensure the effect will be rebuilt.
  59669. if (!doNotBuild) {
  59670. this._updateParameters();
  59671. }
  59672. };
  59673. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  59674. /**
  59675. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59676. */
  59677. get: function () {
  59678. return this.imageProcessingConfiguration.colorCurves;
  59679. },
  59680. /**
  59681. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59682. */
  59683. set: function (value) {
  59684. this.imageProcessingConfiguration.colorCurves = value;
  59685. },
  59686. enumerable: true,
  59687. configurable: true
  59688. });
  59689. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  59690. /**
  59691. * Gets wether the color curves effect is enabled.
  59692. */
  59693. get: function () {
  59694. return this.imageProcessingConfiguration.colorCurvesEnabled;
  59695. },
  59696. /**
  59697. * Sets wether the color curves effect is enabled.
  59698. */
  59699. set: function (value) {
  59700. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  59701. },
  59702. enumerable: true,
  59703. configurable: true
  59704. });
  59705. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  59706. /**
  59707. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59708. */
  59709. get: function () {
  59710. return this.imageProcessingConfiguration.colorGradingTexture;
  59711. },
  59712. /**
  59713. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59714. */
  59715. set: function (value) {
  59716. this.imageProcessingConfiguration.colorGradingTexture = value;
  59717. },
  59718. enumerable: true,
  59719. configurable: true
  59720. });
  59721. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  59722. /**
  59723. * Gets wether the color grading effect is enabled.
  59724. */
  59725. get: function () {
  59726. return this.imageProcessingConfiguration.colorGradingEnabled;
  59727. },
  59728. /**
  59729. * Gets wether the color grading effect is enabled.
  59730. */
  59731. set: function (value) {
  59732. this.imageProcessingConfiguration.colorGradingEnabled = value;
  59733. },
  59734. enumerable: true,
  59735. configurable: true
  59736. });
  59737. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  59738. /**
  59739. * Gets exposure used in the effect.
  59740. */
  59741. get: function () {
  59742. return this.imageProcessingConfiguration.exposure;
  59743. },
  59744. /**
  59745. * Sets exposure used in the effect.
  59746. */
  59747. set: function (value) {
  59748. this.imageProcessingConfiguration.exposure = value;
  59749. },
  59750. enumerable: true,
  59751. configurable: true
  59752. });
  59753. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  59754. /**
  59755. * Gets wether tonemapping is enabled or not.
  59756. */
  59757. get: function () {
  59758. return this._imageProcessingConfiguration.toneMappingEnabled;
  59759. },
  59760. /**
  59761. * Sets wether tonemapping is enabled or not
  59762. */
  59763. set: function (value) {
  59764. this._imageProcessingConfiguration.toneMappingEnabled = value;
  59765. },
  59766. enumerable: true,
  59767. configurable: true
  59768. });
  59769. ;
  59770. ;
  59771. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  59772. /**
  59773. * Gets contrast used in the effect.
  59774. */
  59775. get: function () {
  59776. return this.imageProcessingConfiguration.contrast;
  59777. },
  59778. /**
  59779. * Sets contrast used in the effect.
  59780. */
  59781. set: function (value) {
  59782. this.imageProcessingConfiguration.contrast = value;
  59783. },
  59784. enumerable: true,
  59785. configurable: true
  59786. });
  59787. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  59788. /**
  59789. * Gets Vignette stretch size.
  59790. */
  59791. get: function () {
  59792. return this.imageProcessingConfiguration.vignetteStretch;
  59793. },
  59794. /**
  59795. * Sets Vignette stretch size.
  59796. */
  59797. set: function (value) {
  59798. this.imageProcessingConfiguration.vignetteStretch = value;
  59799. },
  59800. enumerable: true,
  59801. configurable: true
  59802. });
  59803. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  59804. /**
  59805. * Gets Vignette centre X Offset.
  59806. */
  59807. get: function () {
  59808. return this.imageProcessingConfiguration.vignetteCentreX;
  59809. },
  59810. /**
  59811. * Sets Vignette centre X Offset.
  59812. */
  59813. set: function (value) {
  59814. this.imageProcessingConfiguration.vignetteCentreX = value;
  59815. },
  59816. enumerable: true,
  59817. configurable: true
  59818. });
  59819. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  59820. /**
  59821. * Gets Vignette centre Y Offset.
  59822. */
  59823. get: function () {
  59824. return this.imageProcessingConfiguration.vignetteCentreY;
  59825. },
  59826. /**
  59827. * Sets Vignette centre Y Offset.
  59828. */
  59829. set: function (value) {
  59830. this.imageProcessingConfiguration.vignetteCentreY = value;
  59831. },
  59832. enumerable: true,
  59833. configurable: true
  59834. });
  59835. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  59836. /**
  59837. * Gets Vignette weight or intensity of the vignette effect.
  59838. */
  59839. get: function () {
  59840. return this.imageProcessingConfiguration.vignetteWeight;
  59841. },
  59842. /**
  59843. * Sets Vignette weight or intensity of the vignette effect.
  59844. */
  59845. set: function (value) {
  59846. this.imageProcessingConfiguration.vignetteWeight = value;
  59847. },
  59848. enumerable: true,
  59849. configurable: true
  59850. });
  59851. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  59852. /**
  59853. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  59854. * if vignetteEnabled is set to true.
  59855. */
  59856. get: function () {
  59857. return this.imageProcessingConfiguration.vignetteColor;
  59858. },
  59859. /**
  59860. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  59861. * if vignetteEnabled is set to true.
  59862. */
  59863. set: function (value) {
  59864. this.imageProcessingConfiguration.vignetteColor = value;
  59865. },
  59866. enumerable: true,
  59867. configurable: true
  59868. });
  59869. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  59870. /**
  59871. * Gets Camera field of view used by the Vignette effect.
  59872. */
  59873. get: function () {
  59874. return this.imageProcessingConfiguration.vignetteCameraFov;
  59875. },
  59876. /**
  59877. * Sets Camera field of view used by the Vignette effect.
  59878. */
  59879. set: function (value) {
  59880. this.imageProcessingConfiguration.vignetteCameraFov = value;
  59881. },
  59882. enumerable: true,
  59883. configurable: true
  59884. });
  59885. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  59886. /**
  59887. * Gets the vignette blend mode allowing different kind of effect.
  59888. */
  59889. get: function () {
  59890. return this.imageProcessingConfiguration.vignetteBlendMode;
  59891. },
  59892. /**
  59893. * Sets the vignette blend mode allowing different kind of effect.
  59894. */
  59895. set: function (value) {
  59896. this.imageProcessingConfiguration.vignetteBlendMode = value;
  59897. },
  59898. enumerable: true,
  59899. configurable: true
  59900. });
  59901. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  59902. /**
  59903. * Gets wether the vignette effect is enabled.
  59904. */
  59905. get: function () {
  59906. return this.imageProcessingConfiguration.vignetteEnabled;
  59907. },
  59908. /**
  59909. * Sets wether the vignette effect is enabled.
  59910. */
  59911. set: function (value) {
  59912. this.imageProcessingConfiguration.vignetteEnabled = value;
  59913. },
  59914. enumerable: true,
  59915. configurable: true
  59916. });
  59917. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  59918. /**
  59919. * Gets wether the input of the processing is in Gamma or Linear Space.
  59920. */
  59921. get: function () {
  59922. return this._fromLinearSpace;
  59923. },
  59924. /**
  59925. * Sets wether the input of the processing is in Gamma or Linear Space.
  59926. */
  59927. set: function (value) {
  59928. if (this._fromLinearSpace === value) {
  59929. return;
  59930. }
  59931. this._fromLinearSpace = value;
  59932. this._updateParameters();
  59933. },
  59934. enumerable: true,
  59935. configurable: true
  59936. });
  59937. ImageProcessingPostProcess.prototype.getClassName = function () {
  59938. return "ImageProcessingPostProcess";
  59939. };
  59940. ImageProcessingPostProcess.prototype._updateParameters = function () {
  59941. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  59942. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  59943. var defines = "";
  59944. for (var define in this._defines) {
  59945. if (this._defines[define]) {
  59946. defines += "#define " + define + ";\r\n";
  59947. }
  59948. }
  59949. var samplers = ["textureSampler"];
  59950. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  59951. var uniforms = ["scale"];
  59952. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  59953. this.updateEffect(defines, uniforms, samplers);
  59954. };
  59955. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  59956. _super.prototype.dispose.call(this, camera);
  59957. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59958. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59959. }
  59960. this.imageProcessingConfiguration.applyByPostProcess = false;
  59961. };
  59962. __decorate([
  59963. BABYLON.serialize()
  59964. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  59965. return ImageProcessingPostProcess;
  59966. }(BABYLON.PostProcess));
  59967. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  59968. })(BABYLON || (BABYLON = {}));
  59969. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  59970. var BABYLON;
  59971. (function (BABYLON) {
  59972. var BlurPostProcess = /** @class */ (function (_super) {
  59973. __extends(BlurPostProcess, _super);
  59974. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  59975. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59976. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59977. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  59978. _this.direction = direction;
  59979. _this._packedFloat = false;
  59980. _this.onApplyObservable.add(function (effect) {
  59981. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  59982. });
  59983. _this.kernel = kernel;
  59984. return _this;
  59985. }
  59986. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  59987. /**
  59988. * Gets the length in pixels of the blur sample region
  59989. */
  59990. get: function () {
  59991. return this._idealKernel;
  59992. },
  59993. /**
  59994. * Sets the length in pixels of the blur sample region
  59995. */
  59996. set: function (v) {
  59997. if (this._idealKernel === v) {
  59998. return;
  59999. }
  60000. v = Math.max(v, 1);
  60001. this._idealKernel = v;
  60002. this._kernel = this._nearestBestKernel(v);
  60003. this._updateParameters();
  60004. },
  60005. enumerable: true,
  60006. configurable: true
  60007. });
  60008. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60009. /**
  60010. * Gets wether or not the blur is unpacking/repacking floats
  60011. */
  60012. get: function () {
  60013. return this._packedFloat;
  60014. },
  60015. /**
  60016. * Sets wether or not the blur needs to unpack/repack floats
  60017. */
  60018. set: function (v) {
  60019. if (this._packedFloat === v) {
  60020. return;
  60021. }
  60022. this._packedFloat = v;
  60023. this._updateParameters();
  60024. },
  60025. enumerable: true,
  60026. configurable: true
  60027. });
  60028. BlurPostProcess.prototype._updateParameters = function () {
  60029. // Generate sampling offsets and weights
  60030. var N = this._kernel;
  60031. var centerIndex = (N - 1) / 2;
  60032. // Generate Gaussian sampling weights over kernel
  60033. var offsets = [];
  60034. var weights = [];
  60035. var totalWeight = 0;
  60036. for (var i = 0; i < N; i++) {
  60037. var u = i / (N - 1);
  60038. var w = this._gaussianWeight(u * 2.0 - 1);
  60039. offsets[i] = (i - centerIndex);
  60040. weights[i] = w;
  60041. totalWeight += w;
  60042. }
  60043. // Normalize weights
  60044. for (var i = 0; i < weights.length; i++) {
  60045. weights[i] /= totalWeight;
  60046. }
  60047. // Optimize: combine samples to take advantage of hardware linear sampling
  60048. // Walk from left to center, combining pairs (symmetrically)
  60049. var linearSamplingWeights = [];
  60050. var linearSamplingOffsets = [];
  60051. var linearSamplingMap = [];
  60052. for (var i = 0; i <= centerIndex; i += 2) {
  60053. var j = Math.min(i + 1, Math.floor(centerIndex));
  60054. var singleCenterSample = i === j;
  60055. if (singleCenterSample) {
  60056. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60057. }
  60058. else {
  60059. var sharedCell = j === centerIndex;
  60060. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60061. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60062. if (offsetLinear === 0) {
  60063. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60064. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60065. }
  60066. else {
  60067. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60068. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60069. }
  60070. }
  60071. }
  60072. for (var i = 0; i < linearSamplingMap.length; i++) {
  60073. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60074. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60075. }
  60076. // Replace with optimized
  60077. offsets = linearSamplingOffsets;
  60078. weights = linearSamplingWeights;
  60079. // Generate shaders
  60080. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  60081. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  60082. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  60083. var defines = "";
  60084. for (var i = 0; i < varyingCount; i++) {
  60085. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  60086. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  60087. }
  60088. var depCount = 0;
  60089. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  60090. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  60091. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  60092. depCount++;
  60093. }
  60094. if (this.packedFloat) {
  60095. defines += "#define PACKEDFLOAT 1";
  60096. }
  60097. this.updateEffect(defines, null, null, {
  60098. varyingCount: varyingCount,
  60099. depCount: depCount
  60100. });
  60101. };
  60102. /**
  60103. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  60104. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  60105. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  60106. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  60107. * The gaps between physical kernels are compensated for in the weighting of the samples
  60108. * @param idealKernel Ideal blur kernel.
  60109. * @return Nearest best kernel.
  60110. */
  60111. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  60112. var v = Math.round(idealKernel);
  60113. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  60114. var k = _a[_i];
  60115. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  60116. return Math.max(k, 3);
  60117. }
  60118. }
  60119. return Math.max(v, 3);
  60120. };
  60121. /**
  60122. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  60123. * @param x The point on the Gaussian distribution to sample.
  60124. * @return the value of the Gaussian function at x.
  60125. */
  60126. BlurPostProcess.prototype._gaussianWeight = function (x) {
  60127. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  60128. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  60129. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  60130. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  60131. // truncated at around 1.3% of peak strength.
  60132. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  60133. var sigma = (1 / 3);
  60134. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  60135. var exponent = -((x * x) / (2.0 * sigma * sigma));
  60136. var weight = (1.0 / denominator) * Math.exp(exponent);
  60137. return weight;
  60138. };
  60139. /**
  60140. * Generates a string that can be used as a floating point number in GLSL.
  60141. * @param x Value to print.
  60142. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  60143. * @return GLSL float string.
  60144. */
  60145. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  60146. if (decimalFigures === void 0) { decimalFigures = 8; }
  60147. return x.toFixed(decimalFigures).replace(/0+$/, '');
  60148. };
  60149. return BlurPostProcess;
  60150. }(BABYLON.PostProcess));
  60151. BABYLON.BlurPostProcess = BlurPostProcess;
  60152. })(BABYLON || (BABYLON = {}));
  60153. //# sourceMappingURL=babylon.blurPostProcess.js.map
  60154. var BABYLON;
  60155. (function (BABYLON) {
  60156. var Bone = /** @class */ (function (_super) {
  60157. __extends(Bone, _super);
  60158. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  60159. if (parentBone === void 0) { parentBone = null; }
  60160. if (localMatrix === void 0) { localMatrix = null; }
  60161. if (restPose === void 0) { restPose = null; }
  60162. if (baseMatrix === void 0) { baseMatrix = null; }
  60163. if (index === void 0) { index = null; }
  60164. var _this = _super.call(this, name, skeleton.getScene()) || this;
  60165. _this.name = name;
  60166. _this.children = new Array();
  60167. _this.animations = new Array();
  60168. // Set this value to map this bone to a different index in the transform matrices.
  60169. // Set this value to -1 to exclude the bone from the transform matrices.
  60170. _this._index = null;
  60171. _this._worldTransform = new BABYLON.Matrix();
  60172. _this._absoluteTransform = new BABYLON.Matrix();
  60173. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  60174. _this._scaleMatrix = BABYLON.Matrix.Identity();
  60175. _this._scaleVector = BABYLON.Vector3.One();
  60176. _this._negateScaleChildren = BABYLON.Vector3.One();
  60177. _this._scalingDeterminant = 1;
  60178. _this._skeleton = skeleton;
  60179. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  60180. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  60181. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  60182. _this._index = index;
  60183. skeleton.bones.push(_this);
  60184. _this.setParent(parentBone, false);
  60185. _this._updateDifferenceMatrix();
  60186. return _this;
  60187. }
  60188. Object.defineProperty(Bone.prototype, "_matrix", {
  60189. get: function () {
  60190. return this._localMatrix;
  60191. },
  60192. set: function (val) {
  60193. if (this._localMatrix) {
  60194. this._localMatrix.copyFrom(val);
  60195. }
  60196. else {
  60197. this._localMatrix = val;
  60198. }
  60199. },
  60200. enumerable: true,
  60201. configurable: true
  60202. });
  60203. // Members
  60204. Bone.prototype.getSkeleton = function () {
  60205. return this._skeleton;
  60206. };
  60207. Bone.prototype.getParent = function () {
  60208. return this._parent;
  60209. };
  60210. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  60211. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60212. if (this._parent === parent) {
  60213. return;
  60214. }
  60215. if (this._parent) {
  60216. var index = this._parent.children.indexOf(this);
  60217. if (index !== -1) {
  60218. this._parent.children.splice(index, 1);
  60219. }
  60220. }
  60221. this._parent = parent;
  60222. if (this._parent) {
  60223. this._parent.children.push(this);
  60224. }
  60225. if (updateDifferenceMatrix) {
  60226. this._updateDifferenceMatrix();
  60227. }
  60228. };
  60229. Bone.prototype.getLocalMatrix = function () {
  60230. return this._localMatrix;
  60231. };
  60232. Bone.prototype.getBaseMatrix = function () {
  60233. return this._baseMatrix;
  60234. };
  60235. Bone.prototype.getRestPose = function () {
  60236. return this._restPose;
  60237. };
  60238. Bone.prototype.returnToRest = function () {
  60239. this.updateMatrix(this._restPose.clone());
  60240. };
  60241. Bone.prototype.getWorldMatrix = function () {
  60242. return this._worldTransform;
  60243. };
  60244. Bone.prototype.getInvertedAbsoluteTransform = function () {
  60245. return this._invertedAbsoluteTransform;
  60246. };
  60247. Bone.prototype.getAbsoluteTransform = function () {
  60248. return this._absoluteTransform;
  60249. };
  60250. Object.defineProperty(Bone.prototype, "position", {
  60251. // Properties (matches AbstractMesh properties)
  60252. get: function () {
  60253. return this.getPosition();
  60254. },
  60255. set: function (newPosition) {
  60256. this.setPosition(newPosition);
  60257. },
  60258. enumerable: true,
  60259. configurable: true
  60260. });
  60261. Object.defineProperty(Bone.prototype, "rotation", {
  60262. get: function () {
  60263. return this.getRotation();
  60264. },
  60265. set: function (newRotation) {
  60266. this.setRotation(newRotation);
  60267. },
  60268. enumerable: true,
  60269. configurable: true
  60270. });
  60271. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  60272. get: function () {
  60273. return this.getRotationQuaternion();
  60274. },
  60275. set: function (newRotation) {
  60276. this.setRotationQuaternion(newRotation);
  60277. },
  60278. enumerable: true,
  60279. configurable: true
  60280. });
  60281. Object.defineProperty(Bone.prototype, "scaling", {
  60282. get: function () {
  60283. return this.getScale();
  60284. },
  60285. set: function (newScaling) {
  60286. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  60287. },
  60288. enumerable: true,
  60289. configurable: true
  60290. });
  60291. // Methods
  60292. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  60293. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60294. this._baseMatrix = matrix.clone();
  60295. this._localMatrix = matrix.clone();
  60296. this._skeleton._markAsDirty();
  60297. if (updateDifferenceMatrix) {
  60298. this._updateDifferenceMatrix();
  60299. }
  60300. };
  60301. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  60302. if (!rootMatrix) {
  60303. rootMatrix = this._baseMatrix;
  60304. }
  60305. if (this._parent) {
  60306. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60307. }
  60308. else {
  60309. this._absoluteTransform.copyFrom(rootMatrix);
  60310. }
  60311. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  60312. for (var index = 0; index < this.children.length; index++) {
  60313. this.children[index]._updateDifferenceMatrix();
  60314. }
  60315. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  60316. };
  60317. Bone.prototype.markAsDirty = function () {
  60318. this._currentRenderId++;
  60319. this._skeleton._markAsDirty();
  60320. };
  60321. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  60322. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60323. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  60324. // all animation may be coming from a library skeleton, so may need to create animation
  60325. if (this.animations.length === 0) {
  60326. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  60327. this.animations[0].setKeys([]);
  60328. }
  60329. // get animation info / verify there is such a range from the source bone
  60330. var sourceRange = source.animations[0].getRange(rangeName);
  60331. if (!sourceRange) {
  60332. return false;
  60333. }
  60334. var from = sourceRange.from;
  60335. var to = sourceRange.to;
  60336. var sourceKeys = source.animations[0].getKeys();
  60337. // rescaling prep
  60338. var sourceBoneLength = source.length;
  60339. var sourceParent = source.getParent();
  60340. var parent = this.getParent();
  60341. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  60342. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  60343. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  60344. var destKeys = this.animations[0].getKeys();
  60345. // loop vars declaration
  60346. var orig;
  60347. var origTranslation;
  60348. var mat;
  60349. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  60350. orig = sourceKeys[key];
  60351. if (orig.frame >= from && orig.frame <= to) {
  60352. if (rescaleAsRequired) {
  60353. mat = orig.value.clone();
  60354. // scale based on parent ratio, when bone has parent
  60355. if (parentScalingReqd) {
  60356. origTranslation = mat.getTranslation();
  60357. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  60358. // scale based on skeleton dimension ratio when root bone, and value is passed
  60359. }
  60360. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  60361. origTranslation = mat.getTranslation();
  60362. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  60363. // use original when root bone, and no data for skelDimensionsRatio
  60364. }
  60365. else {
  60366. mat = orig.value;
  60367. }
  60368. }
  60369. else {
  60370. mat = orig.value;
  60371. }
  60372. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  60373. }
  60374. }
  60375. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  60376. return true;
  60377. };
  60378. /**
  60379. * Translate the bone in local or world space.
  60380. * @param vec The amount to translate the bone.
  60381. * @param space The space that the translation is in.
  60382. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60383. */
  60384. Bone.prototype.translate = function (vec, space, mesh) {
  60385. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60386. var lm = this.getLocalMatrix();
  60387. if (space == BABYLON.Space.LOCAL) {
  60388. lm.m[12] += vec.x;
  60389. lm.m[13] += vec.y;
  60390. lm.m[14] += vec.z;
  60391. }
  60392. else {
  60393. var wm = null;
  60394. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60395. if (mesh) {
  60396. wm = mesh.getWorldMatrix();
  60397. }
  60398. this._skeleton.computeAbsoluteTransforms();
  60399. var tmat = Bone._tmpMats[0];
  60400. var tvec = Bone._tmpVecs[0];
  60401. if (this._parent) {
  60402. if (mesh && wm) {
  60403. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60404. tmat.multiplyToRef(wm, tmat);
  60405. }
  60406. else {
  60407. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60408. }
  60409. }
  60410. tmat.m[12] = 0;
  60411. tmat.m[13] = 0;
  60412. tmat.m[14] = 0;
  60413. tmat.invert();
  60414. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  60415. lm.m[12] += tvec.x;
  60416. lm.m[13] += tvec.y;
  60417. lm.m[14] += tvec.z;
  60418. }
  60419. this.markAsDirty();
  60420. };
  60421. /**
  60422. * Set the postion of the bone in local or world space.
  60423. * @param position The position to set the bone.
  60424. * @param space The space that the position is in.
  60425. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60426. */
  60427. Bone.prototype.setPosition = function (position, space, mesh) {
  60428. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60429. var lm = this.getLocalMatrix();
  60430. if (space == BABYLON.Space.LOCAL) {
  60431. lm.m[12] = position.x;
  60432. lm.m[13] = position.y;
  60433. lm.m[14] = position.z;
  60434. }
  60435. else {
  60436. var wm = null;
  60437. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60438. if (mesh) {
  60439. wm = mesh.getWorldMatrix();
  60440. }
  60441. this._skeleton.computeAbsoluteTransforms();
  60442. var tmat = Bone._tmpMats[0];
  60443. var vec = Bone._tmpVecs[0];
  60444. if (this._parent) {
  60445. if (mesh && wm) {
  60446. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60447. tmat.multiplyToRef(wm, tmat);
  60448. }
  60449. else {
  60450. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60451. }
  60452. }
  60453. tmat.invert();
  60454. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  60455. lm.m[12] = vec.x;
  60456. lm.m[13] = vec.y;
  60457. lm.m[14] = vec.z;
  60458. }
  60459. this.markAsDirty();
  60460. };
  60461. /**
  60462. * Set the absolute postion of the bone (world space).
  60463. * @param position The position to set the bone.
  60464. * @param mesh The mesh that this bone is attached to.
  60465. */
  60466. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  60467. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  60468. };
  60469. /**
  60470. * Set the scale of the bone on the x, y and z axes.
  60471. * @param x The scale of the bone on the x axis.
  60472. * @param x The scale of the bone on the y axis.
  60473. * @param z The scale of the bone on the z axis.
  60474. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60475. */
  60476. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  60477. if (scaleChildren === void 0) { scaleChildren = false; }
  60478. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  60479. if (!scaleChildren) {
  60480. this._negateScaleChildren.x = 1 / x;
  60481. this._negateScaleChildren.y = 1 / y;
  60482. this._negateScaleChildren.z = 1 / z;
  60483. }
  60484. this._syncScaleVector();
  60485. }
  60486. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  60487. };
  60488. /**
  60489. * Scale the bone on the x, y and z axes.
  60490. * @param x The amount to scale the bone on the x axis.
  60491. * @param x The amount to scale the bone on the y axis.
  60492. * @param z The amount to scale the bone on the z axis.
  60493. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60494. */
  60495. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  60496. if (scaleChildren === void 0) { scaleChildren = false; }
  60497. var locMat = this.getLocalMatrix();
  60498. var origLocMat = Bone._tmpMats[0];
  60499. origLocMat.copyFrom(locMat);
  60500. var origLocMatInv = Bone._tmpMats[1];
  60501. origLocMatInv.copyFrom(origLocMat);
  60502. origLocMatInv.invert();
  60503. var scaleMat = Bone._tmpMats[2];
  60504. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  60505. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  60506. this._scaleVector.x *= x;
  60507. this._scaleVector.y *= y;
  60508. this._scaleVector.z *= z;
  60509. locMat.multiplyToRef(origLocMatInv, locMat);
  60510. locMat.multiplyToRef(scaleMat, locMat);
  60511. locMat.multiplyToRef(origLocMat, locMat);
  60512. var parent = this.getParent();
  60513. if (parent) {
  60514. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  60515. }
  60516. else {
  60517. this.getAbsoluteTransform().copyFrom(locMat);
  60518. }
  60519. var len = this.children.length;
  60520. scaleMat.invert();
  60521. for (var i = 0; i < len; i++) {
  60522. var child = this.children[i];
  60523. var cm = child.getLocalMatrix();
  60524. cm.multiplyToRef(scaleMat, cm);
  60525. var lm = child.getLocalMatrix();
  60526. lm.m[12] *= x;
  60527. lm.m[13] *= y;
  60528. lm.m[14] *= z;
  60529. }
  60530. this.computeAbsoluteTransforms();
  60531. if (scaleChildren) {
  60532. for (var i = 0; i < len; i++) {
  60533. this.children[i].scale(x, y, z, scaleChildren);
  60534. }
  60535. }
  60536. this.markAsDirty();
  60537. };
  60538. /**
  60539. * Set the yaw, pitch, and roll of the bone in local or world space.
  60540. * @param yaw The rotation of the bone on the y axis.
  60541. * @param pitch The rotation of the bone on the x axis.
  60542. * @param roll The rotation of the bone on the z axis.
  60543. * @param space The space that the axes of rotation are in.
  60544. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60545. */
  60546. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  60547. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60548. var rotMat = Bone._tmpMats[0];
  60549. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  60550. var rotMatInv = Bone._tmpMats[1];
  60551. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60552. rotMatInv.multiplyToRef(rotMat, rotMat);
  60553. this._rotateWithMatrix(rotMat, space, mesh);
  60554. };
  60555. /**
  60556. * Rotate the bone on an axis in local or world space.
  60557. * @param axis The axis to rotate the bone on.
  60558. * @param amount The amount to rotate the bone.
  60559. * @param space The space that the axis is in.
  60560. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60561. */
  60562. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  60563. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60564. var rmat = Bone._tmpMats[0];
  60565. rmat.m[12] = 0;
  60566. rmat.m[13] = 0;
  60567. rmat.m[14] = 0;
  60568. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  60569. this._rotateWithMatrix(rmat, space, mesh);
  60570. };
  60571. /**
  60572. * Set the rotation of the bone to a particular axis angle in local or world space.
  60573. * @param axis The axis to rotate the bone on.
  60574. * @param angle The angle that the bone should be rotated to.
  60575. * @param space The space that the axis is in.
  60576. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60577. */
  60578. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  60579. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60580. var rotMat = Bone._tmpMats[0];
  60581. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  60582. var rotMatInv = Bone._tmpMats[1];
  60583. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60584. rotMatInv.multiplyToRef(rotMat, rotMat);
  60585. this._rotateWithMatrix(rotMat, space, mesh);
  60586. };
  60587. /**
  60588. * Set the euler rotation of the bone in local of world space.
  60589. * @param rotation The euler rotation that the bone should be set to.
  60590. * @param space The space that the rotation is in.
  60591. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60592. */
  60593. Bone.prototype.setRotation = function (rotation, space, mesh) {
  60594. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60595. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  60596. };
  60597. /**
  60598. * Set the quaternion rotation of the bone in local of world space.
  60599. * @param quat The quaternion rotation that the bone should be set to.
  60600. * @param space The space that the rotation is in.
  60601. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60602. */
  60603. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  60604. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60605. var rotMatInv = Bone._tmpMats[0];
  60606. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60607. var rotMat = Bone._tmpMats[1];
  60608. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  60609. rotMatInv.multiplyToRef(rotMat, rotMat);
  60610. this._rotateWithMatrix(rotMat, space, mesh);
  60611. };
  60612. /**
  60613. * Set the rotation matrix of the bone in local of world space.
  60614. * @param rotMat The rotation matrix that the bone should be set to.
  60615. * @param space The space that the rotation is in.
  60616. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60617. */
  60618. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  60619. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60620. var rotMatInv = Bone._tmpMats[0];
  60621. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60622. var rotMat2 = Bone._tmpMats[1];
  60623. rotMat2.copyFrom(rotMat);
  60624. rotMatInv.multiplyToRef(rotMat, rotMat2);
  60625. this._rotateWithMatrix(rotMat2, space, mesh);
  60626. };
  60627. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  60628. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60629. var lmat = this.getLocalMatrix();
  60630. var lx = lmat.m[12];
  60631. var ly = lmat.m[13];
  60632. var lz = lmat.m[14];
  60633. var parent = this.getParent();
  60634. var parentScale = Bone._tmpMats[3];
  60635. var parentScaleInv = Bone._tmpMats[4];
  60636. if (parent) {
  60637. if (space == BABYLON.Space.WORLD) {
  60638. if (mesh) {
  60639. parentScale.copyFrom(mesh.getWorldMatrix());
  60640. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  60641. }
  60642. else {
  60643. parentScale.copyFrom(parent.getAbsoluteTransform());
  60644. }
  60645. }
  60646. else {
  60647. parentScale = parent._scaleMatrix;
  60648. }
  60649. parentScaleInv.copyFrom(parentScale);
  60650. parentScaleInv.invert();
  60651. lmat.multiplyToRef(parentScale, lmat);
  60652. lmat.multiplyToRef(rmat, lmat);
  60653. lmat.multiplyToRef(parentScaleInv, lmat);
  60654. }
  60655. else {
  60656. if (space == BABYLON.Space.WORLD && mesh) {
  60657. parentScale.copyFrom(mesh.getWorldMatrix());
  60658. parentScaleInv.copyFrom(parentScale);
  60659. parentScaleInv.invert();
  60660. lmat.multiplyToRef(parentScale, lmat);
  60661. lmat.multiplyToRef(rmat, lmat);
  60662. lmat.multiplyToRef(parentScaleInv, lmat);
  60663. }
  60664. else {
  60665. lmat.multiplyToRef(rmat, lmat);
  60666. }
  60667. }
  60668. lmat.m[12] = lx;
  60669. lmat.m[13] = ly;
  60670. lmat.m[14] = lz;
  60671. this.computeAbsoluteTransforms();
  60672. this.markAsDirty();
  60673. };
  60674. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  60675. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60676. if (space == BABYLON.Space.WORLD) {
  60677. var scaleMatrix = Bone._tmpMats[2];
  60678. scaleMatrix.copyFrom(this._scaleMatrix);
  60679. rotMatInv.copyFrom(this.getAbsoluteTransform());
  60680. if (mesh) {
  60681. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  60682. var meshScale = Bone._tmpMats[3];
  60683. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  60684. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  60685. }
  60686. rotMatInv.invert();
  60687. scaleMatrix.m[0] *= this._scalingDeterminant;
  60688. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60689. }
  60690. else {
  60691. rotMatInv.copyFrom(this.getLocalMatrix());
  60692. rotMatInv.invert();
  60693. var scaleMatrix = Bone._tmpMats[2];
  60694. scaleMatrix.copyFrom(this._scaleMatrix);
  60695. if (this._parent) {
  60696. var pscaleMatrix = Bone._tmpMats[3];
  60697. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  60698. pscaleMatrix.invert();
  60699. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  60700. }
  60701. else {
  60702. scaleMatrix.m[0] *= this._scalingDeterminant;
  60703. }
  60704. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60705. }
  60706. };
  60707. /**
  60708. * Get the scale of the bone
  60709. * @returns the scale of the bone
  60710. */
  60711. Bone.prototype.getScale = function () {
  60712. return this._scaleVector.clone();
  60713. };
  60714. /**
  60715. * Copy the scale of the bone to a vector3.
  60716. * @param result The vector3 to copy the scale to
  60717. */
  60718. Bone.prototype.getScaleToRef = function (result) {
  60719. result.copyFrom(this._scaleVector);
  60720. };
  60721. /**
  60722. * Get the position of the bone in local or world space.
  60723. * @param space The space that the returned position is in.
  60724. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60725. * @returns The position of the bone
  60726. */
  60727. Bone.prototype.getPosition = function (space, mesh) {
  60728. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60729. if (mesh === void 0) { mesh = null; }
  60730. var pos = BABYLON.Vector3.Zero();
  60731. this.getPositionToRef(space, mesh, pos);
  60732. return pos;
  60733. };
  60734. /**
  60735. * Copy the position of the bone to a vector3 in local or world space.
  60736. * @param space The space that the returned position is in.
  60737. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60738. * @param result The vector3 to copy the position to.
  60739. */
  60740. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  60741. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60742. if (space == BABYLON.Space.LOCAL) {
  60743. var lm = this.getLocalMatrix();
  60744. result.x = lm.m[12];
  60745. result.y = lm.m[13];
  60746. result.z = lm.m[14];
  60747. }
  60748. else {
  60749. var wm = null;
  60750. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60751. if (mesh) {
  60752. wm = mesh.getWorldMatrix();
  60753. }
  60754. this._skeleton.computeAbsoluteTransforms();
  60755. var tmat = Bone._tmpMats[0];
  60756. if (mesh && wm) {
  60757. tmat.copyFrom(this.getAbsoluteTransform());
  60758. tmat.multiplyToRef(wm, tmat);
  60759. }
  60760. else {
  60761. tmat = this.getAbsoluteTransform();
  60762. }
  60763. result.x = tmat.m[12];
  60764. result.y = tmat.m[13];
  60765. result.z = tmat.m[14];
  60766. }
  60767. };
  60768. /**
  60769. * Get the absolute position of the bone (world space).
  60770. * @param mesh The mesh that this bone is attached to.
  60771. * @returns The absolute position of the bone
  60772. */
  60773. Bone.prototype.getAbsolutePosition = function (mesh) {
  60774. if (mesh === void 0) { mesh = null; }
  60775. var pos = BABYLON.Vector3.Zero();
  60776. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  60777. return pos;
  60778. };
  60779. /**
  60780. * Copy the absolute position of the bone (world space) to the result param.
  60781. * @param mesh The mesh that this bone is attached to.
  60782. * @param result The vector3 to copy the absolute position to.
  60783. */
  60784. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  60785. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  60786. };
  60787. /**
  60788. * Compute the absolute transforms of this bone and its children.
  60789. */
  60790. Bone.prototype.computeAbsoluteTransforms = function () {
  60791. if (this._parent) {
  60792. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60793. }
  60794. else {
  60795. this._absoluteTransform.copyFrom(this._localMatrix);
  60796. var poseMatrix = this._skeleton.getPoseMatrix();
  60797. if (poseMatrix) {
  60798. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  60799. }
  60800. }
  60801. var children = this.children;
  60802. var len = children.length;
  60803. for (var i = 0; i < len; i++) {
  60804. children[i].computeAbsoluteTransforms();
  60805. }
  60806. };
  60807. Bone.prototype._syncScaleVector = function () {
  60808. var lm = this.getLocalMatrix();
  60809. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  60810. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  60811. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  60812. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  60813. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  60814. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  60815. this._scaleVector.x = xs * Math.sqrt(xsq);
  60816. this._scaleVector.y = ys * Math.sqrt(ysq);
  60817. this._scaleVector.z = zs * Math.sqrt(zsq);
  60818. if (this._parent) {
  60819. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  60820. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  60821. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  60822. }
  60823. 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);
  60824. };
  60825. /**
  60826. * Get the world direction from an axis that is in the local space of the bone.
  60827. * @param localAxis The local direction that is used to compute the world direction.
  60828. * @param mesh The mesh that this bone is attached to.
  60829. * @returns The world direction
  60830. */
  60831. Bone.prototype.getDirection = function (localAxis, mesh) {
  60832. if (mesh === void 0) { mesh = null; }
  60833. var result = BABYLON.Vector3.Zero();
  60834. this.getDirectionToRef(localAxis, mesh, result);
  60835. return result;
  60836. };
  60837. /**
  60838. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  60839. * @param localAxis The local direction that is used to compute the world direction.
  60840. * @param mesh The mesh that this bone is attached to.
  60841. * @param result The vector3 that the world direction will be copied to.
  60842. */
  60843. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  60844. if (mesh === void 0) { mesh = null; }
  60845. var wm = null;
  60846. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60847. if (mesh) {
  60848. wm = mesh.getWorldMatrix();
  60849. }
  60850. this._skeleton.computeAbsoluteTransforms();
  60851. var mat = Bone._tmpMats[0];
  60852. mat.copyFrom(this.getAbsoluteTransform());
  60853. if (mesh && wm) {
  60854. mat.multiplyToRef(wm, mat);
  60855. }
  60856. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  60857. result.normalize();
  60858. };
  60859. /**
  60860. * Get the euler rotation of the bone in local or world space.
  60861. * @param space The space that the rotation should be in.
  60862. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60863. * @returns The euler rotation
  60864. */
  60865. Bone.prototype.getRotation = function (space, mesh) {
  60866. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60867. if (mesh === void 0) { mesh = null; }
  60868. var result = BABYLON.Vector3.Zero();
  60869. this.getRotationToRef(space, mesh, result);
  60870. return result;
  60871. };
  60872. /**
  60873. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  60874. * @param space The space that the rotation should be in.
  60875. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60876. * @param result The vector3 that the rotation should be copied to.
  60877. */
  60878. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  60879. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60880. if (mesh === void 0) { mesh = null; }
  60881. var quat = Bone._tmpQuat;
  60882. this.getRotationQuaternionToRef(space, mesh, quat);
  60883. quat.toEulerAnglesToRef(result);
  60884. };
  60885. /**
  60886. * Get the quaternion rotation of the bone in either local or world space.
  60887. * @param space The space that the rotation should be in.
  60888. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60889. * @returns The quaternion rotation
  60890. */
  60891. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  60892. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60893. if (mesh === void 0) { mesh = null; }
  60894. var result = BABYLON.Quaternion.Identity();
  60895. this.getRotationQuaternionToRef(space, mesh, result);
  60896. return result;
  60897. };
  60898. /**
  60899. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  60900. * @param space The space that the rotation should be in.
  60901. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60902. * @param result The quaternion that the rotation should be copied to.
  60903. */
  60904. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  60905. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60906. if (mesh === void 0) { mesh = null; }
  60907. if (space == BABYLON.Space.LOCAL) {
  60908. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  60909. }
  60910. else {
  60911. var mat = Bone._tmpMats[0];
  60912. var amat = this.getAbsoluteTransform();
  60913. if (mesh) {
  60914. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  60915. }
  60916. else {
  60917. mat.copyFrom(amat);
  60918. }
  60919. mat.m[0] *= this._scalingDeterminant;
  60920. mat.m[1] *= this._scalingDeterminant;
  60921. mat.m[2] *= this._scalingDeterminant;
  60922. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  60923. }
  60924. };
  60925. /**
  60926. * Get the rotation matrix of the bone in local or world space.
  60927. * @param space The space that the rotation should be in.
  60928. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60929. * @returns The rotation matrix
  60930. */
  60931. Bone.prototype.getRotationMatrix = function (space, mesh) {
  60932. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60933. var result = BABYLON.Matrix.Identity();
  60934. this.getRotationMatrixToRef(space, mesh, result);
  60935. return result;
  60936. };
  60937. /**
  60938. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  60939. * @param space The space that the rotation should be in.
  60940. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60941. * @param result The quaternion that the rotation should be copied to.
  60942. */
  60943. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  60944. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60945. if (space == BABYLON.Space.LOCAL) {
  60946. this.getLocalMatrix().getRotationMatrixToRef(result);
  60947. }
  60948. else {
  60949. var mat = Bone._tmpMats[0];
  60950. var amat = this.getAbsoluteTransform();
  60951. if (mesh) {
  60952. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  60953. }
  60954. else {
  60955. mat.copyFrom(amat);
  60956. }
  60957. mat.m[0] *= this._scalingDeterminant;
  60958. mat.m[1] *= this._scalingDeterminant;
  60959. mat.m[2] *= this._scalingDeterminant;
  60960. mat.getRotationMatrixToRef(result);
  60961. }
  60962. };
  60963. /**
  60964. * Get the world position of a point that is in the local space of the bone.
  60965. * @param position The local position
  60966. * @param mesh The mesh that this bone is attached to.
  60967. * @returns The world position
  60968. */
  60969. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  60970. if (mesh === void 0) { mesh = null; }
  60971. var result = BABYLON.Vector3.Zero();
  60972. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  60973. return result;
  60974. };
  60975. /**
  60976. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  60977. * @param position The local position
  60978. * @param mesh The mesh that this bone is attached to.
  60979. * @param result The vector3 that the world position should be copied to.
  60980. */
  60981. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  60982. if (mesh === void 0) { mesh = null; }
  60983. var wm = null;
  60984. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60985. if (mesh) {
  60986. wm = mesh.getWorldMatrix();
  60987. }
  60988. this._skeleton.computeAbsoluteTransforms();
  60989. var tmat = Bone._tmpMats[0];
  60990. if (mesh && wm) {
  60991. tmat.copyFrom(this.getAbsoluteTransform());
  60992. tmat.multiplyToRef(wm, tmat);
  60993. }
  60994. else {
  60995. tmat = this.getAbsoluteTransform();
  60996. }
  60997. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  60998. };
  60999. /**
  61000. * Get the local position of a point that is in world space.
  61001. * @param position The world position
  61002. * @param mesh The mesh that this bone is attached to.
  61003. * @returns The local position
  61004. */
  61005. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61006. if (mesh === void 0) { mesh = null; }
  61007. var result = BABYLON.Vector3.Zero();
  61008. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61009. return result;
  61010. };
  61011. /**
  61012. * Get the local position of a point that is in world space and copy it to the result param.
  61013. * @param position The world position
  61014. * @param mesh The mesh that this bone is attached to.
  61015. * @param result The vector3 that the local position should be copied to.
  61016. */
  61017. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61018. if (mesh === void 0) { mesh = null; }
  61019. var wm = null;
  61020. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61021. if (mesh) {
  61022. wm = mesh.getWorldMatrix();
  61023. }
  61024. this._skeleton.computeAbsoluteTransforms();
  61025. var tmat = Bone._tmpMats[0];
  61026. tmat.copyFrom(this.getAbsoluteTransform());
  61027. if (mesh && wm) {
  61028. tmat.multiplyToRef(wm, tmat);
  61029. }
  61030. tmat.invert();
  61031. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61032. };
  61033. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61034. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61035. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61036. return Bone;
  61037. }(BABYLON.Node));
  61038. BABYLON.Bone = Bone;
  61039. })(BABYLON || (BABYLON = {}));
  61040. //# sourceMappingURL=babylon.bone.js.map
  61041. var BABYLON;
  61042. (function (BABYLON) {
  61043. var BoneIKController = /** @class */ (function () {
  61044. function BoneIKController(mesh, bone, options) {
  61045. this.targetPosition = BABYLON.Vector3.Zero();
  61046. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61047. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61048. this.poleAngle = 0;
  61049. this.slerpAmount = 1;
  61050. this._bone1Quat = BABYLON.Quaternion.Identity();
  61051. this._bone1Mat = BABYLON.Matrix.Identity();
  61052. this._bone2Ang = Math.PI;
  61053. this._maxAngle = Math.PI;
  61054. this._rightHandedSystem = false;
  61055. this._bendAxis = BABYLON.Vector3.Right();
  61056. this._slerping = false;
  61057. this._adjustRoll = 0;
  61058. this._bone2 = bone;
  61059. this._bone1 = bone.getParent();
  61060. if (!this._bone1) {
  61061. return;
  61062. }
  61063. this.mesh = mesh;
  61064. var bonePos = bone.getPosition();
  61065. if (bone.getAbsoluteTransform().determinant() > 0) {
  61066. this._rightHandedSystem = true;
  61067. this._bendAxis.x = 0;
  61068. this._bendAxis.y = 0;
  61069. this._bendAxis.z = -1;
  61070. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61071. this._adjustRoll = Math.PI * .5;
  61072. this._bendAxis.z = 1;
  61073. }
  61074. }
  61075. if (this._bone1.length) {
  61076. var boneScale1 = this._bone1.getScale();
  61077. var boneScale2 = this._bone2.getScale();
  61078. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  61079. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  61080. }
  61081. else if (this._bone1.children[0]) {
  61082. mesh.computeWorldMatrix(true);
  61083. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  61084. var pos2 = this._bone2.getAbsolutePosition(mesh);
  61085. var pos3 = this._bone1.getAbsolutePosition(mesh);
  61086. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  61087. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  61088. }
  61089. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  61090. this.maxAngle = Math.PI;
  61091. if (options) {
  61092. if (options.targetMesh) {
  61093. this.targetMesh = options.targetMesh;
  61094. this.targetMesh.computeWorldMatrix(true);
  61095. }
  61096. if (options.poleTargetMesh) {
  61097. this.poleTargetMesh = options.poleTargetMesh;
  61098. this.poleTargetMesh.computeWorldMatrix(true);
  61099. }
  61100. else if (options.poleTargetBone) {
  61101. this.poleTargetBone = options.poleTargetBone;
  61102. }
  61103. else if (this._bone1.getParent()) {
  61104. this.poleTargetBone = this._bone1.getParent();
  61105. }
  61106. if (options.poleTargetLocalOffset) {
  61107. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  61108. }
  61109. if (options.poleAngle) {
  61110. this.poleAngle = options.poleAngle;
  61111. }
  61112. if (options.bendAxis) {
  61113. this._bendAxis.copyFrom(options.bendAxis);
  61114. }
  61115. if (options.maxAngle) {
  61116. this.maxAngle = options.maxAngle;
  61117. }
  61118. if (options.slerpAmount) {
  61119. this.slerpAmount = options.slerpAmount;
  61120. }
  61121. }
  61122. }
  61123. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  61124. get: function () {
  61125. return this._maxAngle;
  61126. },
  61127. set: function (value) {
  61128. this._setMaxAngle(value);
  61129. },
  61130. enumerable: true,
  61131. configurable: true
  61132. });
  61133. BoneIKController.prototype._setMaxAngle = function (ang) {
  61134. if (ang < 0) {
  61135. ang = 0;
  61136. }
  61137. if (ang > Math.PI || ang == undefined) {
  61138. ang = Math.PI;
  61139. }
  61140. this._maxAngle = ang;
  61141. var a = this._bone1Length;
  61142. var b = this._bone2Length;
  61143. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  61144. };
  61145. BoneIKController.prototype.update = function () {
  61146. var bone1 = this._bone1;
  61147. if (!bone1) {
  61148. return;
  61149. }
  61150. var target = this.targetPosition;
  61151. var poleTarget = this.poleTargetPosition;
  61152. var mat1 = BoneIKController._tmpMats[0];
  61153. var mat2 = BoneIKController._tmpMats[1];
  61154. if (this.targetMesh) {
  61155. target.copyFrom(this.targetMesh.getAbsolutePosition());
  61156. }
  61157. if (this.poleTargetBone) {
  61158. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  61159. }
  61160. else if (this.poleTargetMesh) {
  61161. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  61162. }
  61163. var bonePos = BoneIKController._tmpVecs[0];
  61164. var zaxis = BoneIKController._tmpVecs[1];
  61165. var xaxis = BoneIKController._tmpVecs[2];
  61166. var yaxis = BoneIKController._tmpVecs[3];
  61167. var upAxis = BoneIKController._tmpVecs[4];
  61168. var _tmpQuat = BoneIKController._tmpQuat;
  61169. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  61170. poleTarget.subtractToRef(bonePos, upAxis);
  61171. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  61172. upAxis.y = 1;
  61173. }
  61174. else {
  61175. upAxis.normalize();
  61176. }
  61177. target.subtractToRef(bonePos, yaxis);
  61178. yaxis.normalize();
  61179. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  61180. zaxis.normalize();
  61181. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  61182. xaxis.normalize();
  61183. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  61184. var a = this._bone1Length;
  61185. var b = this._bone2Length;
  61186. var c = BABYLON.Vector3.Distance(bonePos, target);
  61187. if (this._maxReach > 0) {
  61188. c = Math.min(this._maxReach, c);
  61189. }
  61190. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  61191. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  61192. if (acosa > 1) {
  61193. acosa = 1;
  61194. }
  61195. if (acosb > 1) {
  61196. acosb = 1;
  61197. }
  61198. if (acosa < -1) {
  61199. acosa = -1;
  61200. }
  61201. if (acosb < -1) {
  61202. acosb = -1;
  61203. }
  61204. var angA = Math.acos(acosa);
  61205. var angB = Math.acos(acosb);
  61206. var angC = -angA - angB;
  61207. if (this._rightHandedSystem) {
  61208. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  61209. mat2.multiplyToRef(mat1, mat1);
  61210. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  61211. mat2.multiplyToRef(mat1, mat1);
  61212. }
  61213. else {
  61214. var _tmpVec = BoneIKController._tmpVecs[5];
  61215. _tmpVec.copyFrom(this._bendAxis);
  61216. _tmpVec.x *= -1;
  61217. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  61218. mat2.multiplyToRef(mat1, mat1);
  61219. }
  61220. if (this.poleAngle) {
  61221. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  61222. mat1.multiplyToRef(mat2, mat1);
  61223. }
  61224. if (this._bone1) {
  61225. if (this.slerpAmount < 1) {
  61226. if (!this._slerping) {
  61227. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  61228. }
  61229. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  61230. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  61231. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  61232. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  61233. this._slerping = true;
  61234. }
  61235. else {
  61236. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  61237. this._bone1Mat.copyFrom(mat1);
  61238. this._slerping = false;
  61239. }
  61240. }
  61241. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  61242. this._bone2Ang = angC;
  61243. };
  61244. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61245. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  61246. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61247. return BoneIKController;
  61248. }());
  61249. BABYLON.BoneIKController = BoneIKController;
  61250. })(BABYLON || (BABYLON = {}));
  61251. //# sourceMappingURL=babylon.boneIKController.js.map
  61252. var BABYLON;
  61253. (function (BABYLON) {
  61254. var BoneLookController = /** @class */ (function () {
  61255. /**
  61256. * Create a BoneLookController
  61257. * @param mesh the mesh that the bone belongs to
  61258. * @param bone the bone that will be looking to the target
  61259. * @param target the target Vector3 to look at
  61260. * @param settings optional settings:
  61261. * - maxYaw: the maximum angle the bone will yaw to
  61262. * - minYaw: the minimum angle the bone will yaw to
  61263. * - maxPitch: the maximum angle the bone will pitch to
  61264. * - minPitch: the minimum angle the bone will yaw to
  61265. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  61266. * - upAxis: the up axis of the coordinate system
  61267. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61268. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  61269. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  61270. * - adjustYaw: used to make an adjustment to the yaw of the bone
  61271. * - adjustPitch: used to make an adjustment to the pitch of the bone
  61272. * - adjustRoll: used to make an adjustment to the roll of the bone
  61273. **/
  61274. function BoneLookController(mesh, bone, target, options) {
  61275. /**
  61276. * The up axis of the coordinate system that is used when the bone is rotated.
  61277. */
  61278. this.upAxis = BABYLON.Vector3.Up();
  61279. /**
  61280. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61281. */
  61282. this.upAxisSpace = BABYLON.Space.LOCAL;
  61283. /**
  61284. * Used to make an adjustment to the yaw of the bone.
  61285. */
  61286. this.adjustYaw = 0;
  61287. /**
  61288. * Used to make an adjustment to the pitch of the bone.
  61289. */
  61290. this.adjustPitch = 0;
  61291. /**
  61292. * Used to make an adjustment to the roll of the bone.
  61293. */
  61294. this.adjustRoll = 0;
  61295. /**
  61296. * 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).
  61297. */
  61298. this.slerpAmount = 1;
  61299. this._boneQuat = BABYLON.Quaternion.Identity();
  61300. this._slerping = false;
  61301. this._firstFrameSkipped = false;
  61302. this._fowardAxis = BABYLON.Vector3.Forward();
  61303. this.mesh = mesh;
  61304. this.bone = bone;
  61305. this.target = target;
  61306. if (options) {
  61307. if (options.adjustYaw) {
  61308. this.adjustYaw = options.adjustYaw;
  61309. }
  61310. if (options.adjustPitch) {
  61311. this.adjustPitch = options.adjustPitch;
  61312. }
  61313. if (options.adjustRoll) {
  61314. this.adjustRoll = options.adjustRoll;
  61315. }
  61316. if (options.maxYaw != null) {
  61317. this.maxYaw = options.maxYaw;
  61318. }
  61319. else {
  61320. this.maxYaw = Math.PI;
  61321. }
  61322. if (options.minYaw != null) {
  61323. this.minYaw = options.minYaw;
  61324. }
  61325. else {
  61326. this.minYaw = -Math.PI;
  61327. }
  61328. if (options.maxPitch != null) {
  61329. this.maxPitch = options.maxPitch;
  61330. }
  61331. else {
  61332. this.maxPitch = Math.PI;
  61333. }
  61334. if (options.minPitch != null) {
  61335. this.minPitch = options.minPitch;
  61336. }
  61337. else {
  61338. this.minPitch = -Math.PI;
  61339. }
  61340. if (options.slerpAmount != null) {
  61341. this.slerpAmount = options.slerpAmount;
  61342. }
  61343. if (options.upAxis != null) {
  61344. this.upAxis = options.upAxis;
  61345. }
  61346. if (options.upAxisSpace != null) {
  61347. this.upAxisSpace = options.upAxisSpace;
  61348. }
  61349. if (options.yawAxis != null || options.pitchAxis != null) {
  61350. var newYawAxis = BABYLON.Axis.Y;
  61351. var newPitchAxis = BABYLON.Axis.X;
  61352. if (options.yawAxis != null) {
  61353. newYawAxis = options.yawAxis.clone();
  61354. newYawAxis.normalize();
  61355. }
  61356. if (options.pitchAxis != null) {
  61357. newPitchAxis = options.pitchAxis.clone();
  61358. newPitchAxis.normalize();
  61359. }
  61360. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  61361. this._transformYawPitch = BABYLON.Matrix.Identity();
  61362. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  61363. this._transformYawPitchInv = this._transformYawPitch.clone();
  61364. this._transformYawPitch.invert();
  61365. }
  61366. }
  61367. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  61368. this.upAxisSpace = BABYLON.Space.LOCAL;
  61369. }
  61370. }
  61371. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  61372. /**
  61373. * Get/set the minimum yaw angle that the bone can look to.
  61374. */
  61375. get: function () {
  61376. return this._minYaw;
  61377. },
  61378. set: function (value) {
  61379. this._minYaw = value;
  61380. this._minYawSin = Math.sin(value);
  61381. this._minYawCos = Math.cos(value);
  61382. if (this._maxYaw != null) {
  61383. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61384. this._yawRange = this._maxYaw - this._minYaw;
  61385. }
  61386. },
  61387. enumerable: true,
  61388. configurable: true
  61389. });
  61390. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  61391. /**
  61392. * Get/set the maximum yaw angle that the bone can look to.
  61393. */
  61394. get: function () {
  61395. return this._maxYaw;
  61396. },
  61397. set: function (value) {
  61398. this._maxYaw = value;
  61399. this._maxYawSin = Math.sin(value);
  61400. this._maxYawCos = Math.cos(value);
  61401. if (this._minYaw != null) {
  61402. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61403. this._yawRange = this._maxYaw - this._minYaw;
  61404. }
  61405. },
  61406. enumerable: true,
  61407. configurable: true
  61408. });
  61409. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  61410. /**
  61411. * Get/set the minimum pitch angle that the bone can look to.
  61412. */
  61413. get: function () {
  61414. return this._minPitch;
  61415. },
  61416. set: function (value) {
  61417. this._minPitch = value;
  61418. this._minPitchTan = Math.tan(value);
  61419. },
  61420. enumerable: true,
  61421. configurable: true
  61422. });
  61423. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  61424. /**
  61425. * Get/set the maximum pitch angle that the bone can look to.
  61426. */
  61427. get: function () {
  61428. return this._maxPitch;
  61429. },
  61430. set: function (value) {
  61431. this._maxPitch = value;
  61432. this._maxPitchTan = Math.tan(value);
  61433. },
  61434. enumerable: true,
  61435. configurable: true
  61436. });
  61437. /**
  61438. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  61439. */
  61440. BoneLookController.prototype.update = function () {
  61441. //skip the first frame when slerping so that the mesh rotation is correct
  61442. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  61443. this._firstFrameSkipped = true;
  61444. return;
  61445. }
  61446. var bone = this.bone;
  61447. var bonePos = BoneLookController._tmpVecs[0];
  61448. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  61449. var target = this.target;
  61450. var _tmpMat1 = BoneLookController._tmpMats[0];
  61451. var _tmpMat2 = BoneLookController._tmpMats[1];
  61452. var mesh = this.mesh;
  61453. var parentBone = bone.getParent();
  61454. var upAxis = BoneLookController._tmpVecs[1];
  61455. upAxis.copyFrom(this.upAxis);
  61456. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  61457. if (this._transformYawPitch) {
  61458. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  61459. }
  61460. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  61461. }
  61462. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  61463. mesh.getDirectionToRef(upAxis, upAxis);
  61464. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  61465. upAxis.normalize();
  61466. }
  61467. }
  61468. var checkYaw = false;
  61469. var checkPitch = false;
  61470. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  61471. checkYaw = true;
  61472. }
  61473. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  61474. checkPitch = true;
  61475. }
  61476. if (checkYaw || checkPitch) {
  61477. var spaceMat = BoneLookController._tmpMats[2];
  61478. var spaceMatInv = BoneLookController._tmpMats[3];
  61479. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  61480. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  61481. }
  61482. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  61483. spaceMat.copyFrom(mesh.getWorldMatrix());
  61484. }
  61485. else {
  61486. var forwardAxis = BoneLookController._tmpVecs[2];
  61487. forwardAxis.copyFrom(this._fowardAxis);
  61488. if (this._transformYawPitch) {
  61489. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  61490. }
  61491. if (parentBone) {
  61492. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  61493. }
  61494. else {
  61495. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  61496. }
  61497. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  61498. rightAxis.normalize();
  61499. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  61500. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  61501. }
  61502. spaceMat.invertToRef(spaceMatInv);
  61503. var xzlen = null;
  61504. if (checkPitch) {
  61505. var localTarget = BoneLookController._tmpVecs[3];
  61506. target.subtractToRef(bonePos, localTarget);
  61507. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61508. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61509. var pitch = Math.atan2(localTarget.y, xzlen);
  61510. var newPitch = pitch;
  61511. if (pitch > this._maxPitch) {
  61512. localTarget.y = this._maxPitchTan * xzlen;
  61513. newPitch = this._maxPitch;
  61514. }
  61515. else if (pitch < this._minPitch) {
  61516. localTarget.y = this._minPitchTan * xzlen;
  61517. newPitch = this._minPitch;
  61518. }
  61519. if (pitch != newPitch) {
  61520. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61521. localTarget.addInPlace(bonePos);
  61522. target = localTarget;
  61523. }
  61524. }
  61525. if (checkYaw) {
  61526. var localTarget = BoneLookController._tmpVecs[4];
  61527. target.subtractToRef(bonePos, localTarget);
  61528. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61529. var yaw = Math.atan2(localTarget.x, localTarget.z);
  61530. var newYaw = yaw;
  61531. if (yaw > this._maxYaw || yaw < this._minYaw) {
  61532. if (xzlen == null) {
  61533. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61534. }
  61535. if (this._yawRange > Math.PI) {
  61536. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  61537. localTarget.z = this._maxYawCos * xzlen;
  61538. localTarget.x = this._maxYawSin * xzlen;
  61539. newYaw = this._maxYaw;
  61540. }
  61541. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  61542. localTarget.z = this._minYawCos * xzlen;
  61543. localTarget.x = this._minYawSin * xzlen;
  61544. newYaw = this._minYaw;
  61545. }
  61546. }
  61547. else {
  61548. if (yaw > this._maxYaw) {
  61549. localTarget.z = this._maxYawCos * xzlen;
  61550. localTarget.x = this._maxYawSin * xzlen;
  61551. newYaw = this._maxYaw;
  61552. }
  61553. else if (yaw < this._minYaw) {
  61554. localTarget.z = this._minYawCos * xzlen;
  61555. localTarget.x = this._minYawSin * xzlen;
  61556. newYaw = this._minYaw;
  61557. }
  61558. }
  61559. }
  61560. if (this._slerping && this._yawRange > Math.PI) {
  61561. //are we going to be crossing into the min/max region?
  61562. var boneFwd = BoneLookController._tmpVecs[8];
  61563. boneFwd.copyFrom(BABYLON.Axis.Z);
  61564. if (this._transformYawPitch) {
  61565. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  61566. }
  61567. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  61568. this._boneQuat.toRotationMatrix(boneRotMat);
  61569. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  61570. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  61571. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  61572. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  61573. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  61574. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  61575. if (angBtwTar > angBtwMidYaw) {
  61576. if (xzlen == null) {
  61577. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61578. }
  61579. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  61580. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  61581. if (angBtwMin < angBtwMax) {
  61582. newYaw = boneYaw + Math.PI * .75;
  61583. localTarget.z = Math.cos(newYaw) * xzlen;
  61584. localTarget.x = Math.sin(newYaw) * xzlen;
  61585. }
  61586. else {
  61587. newYaw = boneYaw - Math.PI * .75;
  61588. localTarget.z = Math.cos(newYaw) * xzlen;
  61589. localTarget.x = Math.sin(newYaw) * xzlen;
  61590. }
  61591. }
  61592. }
  61593. if (yaw != newYaw) {
  61594. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61595. localTarget.addInPlace(bonePos);
  61596. target = localTarget;
  61597. }
  61598. }
  61599. }
  61600. var zaxis = BoneLookController._tmpVecs[5];
  61601. var xaxis = BoneLookController._tmpVecs[6];
  61602. var yaxis = BoneLookController._tmpVecs[7];
  61603. var _tmpQuat = BoneLookController._tmpQuat;
  61604. target.subtractToRef(bonePos, zaxis);
  61605. zaxis.normalize();
  61606. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  61607. xaxis.normalize();
  61608. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  61609. yaxis.normalize();
  61610. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  61611. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  61612. return;
  61613. }
  61614. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  61615. return;
  61616. }
  61617. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  61618. return;
  61619. }
  61620. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  61621. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  61622. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  61623. }
  61624. if (this.slerpAmount < 1) {
  61625. if (!this._slerping) {
  61626. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  61627. }
  61628. if (this._transformYawPitch) {
  61629. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61630. }
  61631. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  61632. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  61633. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  61634. this._slerping = true;
  61635. }
  61636. else {
  61637. if (this._transformYawPitch) {
  61638. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61639. }
  61640. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  61641. this._slerping = false;
  61642. }
  61643. };
  61644. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  61645. var angDiff = ang2 - ang1;
  61646. angDiff %= Math.PI * 2;
  61647. if (angDiff > Math.PI) {
  61648. angDiff -= Math.PI * 2;
  61649. }
  61650. else if (angDiff < -Math.PI) {
  61651. angDiff += Math.PI * 2;
  61652. }
  61653. return angDiff;
  61654. };
  61655. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  61656. ang1 %= (2 * Math.PI);
  61657. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61658. ang2 %= (2 * Math.PI);
  61659. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61660. var ab = 0;
  61661. if (ang1 < ang2) {
  61662. ab = ang2 - ang1;
  61663. }
  61664. else {
  61665. ab = ang1 - ang2;
  61666. }
  61667. if (ab > Math.PI) {
  61668. ab = Math.PI * 2 - ab;
  61669. }
  61670. return ab;
  61671. };
  61672. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  61673. ang %= (2 * Math.PI);
  61674. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  61675. ang1 %= (2 * Math.PI);
  61676. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61677. ang2 %= (2 * Math.PI);
  61678. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61679. if (ang1 < ang2) {
  61680. if (ang > ang1 && ang < ang2) {
  61681. return true;
  61682. }
  61683. }
  61684. else {
  61685. if (ang > ang2 && ang < ang1) {
  61686. return true;
  61687. }
  61688. }
  61689. return false;
  61690. };
  61691. 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()];
  61692. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  61693. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61694. return BoneLookController;
  61695. }());
  61696. BABYLON.BoneLookController = BoneLookController;
  61697. })(BABYLON || (BABYLON = {}));
  61698. //# sourceMappingURL=babylon.boneLookController.js.map
  61699. var BABYLON;
  61700. (function (BABYLON) {
  61701. var Skeleton = /** @class */ (function () {
  61702. function Skeleton(name, id, scene) {
  61703. this.name = name;
  61704. this.id = id;
  61705. this.bones = new Array();
  61706. this.needInitialSkinMatrix = false;
  61707. this._isDirty = true;
  61708. this._meshesWithPoseMatrix = new Array();
  61709. this._identity = BABYLON.Matrix.Identity();
  61710. this._ranges = {};
  61711. this._lastAbsoluteTransformsUpdateId = -1;
  61712. // Events
  61713. /**
  61714. * An event triggered before computing the skeleton's matrices
  61715. * @type {BABYLON.Observable}
  61716. */
  61717. this.onBeforeComputeObservable = new BABYLON.Observable();
  61718. this.bones = [];
  61719. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61720. scene.skeletons.push(this);
  61721. //make sure it will recalculate the matrix next time prepare is called.
  61722. this._isDirty = true;
  61723. }
  61724. // Members
  61725. Skeleton.prototype.getTransformMatrices = function (mesh) {
  61726. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  61727. return mesh._bonesTransformMatrices;
  61728. }
  61729. if (!this._transformMatrices) {
  61730. this.prepare();
  61731. }
  61732. return this._transformMatrices;
  61733. };
  61734. Skeleton.prototype.getScene = function () {
  61735. return this._scene;
  61736. };
  61737. // Methods
  61738. /**
  61739. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  61740. */
  61741. Skeleton.prototype.toString = function (fullDetails) {
  61742. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  61743. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  61744. if (fullDetails) {
  61745. ret += ", Ranges: {";
  61746. var first = true;
  61747. for (var name_1 in this._ranges) {
  61748. if (first) {
  61749. ret += ", ";
  61750. first = false;
  61751. }
  61752. ret += name_1;
  61753. }
  61754. ret += "}";
  61755. }
  61756. return ret;
  61757. };
  61758. /**
  61759. * Get bone's index searching by name
  61760. * @param {string} name is bone's name to search for
  61761. * @return {number} Indice of the bone. Returns -1 if not found
  61762. */
  61763. Skeleton.prototype.getBoneIndexByName = function (name) {
  61764. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  61765. if (this.bones[boneIndex].name === name) {
  61766. return boneIndex;
  61767. }
  61768. }
  61769. return -1;
  61770. };
  61771. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  61772. // check name not already in use
  61773. if (!this._ranges[name]) {
  61774. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  61775. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61776. if (this.bones[i].animations[0]) {
  61777. this.bones[i].animations[0].createRange(name, from, to);
  61778. }
  61779. }
  61780. }
  61781. };
  61782. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  61783. if (deleteFrames === void 0) { deleteFrames = true; }
  61784. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61785. if (this.bones[i].animations[0]) {
  61786. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  61787. }
  61788. }
  61789. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  61790. };
  61791. Skeleton.prototype.getAnimationRange = function (name) {
  61792. return this._ranges[name];
  61793. };
  61794. /**
  61795. * Returns as an Array, all AnimationRanges defined on this skeleton
  61796. */
  61797. Skeleton.prototype.getAnimationRanges = function () {
  61798. var animationRanges = [];
  61799. var name;
  61800. var i = 0;
  61801. for (name in this._ranges) {
  61802. animationRanges[i] = this._ranges[name];
  61803. i++;
  61804. }
  61805. return animationRanges;
  61806. };
  61807. /**
  61808. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  61809. */
  61810. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  61811. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61812. if (this._ranges[name] || !source.getAnimationRange(name)) {
  61813. return false;
  61814. }
  61815. var ret = true;
  61816. var frameOffset = this._getHighestAnimationFrame() + 1;
  61817. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  61818. var boneDict = {};
  61819. var sourceBones = source.bones;
  61820. var nBones;
  61821. var i;
  61822. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  61823. boneDict[sourceBones[i].name] = sourceBones[i];
  61824. }
  61825. if (this.bones.length !== sourceBones.length) {
  61826. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  61827. ret = false;
  61828. }
  61829. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  61830. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  61831. var boneName = this.bones[i].name;
  61832. var sourceBone = boneDict[boneName];
  61833. if (sourceBone) {
  61834. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  61835. }
  61836. else {
  61837. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  61838. ret = false;
  61839. }
  61840. }
  61841. // do not call createAnimationRange(), since it also is done to bones, which was already done
  61842. var range = source.getAnimationRange(name);
  61843. if (range) {
  61844. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  61845. }
  61846. return ret;
  61847. };
  61848. Skeleton.prototype.returnToRest = function () {
  61849. for (var index = 0; index < this.bones.length; index++) {
  61850. this.bones[index].returnToRest();
  61851. }
  61852. };
  61853. Skeleton.prototype._getHighestAnimationFrame = function () {
  61854. var ret = 0;
  61855. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61856. if (this.bones[i].animations[0]) {
  61857. var highest = this.bones[i].animations[0].getHighestFrame();
  61858. if (ret < highest) {
  61859. ret = highest;
  61860. }
  61861. }
  61862. }
  61863. return ret;
  61864. };
  61865. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  61866. var range = this.getAnimationRange(name);
  61867. if (!range) {
  61868. return null;
  61869. }
  61870. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  61871. };
  61872. Skeleton.prototype._markAsDirty = function () {
  61873. this._isDirty = true;
  61874. };
  61875. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  61876. this._meshesWithPoseMatrix.push(mesh);
  61877. };
  61878. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  61879. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  61880. if (index > -1) {
  61881. this._meshesWithPoseMatrix.splice(index, 1);
  61882. }
  61883. };
  61884. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  61885. this.onBeforeComputeObservable.notifyObservers(this);
  61886. for (var index = 0; index < this.bones.length; index++) {
  61887. var bone = this.bones[index];
  61888. var parentBone = bone.getParent();
  61889. if (parentBone) {
  61890. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  61891. }
  61892. else {
  61893. if (initialSkinMatrix) {
  61894. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  61895. }
  61896. else {
  61897. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  61898. }
  61899. }
  61900. if (bone._index !== -1) {
  61901. var mappedIndex = bone._index === null ? index : bone._index;
  61902. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  61903. }
  61904. }
  61905. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  61906. };
  61907. Skeleton.prototype.prepare = function () {
  61908. if (!this._isDirty) {
  61909. return;
  61910. }
  61911. if (this.needInitialSkinMatrix) {
  61912. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  61913. var mesh = this._meshesWithPoseMatrix[index];
  61914. var poseMatrix = mesh.getPoseMatrix();
  61915. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  61916. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  61917. }
  61918. if (this._synchronizedWithMesh !== mesh) {
  61919. this._synchronizedWithMesh = mesh;
  61920. // Prepare bones
  61921. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  61922. var bone = this.bones[boneIndex];
  61923. if (!bone.getParent()) {
  61924. var matrix = bone.getBaseMatrix();
  61925. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  61926. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  61927. }
  61928. }
  61929. }
  61930. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  61931. }
  61932. }
  61933. else {
  61934. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  61935. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  61936. }
  61937. this._computeTransformMatrices(this._transformMatrices, null);
  61938. }
  61939. this._isDirty = false;
  61940. this._scene._activeBones.addCount(this.bones.length, false);
  61941. };
  61942. Skeleton.prototype.getAnimatables = function () {
  61943. if (!this._animatables || this._animatables.length !== this.bones.length) {
  61944. this._animatables = [];
  61945. for (var index = 0; index < this.bones.length; index++) {
  61946. this._animatables.push(this.bones[index]);
  61947. }
  61948. }
  61949. return this._animatables;
  61950. };
  61951. Skeleton.prototype.clone = function (name, id) {
  61952. var result = new Skeleton(name, id || name, this._scene);
  61953. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  61954. for (var index = 0; index < this.bones.length; index++) {
  61955. var source = this.bones[index];
  61956. var parentBone = null;
  61957. var parent_1 = source.getParent();
  61958. if (parent_1) {
  61959. var parentIndex = this.bones.indexOf(parent_1);
  61960. parentBone = result.bones[parentIndex];
  61961. }
  61962. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  61963. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  61964. }
  61965. if (this._ranges) {
  61966. result._ranges = {};
  61967. for (var rangeName in this._ranges) {
  61968. var range = this._ranges[rangeName];
  61969. if (range) {
  61970. result._ranges[rangeName] = range.clone();
  61971. }
  61972. }
  61973. }
  61974. this._isDirty = true;
  61975. return result;
  61976. };
  61977. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  61978. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  61979. this.bones.forEach(function (bone) {
  61980. bone.animations.forEach(function (animation) {
  61981. animation.enableBlending = true;
  61982. animation.blendingSpeed = blendingSpeed;
  61983. });
  61984. });
  61985. };
  61986. Skeleton.prototype.dispose = function () {
  61987. this._meshesWithPoseMatrix = [];
  61988. // Animations
  61989. this.getScene().stopAnimation(this);
  61990. // Remove from scene
  61991. this.getScene().removeSkeleton(this);
  61992. };
  61993. Skeleton.prototype.serialize = function () {
  61994. var serializationObject = {};
  61995. serializationObject.name = this.name;
  61996. serializationObject.id = this.id;
  61997. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  61998. serializationObject.bones = [];
  61999. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62000. for (var index = 0; index < this.bones.length; index++) {
  62001. var bone = this.bones[index];
  62002. var parent_2 = bone.getParent();
  62003. var serializedBone = {
  62004. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62005. name: bone.name,
  62006. matrix: bone.getBaseMatrix().toArray(),
  62007. rest: bone.getRestPose().toArray()
  62008. };
  62009. serializationObject.bones.push(serializedBone);
  62010. if (bone.length) {
  62011. serializedBone.length = bone.length;
  62012. }
  62013. if (bone.animations && bone.animations.length > 0) {
  62014. serializedBone.animation = bone.animations[0].serialize();
  62015. }
  62016. serializationObject.ranges = [];
  62017. for (var name in this._ranges) {
  62018. var source = this._ranges[name];
  62019. if (!source) {
  62020. continue;
  62021. }
  62022. var range = {};
  62023. range.name = name;
  62024. range.from = source.from;
  62025. range.to = source.to;
  62026. serializationObject.ranges.push(range);
  62027. }
  62028. }
  62029. return serializationObject;
  62030. };
  62031. Skeleton.Parse = function (parsedSkeleton, scene) {
  62032. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62033. if (parsedSkeleton.dimensionsAtRest) {
  62034. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62035. }
  62036. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62037. var index;
  62038. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62039. var parsedBone = parsedSkeleton.bones[index];
  62040. var parentBone = null;
  62041. if (parsedBone.parentBoneIndex > -1) {
  62042. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62043. }
  62044. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62045. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62046. if (parsedBone.length) {
  62047. bone.length = parsedBone.length;
  62048. }
  62049. if (parsedBone.animation) {
  62050. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62051. }
  62052. }
  62053. // placed after bones, so createAnimationRange can cascade down
  62054. if (parsedSkeleton.ranges) {
  62055. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62056. var data = parsedSkeleton.ranges[index];
  62057. skeleton.createAnimationRange(data.name, data.from, data.to);
  62058. }
  62059. }
  62060. return skeleton;
  62061. };
  62062. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62063. if (forceUpdate === void 0) { forceUpdate = false; }
  62064. var renderId = this._scene.getRenderId();
  62065. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62066. this.bones[0].computeAbsoluteTransforms();
  62067. this._lastAbsoluteTransformsUpdateId = renderId;
  62068. }
  62069. };
  62070. Skeleton.prototype.getPoseMatrix = function () {
  62071. var poseMatrix = null;
  62072. if (this._meshesWithPoseMatrix.length > 0) {
  62073. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62074. }
  62075. return poseMatrix;
  62076. };
  62077. Skeleton.prototype.sortBones = function () {
  62078. var bones = new Array();
  62079. var visited = new Array(this.bones.length);
  62080. for (var index = 0; index < this.bones.length; index++) {
  62081. this._sortBones(index, bones, visited);
  62082. }
  62083. this.bones = bones;
  62084. };
  62085. Skeleton.prototype._sortBones = function (index, bones, visited) {
  62086. if (visited[index]) {
  62087. return;
  62088. }
  62089. visited[index] = true;
  62090. var bone = this.bones[index];
  62091. if (bone._index === undefined) {
  62092. bone._index = index;
  62093. }
  62094. var parentBone = bone.getParent();
  62095. if (parentBone) {
  62096. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  62097. }
  62098. bones.push(bone);
  62099. };
  62100. return Skeleton;
  62101. }());
  62102. BABYLON.Skeleton = Skeleton;
  62103. })(BABYLON || (BABYLON = {}));
  62104. //# sourceMappingURL=babylon.skeleton.js.map
  62105. var BABYLON;
  62106. (function (BABYLON) {
  62107. var SphericalPolynomial = /** @class */ (function () {
  62108. function SphericalPolynomial() {
  62109. this.x = BABYLON.Vector3.Zero();
  62110. this.y = BABYLON.Vector3.Zero();
  62111. this.z = BABYLON.Vector3.Zero();
  62112. this.xx = BABYLON.Vector3.Zero();
  62113. this.yy = BABYLON.Vector3.Zero();
  62114. this.zz = BABYLON.Vector3.Zero();
  62115. this.xy = BABYLON.Vector3.Zero();
  62116. this.yz = BABYLON.Vector3.Zero();
  62117. this.zx = BABYLON.Vector3.Zero();
  62118. }
  62119. SphericalPolynomial.prototype.addAmbient = function (color) {
  62120. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62121. this.xx = this.xx.add(colorVector);
  62122. this.yy = this.yy.add(colorVector);
  62123. this.zz = this.zz.add(colorVector);
  62124. };
  62125. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  62126. var result = new SphericalPolynomial();
  62127. result.x = harmonics.L11.scale(1.02333);
  62128. result.y = harmonics.L1_1.scale(1.02333);
  62129. result.z = harmonics.L10.scale(1.02333);
  62130. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  62131. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  62132. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  62133. result.yz = harmonics.L2_1.scale(0.858086);
  62134. result.zx = harmonics.L21.scale(0.858086);
  62135. result.xy = harmonics.L2_2.scale(0.858086);
  62136. result.scale(1.0 / Math.PI);
  62137. return result;
  62138. };
  62139. SphericalPolynomial.prototype.scale = function (scale) {
  62140. this.x = this.x.scale(scale);
  62141. this.y = this.y.scale(scale);
  62142. this.z = this.z.scale(scale);
  62143. this.xx = this.xx.scale(scale);
  62144. this.yy = this.yy.scale(scale);
  62145. this.zz = this.zz.scale(scale);
  62146. this.yz = this.yz.scale(scale);
  62147. this.zx = this.zx.scale(scale);
  62148. this.xy = this.xy.scale(scale);
  62149. };
  62150. return SphericalPolynomial;
  62151. }());
  62152. BABYLON.SphericalPolynomial = SphericalPolynomial;
  62153. var SphericalHarmonics = /** @class */ (function () {
  62154. function SphericalHarmonics() {
  62155. this.L00 = BABYLON.Vector3.Zero();
  62156. this.L1_1 = BABYLON.Vector3.Zero();
  62157. this.L10 = BABYLON.Vector3.Zero();
  62158. this.L11 = BABYLON.Vector3.Zero();
  62159. this.L2_2 = BABYLON.Vector3.Zero();
  62160. this.L2_1 = BABYLON.Vector3.Zero();
  62161. this.L20 = BABYLON.Vector3.Zero();
  62162. this.L21 = BABYLON.Vector3.Zero();
  62163. this.L22 = BABYLON.Vector3.Zero();
  62164. }
  62165. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  62166. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62167. var c = colorVector.scale(deltaSolidAngle);
  62168. this.L00 = this.L00.add(c.scale(0.282095));
  62169. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  62170. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  62171. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  62172. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  62173. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  62174. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  62175. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  62176. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  62177. };
  62178. SphericalHarmonics.prototype.scale = function (scale) {
  62179. this.L00 = this.L00.scale(scale);
  62180. this.L1_1 = this.L1_1.scale(scale);
  62181. this.L10 = this.L10.scale(scale);
  62182. this.L11 = this.L11.scale(scale);
  62183. this.L2_2 = this.L2_2.scale(scale);
  62184. this.L2_1 = this.L2_1.scale(scale);
  62185. this.L20 = this.L20.scale(scale);
  62186. this.L21 = this.L21.scale(scale);
  62187. this.L22 = this.L22.scale(scale);
  62188. };
  62189. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  62190. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  62191. //
  62192. // E_lm = A_l * L_lm
  62193. //
  62194. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  62195. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  62196. // the scaling factors are given in equation 9.
  62197. // Constant (Band 0)
  62198. this.L00 = this.L00.scale(3.141593);
  62199. // Linear (Band 1)
  62200. this.L1_1 = this.L1_1.scale(2.094395);
  62201. this.L10 = this.L10.scale(2.094395);
  62202. this.L11 = this.L11.scale(2.094395);
  62203. // Quadratic (Band 2)
  62204. this.L2_2 = this.L2_2.scale(0.785398);
  62205. this.L2_1 = this.L2_1.scale(0.785398);
  62206. this.L20 = this.L20.scale(0.785398);
  62207. this.L21 = this.L21.scale(0.785398);
  62208. this.L22 = this.L22.scale(0.785398);
  62209. };
  62210. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  62211. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  62212. // L = (1/pi) * E * rho
  62213. //
  62214. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  62215. this.scale(1.0 / Math.PI);
  62216. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  62217. // (The pixel shader must apply albedo after texture fetches, etc).
  62218. };
  62219. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  62220. var result = new SphericalHarmonics();
  62221. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  62222. result.L1_1 = polynomial.y.scale(0.977204);
  62223. result.L10 = polynomial.z.scale(0.977204);
  62224. result.L11 = polynomial.x.scale(0.977204);
  62225. result.L2_2 = polynomial.xy.scale(1.16538);
  62226. result.L2_1 = polynomial.yz.scale(1.16538);
  62227. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  62228. result.L21 = polynomial.zx.scale(1.16538);
  62229. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  62230. result.scale(Math.PI);
  62231. return result;
  62232. };
  62233. return SphericalHarmonics;
  62234. }());
  62235. BABYLON.SphericalHarmonics = SphericalHarmonics;
  62236. })(BABYLON || (BABYLON = {}));
  62237. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  62238. var BABYLON;
  62239. (function (BABYLON) {
  62240. var Internals;
  62241. (function (Internals) {
  62242. var FileFaceOrientation = /** @class */ (function () {
  62243. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  62244. this.name = name;
  62245. this.worldAxisForNormal = worldAxisForNormal;
  62246. this.worldAxisForFileX = worldAxisForFileX;
  62247. this.worldAxisForFileY = worldAxisForFileY;
  62248. }
  62249. return FileFaceOrientation;
  62250. }());
  62251. ;
  62252. /**
  62253. * Helper class dealing with the extraction of spherical polynomial dataArray
  62254. * from a cube map.
  62255. */
  62256. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  62257. function CubeMapToSphericalPolynomialTools() {
  62258. }
  62259. /**
  62260. * Converts a texture to the according Spherical Polynomial data.
  62261. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62262. *
  62263. * @param texture The texture to extract the information from.
  62264. * @return The Spherical Polynomial data.
  62265. */
  62266. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  62267. if (!texture.isCube) {
  62268. // Only supports cube Textures currently.
  62269. return null;
  62270. }
  62271. var size = texture.getSize().width;
  62272. var right = texture.readPixels(0);
  62273. var left = texture.readPixels(1);
  62274. var up;
  62275. var down;
  62276. if (texture.isRenderTarget) {
  62277. up = texture.readPixels(3);
  62278. down = texture.readPixels(2);
  62279. }
  62280. else {
  62281. up = texture.readPixels(2);
  62282. down = texture.readPixels(3);
  62283. }
  62284. var front = texture.readPixels(4);
  62285. var back = texture.readPixels(5);
  62286. var gammaSpace = texture.gammaSpace;
  62287. // Always read as RGBA.
  62288. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  62289. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62290. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62291. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62292. }
  62293. var cubeInfo = {
  62294. size: size,
  62295. right: right,
  62296. left: left,
  62297. up: up,
  62298. down: down,
  62299. front: front,
  62300. back: back,
  62301. format: format,
  62302. type: type,
  62303. gammaSpace: gammaSpace,
  62304. };
  62305. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  62306. };
  62307. /**
  62308. * Converts a cubemap to the according Spherical Polynomial data.
  62309. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62310. *
  62311. * @param cubeInfo The Cube map to extract the information from.
  62312. * @return The Spherical Polynomial data.
  62313. */
  62314. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  62315. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  62316. var totalSolidAngle = 0.0;
  62317. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  62318. var du = 2.0 / cubeInfo.size;
  62319. var dv = du;
  62320. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  62321. var minUV = du * 0.5 - 1.0;
  62322. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62323. var fileFace = this.FileFaces[faceIndex];
  62324. var dataArray = cubeInfo[fileFace.name];
  62325. var v = minUV;
  62326. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  62327. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  62328. // Because SP is still linear, so summation is fine in that basis.
  62329. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  62330. for (var y = 0; y < cubeInfo.size; y++) {
  62331. var u = minUV;
  62332. for (var x = 0; x < cubeInfo.size; x++) {
  62333. // World direction (not normalised)
  62334. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  62335. worldDirection.normalize();
  62336. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  62337. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  62338. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  62339. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  62340. // Handle Integer types.
  62341. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62342. r /= 255;
  62343. g /= 255;
  62344. b /= 255;
  62345. }
  62346. // Handle Gamma space textures.
  62347. if (cubeInfo.gammaSpace) {
  62348. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  62349. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  62350. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  62351. }
  62352. var color = new BABYLON.Color3(r, g, b);
  62353. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  62354. totalSolidAngle += deltaSolidAngle;
  62355. u += du;
  62356. }
  62357. v += dv;
  62358. }
  62359. }
  62360. // Solid angle for entire sphere is 4*pi
  62361. var sphereSolidAngle = 4.0 * Math.PI;
  62362. // Adjust the solid angle to allow for how many faces we processed.
  62363. var facesProcessed = 6.0;
  62364. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  62365. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  62366. // This is needed because the numerical integration over the cube uses a
  62367. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  62368. // and also to compensate for accumulative error due to float precision in the summation.
  62369. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  62370. sphericalHarmonics.scale(correctionFactor);
  62371. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  62372. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  62373. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  62374. };
  62375. CubeMapToSphericalPolynomialTools.FileFaces = [
  62376. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  62377. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  62378. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  62379. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  62380. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  62381. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  62382. ];
  62383. return CubeMapToSphericalPolynomialTools;
  62384. }());
  62385. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  62386. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62387. })(BABYLON || (BABYLON = {}));
  62388. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  62389. var BABYLON;
  62390. (function (BABYLON) {
  62391. var Internals;
  62392. (function (Internals) {
  62393. /**
  62394. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  62395. */
  62396. var PanoramaToCubeMapTools = /** @class */ (function () {
  62397. function PanoramaToCubeMapTools() {
  62398. }
  62399. /**
  62400. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  62401. *
  62402. * @param float32Array The source data.
  62403. * @param inputWidth The width of the input panorama.
  62404. * @param inputhHeight The height of the input panorama.
  62405. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  62406. * @return The cubemap data
  62407. */
  62408. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  62409. if (!float32Array) {
  62410. throw "ConvertPanoramaToCubemap: input cannot be null";
  62411. }
  62412. if (float32Array.length != inputWidth * inputHeight * 3) {
  62413. throw "ConvertPanoramaToCubemap: input size is wrong";
  62414. }
  62415. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  62416. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  62417. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  62418. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  62419. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  62420. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  62421. return {
  62422. front: textureFront,
  62423. back: textureBack,
  62424. left: textureLeft,
  62425. right: textureRight,
  62426. up: textureUp,
  62427. down: textureDown,
  62428. size: size,
  62429. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  62430. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  62431. gammaSpace: false,
  62432. };
  62433. };
  62434. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  62435. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  62436. var textureArray = new Float32Array(buffer);
  62437. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  62438. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  62439. var dy = 1 / texSize;
  62440. var fy = 0;
  62441. for (var y = 0; y < texSize; y++) {
  62442. var xv1 = faceData[0];
  62443. var xv2 = faceData[2];
  62444. for (var x = 0; x < texSize; x++) {
  62445. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  62446. v.normalize();
  62447. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  62448. // 3 channels per pixels
  62449. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  62450. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  62451. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  62452. xv1 = xv1.add(rotDX1);
  62453. xv2 = xv2.add(rotDX2);
  62454. }
  62455. fy += dy;
  62456. }
  62457. return textureArray;
  62458. };
  62459. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  62460. var theta = Math.atan2(vDir.z, vDir.x);
  62461. var phi = Math.acos(vDir.y);
  62462. while (theta < -Math.PI)
  62463. theta += 2 * Math.PI;
  62464. while (theta > Math.PI)
  62465. theta -= 2 * Math.PI;
  62466. var dx = theta / Math.PI;
  62467. var dy = phi / Math.PI;
  62468. // recenter.
  62469. dx = dx * 0.5 + 0.5;
  62470. var px = Math.round(dx * inputWidth);
  62471. if (px < 0)
  62472. px = 0;
  62473. else if (px >= inputWidth)
  62474. px = inputWidth - 1;
  62475. var py = Math.round(dy * inputHeight);
  62476. if (py < 0)
  62477. py = 0;
  62478. else if (py >= inputHeight)
  62479. py = inputHeight - 1;
  62480. var inputY = (inputHeight - py - 1);
  62481. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  62482. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  62483. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  62484. return {
  62485. r: r,
  62486. g: g,
  62487. b: b
  62488. };
  62489. };
  62490. PanoramaToCubeMapTools.FACE_FRONT = [
  62491. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62492. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62493. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62494. new BABYLON.Vector3(1.0, 1.0, -1.0)
  62495. ];
  62496. PanoramaToCubeMapTools.FACE_BACK = [
  62497. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62498. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62499. new BABYLON.Vector3(1.0, 1.0, 1.0),
  62500. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  62501. ];
  62502. PanoramaToCubeMapTools.FACE_RIGHT = [
  62503. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62504. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62505. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62506. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62507. ];
  62508. PanoramaToCubeMapTools.FACE_LEFT = [
  62509. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62510. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62511. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62512. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  62513. ];
  62514. PanoramaToCubeMapTools.FACE_DOWN = [
  62515. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62516. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62517. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62518. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62519. ];
  62520. PanoramaToCubeMapTools.FACE_UP = [
  62521. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62522. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62523. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62524. new BABYLON.Vector3(1.0, -1.0, -1.0)
  62525. ];
  62526. return PanoramaToCubeMapTools;
  62527. }());
  62528. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  62529. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62530. })(BABYLON || (BABYLON = {}));
  62531. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  62532. var BABYLON;
  62533. (function (BABYLON) {
  62534. var Internals;
  62535. (function (Internals) {
  62536. ;
  62537. /**
  62538. * This groups tools to convert HDR texture to native colors array.
  62539. */
  62540. var HDRTools = /** @class */ (function () {
  62541. function HDRTools() {
  62542. }
  62543. HDRTools.Ldexp = function (mantissa, exponent) {
  62544. if (exponent > 1023) {
  62545. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  62546. }
  62547. if (exponent < -1074) {
  62548. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  62549. }
  62550. return mantissa * Math.pow(2, exponent);
  62551. };
  62552. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  62553. if (exponent > 0) {
  62554. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  62555. float32array[index + 0] = red * exponent;
  62556. float32array[index + 1] = green * exponent;
  62557. float32array[index + 2] = blue * exponent;
  62558. }
  62559. else {
  62560. float32array[index + 0] = 0;
  62561. float32array[index + 1] = 0;
  62562. float32array[index + 2] = 0;
  62563. }
  62564. };
  62565. HDRTools.readStringLine = function (uint8array, startIndex) {
  62566. var line = "";
  62567. var character = "";
  62568. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  62569. character = String.fromCharCode(uint8array[i]);
  62570. if (character == "\n") {
  62571. break;
  62572. }
  62573. line += character;
  62574. }
  62575. return line;
  62576. };
  62577. /**
  62578. * Reads header information from an RGBE texture stored in a native array.
  62579. * More information on this format are available here:
  62580. * https://en.wikipedia.org/wiki/RGBE_image_format
  62581. *
  62582. * @param uint8array The binary file stored in native array.
  62583. * @return The header information.
  62584. */
  62585. HDRTools.RGBE_ReadHeader = function (uint8array) {
  62586. var height = 0;
  62587. var width = 0;
  62588. var line = this.readStringLine(uint8array, 0);
  62589. if (line[0] != '#' || line[1] != '?') {
  62590. throw "Bad HDR Format.";
  62591. }
  62592. var endOfHeader = false;
  62593. var findFormat = false;
  62594. var lineIndex = 0;
  62595. do {
  62596. lineIndex += (line.length + 1);
  62597. line = this.readStringLine(uint8array, lineIndex);
  62598. if (line == "FORMAT=32-bit_rle_rgbe") {
  62599. findFormat = true;
  62600. }
  62601. else if (line.length == 0) {
  62602. endOfHeader = true;
  62603. }
  62604. } while (!endOfHeader);
  62605. if (!findFormat) {
  62606. throw "HDR Bad header format, unsupported FORMAT";
  62607. }
  62608. lineIndex += (line.length + 1);
  62609. line = this.readStringLine(uint8array, lineIndex);
  62610. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  62611. var match = sizeRegexp.exec(line);
  62612. // TODO. Support +Y and -X if needed.
  62613. if (!match || match.length < 3) {
  62614. throw "HDR Bad header format, no size";
  62615. }
  62616. width = parseInt(match[2]);
  62617. height = parseInt(match[1]);
  62618. if (width < 8 || width > 0x7fff) {
  62619. throw "HDR Bad header format, unsupported size";
  62620. }
  62621. lineIndex += (line.length + 1);
  62622. return {
  62623. height: height,
  62624. width: width,
  62625. dataPosition: lineIndex
  62626. };
  62627. };
  62628. /**
  62629. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  62630. * This RGBE texture needs to store the information as a panorama.
  62631. *
  62632. * More information on this format are available here:
  62633. * https://en.wikipedia.org/wiki/RGBE_image_format
  62634. *
  62635. * @param buffer The binary file stored in an array buffer.
  62636. * @param size The expected size of the extracted cubemap.
  62637. * @return The Cube Map information.
  62638. */
  62639. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  62640. var uint8array = new Uint8Array(buffer);
  62641. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  62642. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62643. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  62644. return cubeMapData;
  62645. };
  62646. /**
  62647. * Returns the pixels data extracted from an RGBE texture.
  62648. * This pixels will be stored left to right up to down in the R G B order in one array.
  62649. *
  62650. * More information on this format are available here:
  62651. * https://en.wikipedia.org/wiki/RGBE_image_format
  62652. *
  62653. * @param uint8array The binary file stored in an array buffer.
  62654. * @param hdrInfo The header information of the file.
  62655. * @return The pixels data in RGB right to left up to down order.
  62656. */
  62657. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  62658. // Keep for multi format supports.
  62659. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62660. };
  62661. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  62662. var num_scanlines = hdrInfo.height;
  62663. var scanline_width = hdrInfo.width;
  62664. var a, b, c, d, count;
  62665. var dataIndex = hdrInfo.dataPosition;
  62666. var index = 0, endIndex = 0, i = 0;
  62667. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  62668. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  62669. // 3 channels of 4 bytes per pixel in float.
  62670. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  62671. var resultArray = new Float32Array(resultBuffer);
  62672. // read in each successive scanline
  62673. while (num_scanlines > 0) {
  62674. a = uint8array[dataIndex++];
  62675. b = uint8array[dataIndex++];
  62676. c = uint8array[dataIndex++];
  62677. d = uint8array[dataIndex++];
  62678. if (a != 2 || b != 2 || (c & 0x80)) {
  62679. // this file is not run length encoded
  62680. throw "HDR Bad header format, not RLE";
  62681. }
  62682. if (((c << 8) | d) != scanline_width) {
  62683. throw "HDR Bad header format, wrong scan line width";
  62684. }
  62685. index = 0;
  62686. // read each of the four channels for the scanline into the buffer
  62687. for (i = 0; i < 4; i++) {
  62688. endIndex = (i + 1) * scanline_width;
  62689. while (index < endIndex) {
  62690. a = uint8array[dataIndex++];
  62691. b = uint8array[dataIndex++];
  62692. if (a > 128) {
  62693. // a run of the same value
  62694. count = a - 128;
  62695. if ((count == 0) || (count > endIndex - index)) {
  62696. throw "HDR Bad Format, bad scanline data (run)";
  62697. }
  62698. while (count-- > 0) {
  62699. scanLineArray[index++] = b;
  62700. }
  62701. }
  62702. else {
  62703. // a non-run
  62704. count = a;
  62705. if ((count == 0) || (count > endIndex - index)) {
  62706. throw "HDR Bad Format, bad scanline data (non-run)";
  62707. }
  62708. scanLineArray[index++] = b;
  62709. if (--count > 0) {
  62710. for (var j = 0; j < count; j++) {
  62711. scanLineArray[index++] = uint8array[dataIndex++];
  62712. }
  62713. }
  62714. }
  62715. }
  62716. }
  62717. // now convert data from buffer into floats
  62718. for (i = 0; i < scanline_width; i++) {
  62719. a = scanLineArray[i];
  62720. b = scanLineArray[i + scanline_width];
  62721. c = scanLineArray[i + 2 * scanline_width];
  62722. d = scanLineArray[i + 3 * scanline_width];
  62723. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  62724. }
  62725. num_scanlines--;
  62726. }
  62727. return resultArray;
  62728. };
  62729. return HDRTools;
  62730. }());
  62731. Internals.HDRTools = HDRTools;
  62732. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62733. })(BABYLON || (BABYLON = {}));
  62734. //# sourceMappingURL=babylon.hdr.js.map
  62735. var BABYLON;
  62736. (function (BABYLON) {
  62737. /**
  62738. * This represents a texture coming from an HDR input.
  62739. *
  62740. * The only supported format is currently panorama picture stored in RGBE format.
  62741. * Example of such files can be found on HDRLib: http://hdrlib.com/
  62742. */
  62743. var HDRCubeTexture = /** @class */ (function (_super) {
  62744. __extends(HDRCubeTexture, _super);
  62745. /**
  62746. * Instantiates an HDRTexture from the following parameters.
  62747. *
  62748. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  62749. * @param scene The scene the texture will be used in
  62750. * @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.
  62751. * @param noMipmap Forces to not generate the mipmap if true
  62752. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  62753. * @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)
  62754. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  62755. */
  62756. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  62757. if (noMipmap === void 0) { noMipmap = false; }
  62758. if (generateHarmonics === void 0) { generateHarmonics = true; }
  62759. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  62760. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  62761. if (onLoad === void 0) { onLoad = null; }
  62762. if (onError === void 0) { onError = null; }
  62763. var _this = _super.call(this, scene) || this;
  62764. _this._useInGammaSpace = false;
  62765. _this._generateHarmonics = true;
  62766. _this._isBABYLONPreprocessed = false;
  62767. _this._onLoad = null;
  62768. _this._onError = null;
  62769. /**
  62770. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  62771. */
  62772. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62773. /**
  62774. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  62775. * This is usefull at run time to apply the good shader.
  62776. */
  62777. _this.isPMREM = false;
  62778. _this._isBlocking = true;
  62779. if (!url) {
  62780. return _this;
  62781. }
  62782. _this.name = url;
  62783. _this.url = url;
  62784. _this.hasAlpha = false;
  62785. _this.isCube = true;
  62786. _this._textureMatrix = BABYLON.Matrix.Identity();
  62787. _this._onLoad = onLoad;
  62788. _this._onError = onError;
  62789. _this.gammaSpace = false;
  62790. var caps = scene.getEngine().getCaps();
  62791. if (size) {
  62792. _this._isBABYLONPreprocessed = false;
  62793. _this._noMipmap = noMipmap;
  62794. _this._size = size;
  62795. _this._useInGammaSpace = useInGammaSpace;
  62796. _this._usePMREMGenerator = usePMREMGenerator &&
  62797. caps.textureLOD &&
  62798. caps.textureFloat &&
  62799. !_this._useInGammaSpace;
  62800. }
  62801. else {
  62802. _this._isBABYLONPreprocessed = true;
  62803. _this._noMipmap = false;
  62804. _this._useInGammaSpace = false;
  62805. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  62806. !_this._useInGammaSpace;
  62807. }
  62808. _this.isPMREM = _this._usePMREMGenerator;
  62809. _this._texture = _this._getFromCache(url, _this._noMipmap);
  62810. if (!_this._texture) {
  62811. if (!scene.useDelayedTextureLoading) {
  62812. _this.loadTexture();
  62813. }
  62814. else {
  62815. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62816. }
  62817. }
  62818. return _this;
  62819. }
  62820. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  62821. /**
  62822. * Gets wether or not the texture is blocking during loading.
  62823. */
  62824. get: function () {
  62825. return this._isBlocking;
  62826. },
  62827. /**
  62828. * Sets wether or not the texture is blocking during loading.
  62829. */
  62830. set: function (value) {
  62831. this._isBlocking = value;
  62832. },
  62833. enumerable: true,
  62834. configurable: true
  62835. });
  62836. /**
  62837. * Occurs when the file is a preprocessed .babylon.hdr file.
  62838. */
  62839. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  62840. var _this = this;
  62841. var mipLevels = 0;
  62842. var floatArrayView = null;
  62843. var scene = this.getScene();
  62844. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  62845. var mips = new Array();
  62846. if (!floatArrayView) {
  62847. return mips;
  62848. }
  62849. var startIndex = 30;
  62850. for (var level = 0; level < mipLevels; level++) {
  62851. mips.push([]);
  62852. // Fill each pixel of the mip level.
  62853. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  62854. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62855. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  62856. mips[level].push(faceData);
  62857. startIndex += faceSize;
  62858. }
  62859. }
  62860. return mips;
  62861. } : null;
  62862. var callback = function (buffer) {
  62863. var scene = _this.getScene();
  62864. if (!scene) {
  62865. return null;
  62866. }
  62867. // Create Native Array Views
  62868. var intArrayView = new Int32Array(buffer);
  62869. floatArrayView = new Float32Array(buffer);
  62870. // Fill header.
  62871. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  62872. _this._size = intArrayView[1]; // CubeMap max mip face size.
  62873. // Update Texture Information.
  62874. if (!_this._texture) {
  62875. return null;
  62876. }
  62877. _this._texture.updateSize(_this._size, _this._size);
  62878. // Fill polynomial information.
  62879. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  62880. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  62881. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  62882. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  62883. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  62884. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  62885. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  62886. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  62887. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  62888. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  62889. _this.sphericalPolynomial = sphericalPolynomial;
  62890. // Fill pixel data.
  62891. mipLevels = intArrayView[29]; // Number of mip levels.
  62892. var startIndex = 30;
  62893. var data = [];
  62894. var faceSize = Math.pow(_this._size, 2) * 3;
  62895. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62896. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  62897. startIndex += faceSize;
  62898. }
  62899. var results = [];
  62900. var byteArray = null;
  62901. // Push each faces.
  62902. for (var k = 0; k < 6; k++) {
  62903. var dataFace = null;
  62904. // To be deprecated.
  62905. if (version === 1) {
  62906. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  62907. dataFace = data[j];
  62908. }
  62909. // If special cases.
  62910. if (!mipmapGenerator && dataFace) {
  62911. if (!scene.getEngine().getCaps().textureFloat) {
  62912. // 3 channels of 1 bytes per pixel in bytes.
  62913. var byteBuffer = new ArrayBuffer(faceSize);
  62914. byteArray = new Uint8Array(byteBuffer);
  62915. }
  62916. for (var i = 0; i < _this._size * _this._size; i++) {
  62917. // Put in gamma space if requested.
  62918. if (_this._useInGammaSpace) {
  62919. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  62920. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  62921. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  62922. }
  62923. // Convert to int texture for fallback.
  62924. if (byteArray) {
  62925. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  62926. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  62927. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  62928. // May use luminance instead if the result is not accurate.
  62929. var max = Math.max(Math.max(r, g), b);
  62930. if (max > 255) {
  62931. var scale = 255 / max;
  62932. r *= scale;
  62933. g *= scale;
  62934. b *= scale;
  62935. }
  62936. byteArray[(i * 3) + 0] = r;
  62937. byteArray[(i * 3) + 1] = g;
  62938. byteArray[(i * 3) + 2] = b;
  62939. }
  62940. }
  62941. }
  62942. // Fill the array accordingly.
  62943. if (byteArray) {
  62944. results.push(byteArray);
  62945. }
  62946. else {
  62947. results.push(dataFace);
  62948. }
  62949. }
  62950. return results;
  62951. };
  62952. if (scene) {
  62953. 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);
  62954. }
  62955. };
  62956. /**
  62957. * Occurs when the file is raw .hdr file.
  62958. */
  62959. HDRCubeTexture.prototype.loadHDRTexture = function () {
  62960. var _this = this;
  62961. var callback = function (buffer) {
  62962. var scene = _this.getScene();
  62963. if (!scene) {
  62964. return null;
  62965. }
  62966. // Extract the raw linear data.
  62967. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  62968. // Generate harmonics if needed.
  62969. if (_this._generateHarmonics) {
  62970. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  62971. _this.sphericalPolynomial = sphericalPolynomial;
  62972. }
  62973. var results = [];
  62974. var byteArray = null;
  62975. // Push each faces.
  62976. for (var j = 0; j < 6; j++) {
  62977. // Create uintarray fallback.
  62978. if (!scene.getEngine().getCaps().textureFloat) {
  62979. // 3 channels of 1 bytes per pixel in bytes.
  62980. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  62981. byteArray = new Uint8Array(byteBuffer);
  62982. }
  62983. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  62984. // If special cases.
  62985. if (_this._useInGammaSpace || byteArray) {
  62986. for (var i = 0; i < _this._size * _this._size; i++) {
  62987. // Put in gamma space if requested.
  62988. if (_this._useInGammaSpace) {
  62989. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  62990. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  62991. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  62992. }
  62993. // Convert to int texture for fallback.
  62994. if (byteArray) {
  62995. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  62996. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  62997. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  62998. // May use luminance instead if the result is not accurate.
  62999. var max = Math.max(Math.max(r, g), b);
  63000. if (max > 255) {
  63001. var scale = 255 / max;
  63002. r *= scale;
  63003. g *= scale;
  63004. b *= scale;
  63005. }
  63006. byteArray[(i * 3) + 0] = r;
  63007. byteArray[(i * 3) + 1] = g;
  63008. byteArray[(i * 3) + 2] = b;
  63009. }
  63010. }
  63011. }
  63012. if (byteArray) {
  63013. results.push(byteArray);
  63014. }
  63015. else {
  63016. results.push(dataFace);
  63017. }
  63018. }
  63019. return results;
  63020. };
  63021. var mipmapGenerator = null;
  63022. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63023. // if (!this._noMipmap &&
  63024. // this._usePMREMGenerator) {
  63025. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63026. // // Custom setup of the generator matching with the PBR shader values.
  63027. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63028. // this._size,
  63029. // this._size,
  63030. // 0,
  63031. // 3,
  63032. // this.getScene().getEngine().getCaps().textureFloat,
  63033. // 2048,
  63034. // 0.25,
  63035. // false,
  63036. // true);
  63037. // return generator.filterCubeMap();
  63038. // };
  63039. // }
  63040. var scene = this.getScene();
  63041. if (scene) {
  63042. 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);
  63043. }
  63044. };
  63045. /**
  63046. * Starts the loading process of the texture.
  63047. */
  63048. HDRCubeTexture.prototype.loadTexture = function () {
  63049. if (this._isBABYLONPreprocessed) {
  63050. this.loadBabylonTexture();
  63051. }
  63052. else {
  63053. this.loadHDRTexture();
  63054. }
  63055. };
  63056. HDRCubeTexture.prototype.clone = function () {
  63057. var scene = this.getScene();
  63058. if (!scene) {
  63059. return this;
  63060. }
  63061. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63062. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63063. // Base texture
  63064. newTexture.level = this.level;
  63065. newTexture.wrapU = this.wrapU;
  63066. newTexture.wrapV = this.wrapV;
  63067. newTexture.coordinatesIndex = this.coordinatesIndex;
  63068. newTexture.coordinatesMode = this.coordinatesMode;
  63069. return newTexture;
  63070. };
  63071. // Methods
  63072. HDRCubeTexture.prototype.delayLoad = function () {
  63073. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63074. return;
  63075. }
  63076. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63077. this._texture = this._getFromCache(this.url, this._noMipmap);
  63078. if (!this._texture) {
  63079. this.loadTexture();
  63080. }
  63081. };
  63082. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  63083. return this._textureMatrix;
  63084. };
  63085. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63086. this._textureMatrix = value;
  63087. };
  63088. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63089. var texture = null;
  63090. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63091. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  63092. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  63093. texture.name = parsedTexture.name;
  63094. texture.hasAlpha = parsedTexture.hasAlpha;
  63095. texture.level = parsedTexture.level;
  63096. texture.coordinatesMode = parsedTexture.coordinatesMode;
  63097. texture.isBlocking = parsedTexture.isBlocking;
  63098. }
  63099. return texture;
  63100. };
  63101. HDRCubeTexture.prototype.serialize = function () {
  63102. if (!this.name) {
  63103. return null;
  63104. }
  63105. var serializationObject = {};
  63106. serializationObject.name = this.name;
  63107. serializationObject.hasAlpha = this.hasAlpha;
  63108. serializationObject.isCube = true;
  63109. serializationObject.level = this.level;
  63110. serializationObject.size = this._size;
  63111. serializationObject.coordinatesMode = this.coordinatesMode;
  63112. serializationObject.useInGammaSpace = this._useInGammaSpace;
  63113. serializationObject.generateHarmonics = this._generateHarmonics;
  63114. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  63115. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  63116. serializationObject.customType = "BABYLON.HDRCubeTexture";
  63117. serializationObject.noMipmap = this._noMipmap;
  63118. serializationObject.isBlocking = this._isBlocking;
  63119. return serializationObject;
  63120. };
  63121. /**
  63122. * Saves as a file the data contained in the texture in a binary format.
  63123. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63124. * as the spherical used in the lighting.
  63125. * @param url The HDR file url.
  63126. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63127. * @param onError Method called if any error happens during download.
  63128. * @return The packed binary data.
  63129. */
  63130. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  63131. if (onError === void 0) { onError = null; }
  63132. var callback = function (buffer) {
  63133. var data = new Blob([buffer], { type: 'application/octet-stream' });
  63134. // Returns a URL you can use as a href.
  63135. var objUrl = window.URL.createObjectURL(data);
  63136. // Simulates a link to it and click to dowload.
  63137. var a = document.createElement("a");
  63138. document.body.appendChild(a);
  63139. a.style.display = "none";
  63140. a.href = objUrl;
  63141. a.download = "envmap.babylon.hdr";
  63142. a.click();
  63143. };
  63144. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  63145. };
  63146. /**
  63147. * Serializes the data contained in the texture in a binary format.
  63148. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63149. * as the spherical used in the lighting.
  63150. * @param url The HDR file url.
  63151. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63152. * @param onError Method called if any error happens during download.
  63153. * @return The packed binary data.
  63154. */
  63155. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  63156. if (onError === void 0) { onError = null; }
  63157. // Needs the url tho create the texture.
  63158. if (!url) {
  63159. return;
  63160. }
  63161. // Check Power of two size.
  63162. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  63163. return;
  63164. }
  63165. // Coming Back in 3.x.
  63166. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  63167. };
  63168. HDRCubeTexture._facesMapping = [
  63169. "right",
  63170. "left",
  63171. "up",
  63172. "down",
  63173. "front",
  63174. "back"
  63175. ];
  63176. return HDRCubeTexture;
  63177. }(BABYLON.BaseTexture));
  63178. BABYLON.HDRCubeTexture = HDRCubeTexture;
  63179. })(BABYLON || (BABYLON = {}));
  63180. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  63181. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  63182. // Huge respect for a such great lib.
  63183. // Earcut license:
  63184. // Copyright (c) 2016, Mapbox
  63185. //
  63186. // Permission to use, copy, modify, and/or distribute this software for any purpose
  63187. // with or without fee is hereby granted, provided that the above copyright notice
  63188. // and this permission notice appear in all copies.
  63189. //
  63190. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  63191. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  63192. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  63193. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  63194. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  63195. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  63196. // THIS SOFTWARE.
  63197. var Earcut;
  63198. (function (Earcut) {
  63199. /**
  63200. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  63201. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  63202. * @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).
  63203. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  63204. */
  63205. function earcut(data, holeIndices, dim) {
  63206. dim = dim || 2;
  63207. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  63208. if (!outerNode)
  63209. return triangles;
  63210. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  63211. if (hasHoles)
  63212. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  63213. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  63214. if (data.length > 80 * dim) {
  63215. minX = maxX = data[0];
  63216. minY = maxY = data[1];
  63217. for (var i = dim; i < outerLen; i += dim) {
  63218. x = data[i];
  63219. y = data[i + 1];
  63220. if (x < minX)
  63221. minX = x;
  63222. if (y < minY)
  63223. minY = y;
  63224. if (x > maxX)
  63225. maxX = x;
  63226. if (y > maxY)
  63227. maxY = y;
  63228. }
  63229. // minX, minY and size are later used to transform coords into integers for z-order calculation
  63230. size = Math.max(maxX - minX, maxY - minY);
  63231. }
  63232. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  63233. return triangles;
  63234. }
  63235. Earcut.earcut = earcut;
  63236. var Node = /** @class */ (function () {
  63237. function Node(i, x, y) {
  63238. this.i = i;
  63239. this.x = x;
  63240. this.y = y;
  63241. this.prev = null;
  63242. this.next = null;
  63243. this.z = null;
  63244. this.prevZ = null;
  63245. this.nextZ = null;
  63246. this.steiner = false;
  63247. }
  63248. return Node;
  63249. }());
  63250. // create a circular doubly linked list from polygon points in the specified winding order
  63251. function linkedList(data, start, end, dim, clockwise) {
  63252. var i, last = null;
  63253. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  63254. for (i = start; i < end; i += dim)
  63255. last = insertNode(i, data[i], data[i + 1], last);
  63256. }
  63257. else {
  63258. for (i = end - dim; i >= start; i -= dim)
  63259. last = insertNode(i, data[i], data[i + 1], last);
  63260. }
  63261. if (last && equals(last, last.next)) {
  63262. removeNode(last);
  63263. last = last.next;
  63264. }
  63265. return last;
  63266. }
  63267. // eliminate colinear or duplicate points
  63268. function filterPoints(start, end) {
  63269. if (!start)
  63270. return start;
  63271. if (!end)
  63272. end = start;
  63273. var p = start, again;
  63274. do {
  63275. again = false;
  63276. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  63277. removeNode(p);
  63278. p = end = p.prev;
  63279. if (p === p.next)
  63280. return undefined;
  63281. again = true;
  63282. }
  63283. else {
  63284. p = p.next;
  63285. }
  63286. } while (again || p !== end);
  63287. return end;
  63288. }
  63289. // main ear slicing loop which triangulates a polygon (given as a linked list)
  63290. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63291. if (!ear)
  63292. return;
  63293. // interlink polygon nodes in z-order
  63294. if (!pass && size)
  63295. indexCurve(ear, minX, minY, size);
  63296. var stop = ear, prev, next;
  63297. // iterate through ears, slicing them one by one
  63298. while (ear.prev !== ear.next) {
  63299. prev = ear.prev;
  63300. next = ear.next;
  63301. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  63302. // cut off the triangle
  63303. triangles.push(prev.i / dim);
  63304. triangles.push(ear.i / dim);
  63305. triangles.push(next.i / dim);
  63306. removeNode(ear);
  63307. // skipping the next vertice leads to less sliver triangles
  63308. ear = next.next;
  63309. stop = next.next;
  63310. continue;
  63311. }
  63312. ear = next;
  63313. // if we looped through the whole remaining polygon and can't find any more ears
  63314. if (ear === stop) {
  63315. // try filtering points and slicing again
  63316. if (!pass) {
  63317. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  63318. // if this didn't work, try curing all small self-intersections locally
  63319. }
  63320. else if (pass === 1) {
  63321. ear = cureLocalIntersections(ear, triangles, dim);
  63322. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  63323. // as a last resort, try splitting the remaining polygon into two
  63324. }
  63325. else if (pass === 2) {
  63326. splitEarcut(ear, triangles, dim, minX, minY, size);
  63327. }
  63328. break;
  63329. }
  63330. }
  63331. }
  63332. // check whether a polygon node forms a valid ear with adjacent nodes
  63333. function isEar(ear) {
  63334. var a = ear.prev, b = ear, c = ear.next;
  63335. if (area(a, b, c) >= 0)
  63336. return false; // reflex, can't be an ear
  63337. // now make sure we don't have other points inside the potential ear
  63338. var p = ear.next.next;
  63339. while (p !== ear.prev) {
  63340. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63341. area(p.prev, p, p.next) >= 0)
  63342. return false;
  63343. p = p.next;
  63344. }
  63345. return true;
  63346. }
  63347. function isEarHashed(ear, minX, minY, size) {
  63348. var a = ear.prev, b = ear, c = ear.next;
  63349. if (area(a, b, c) >= 0)
  63350. return false; // reflex, can't be an ear
  63351. // triangle bbox; min & max are calculated like this for speed
  63352. 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);
  63353. // z-order range for the current triangle bbox;
  63354. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  63355. // first look for points inside the triangle in increasing z-order
  63356. var p = ear.nextZ;
  63357. while (p && p.z <= maxZ) {
  63358. if (p !== ear.prev &&
  63359. p !== ear.next &&
  63360. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63361. area(p.prev, p, p.next) >= 0)
  63362. return false;
  63363. p = p.nextZ;
  63364. }
  63365. // then look for points in decreasing z-order
  63366. p = ear.prevZ;
  63367. while (p && p.z >= minZ) {
  63368. if (p !== ear.prev &&
  63369. p !== ear.next &&
  63370. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63371. area(p.prev, p, p.next) >= 0)
  63372. return false;
  63373. p = p.prevZ;
  63374. }
  63375. return true;
  63376. }
  63377. // go through all polygon nodes and cure small local self-intersections
  63378. function cureLocalIntersections(start, triangles, dim) {
  63379. var p = start;
  63380. do {
  63381. var a = p.prev, b = p.next.next;
  63382. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  63383. triangles.push(a.i / dim);
  63384. triangles.push(p.i / dim);
  63385. triangles.push(b.i / dim);
  63386. // remove two nodes involved
  63387. removeNode(p);
  63388. removeNode(p.next);
  63389. p = start = b;
  63390. }
  63391. p = p.next;
  63392. } while (p !== start);
  63393. return p;
  63394. }
  63395. // try splitting polygon into two and triangulate them independently
  63396. function splitEarcut(start, triangles, dim, minX, minY, size) {
  63397. // look for a valid diagonal that divides the polygon into two
  63398. var a = start;
  63399. do {
  63400. var b = a.next.next;
  63401. while (b !== a.prev) {
  63402. if (a.i !== b.i && isValidDiagonal(a, b)) {
  63403. // split the polygon in two by the diagonal
  63404. var c = splitPolygon(a, b);
  63405. // filter colinear points around the cuts
  63406. a = filterPoints(a, a.next);
  63407. c = filterPoints(c, c.next);
  63408. // run earcut on each half
  63409. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  63410. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  63411. return;
  63412. }
  63413. b = b.next;
  63414. }
  63415. a = a.next;
  63416. } while (a !== start);
  63417. }
  63418. // link every hole into the outer loop, producing a single-ring polygon without holes
  63419. function eliminateHoles(data, holeIndices, outerNode, dim) {
  63420. var queue = [], i, len, start, end, list;
  63421. for (i = 0, len = holeIndices.length; i < len; i++) {
  63422. start = holeIndices[i] * dim;
  63423. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63424. list = linkedList(data, start, end, dim, false);
  63425. if (list === list.next)
  63426. list.steiner = true;
  63427. queue.push(getLeftmost(list));
  63428. }
  63429. queue.sort(compareX);
  63430. // process holes from left to right
  63431. for (i = 0; i < queue.length; i++) {
  63432. eliminateHole(queue[i], outerNode);
  63433. outerNode = filterPoints(outerNode, outerNode.next);
  63434. }
  63435. return outerNode;
  63436. }
  63437. function compareX(a, b) {
  63438. return a.x - b.x;
  63439. }
  63440. // find a bridge between vertices that connects hole with an outer ring and and link it
  63441. function eliminateHole(hole, outerNode) {
  63442. outerNode = findHoleBridge(hole, outerNode);
  63443. if (outerNode) {
  63444. var b = splitPolygon(outerNode, hole);
  63445. filterPoints(b, b.next);
  63446. }
  63447. }
  63448. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  63449. function findHoleBridge(hole, outerNode) {
  63450. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  63451. // find a segment intersected by a ray from the hole's leftmost point to the left;
  63452. // segment's endpoint with lesser x will be potential connection point
  63453. do {
  63454. if (hy <= p.y && hy >= p.next.y) {
  63455. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  63456. if (x <= hx && x > qx) {
  63457. qx = x;
  63458. if (x === hx) {
  63459. if (hy === p.y)
  63460. return p;
  63461. if (hy === p.next.y)
  63462. return p.next;
  63463. }
  63464. m = p.x < p.next.x ? p : p.next;
  63465. }
  63466. }
  63467. p = p.next;
  63468. } while (p !== outerNode);
  63469. if (!m)
  63470. return null;
  63471. if (hx === qx)
  63472. return m.prev; // hole touches outer segment; pick lower endpoint
  63473. // look for points inside the triangle of hole point, segment intersection and endpoint;
  63474. // if there are no points found, we have a valid connection;
  63475. // otherwise choose the point of the minimum angle with the ray as connection point
  63476. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  63477. p = m.next;
  63478. while (p !== stop) {
  63479. if (hx >= p.x &&
  63480. p.x >= mx &&
  63481. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  63482. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  63483. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  63484. m = p;
  63485. tanMin = tan;
  63486. }
  63487. }
  63488. p = p.next;
  63489. }
  63490. return m;
  63491. }
  63492. // interlink polygon nodes in z-order
  63493. function indexCurve(start, minX, minY, size) {
  63494. var p = start;
  63495. do {
  63496. if (p.z === null)
  63497. p.z = zOrder(p.x, p.y, minX, minY, size);
  63498. p.prevZ = p.prev;
  63499. p.nextZ = p.next;
  63500. p = p.next;
  63501. } while (p !== start);
  63502. p.prevZ.nextZ = null;
  63503. p.prevZ = null;
  63504. sortLinked(p);
  63505. }
  63506. // Simon Tatham's linked list merge sort algorithm
  63507. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  63508. function sortLinked(list) {
  63509. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  63510. do {
  63511. p = list;
  63512. list = null;
  63513. tail = null;
  63514. numMerges = 0;
  63515. while (p) {
  63516. numMerges++;
  63517. q = p;
  63518. pSize = 0;
  63519. for (i = 0; i < inSize; i++) {
  63520. pSize++;
  63521. q = q.nextZ;
  63522. if (!q)
  63523. break;
  63524. }
  63525. qSize = inSize;
  63526. while (pSize > 0 || (qSize > 0 && q)) {
  63527. if (pSize === 0) {
  63528. e = q;
  63529. q = q.nextZ;
  63530. qSize--;
  63531. }
  63532. else if (qSize === 0 || !q) {
  63533. e = p;
  63534. p = p.nextZ;
  63535. pSize--;
  63536. }
  63537. else if (p.z <= q.z) {
  63538. e = p;
  63539. p = p.nextZ;
  63540. pSize--;
  63541. }
  63542. else {
  63543. e = q;
  63544. q = q.nextZ;
  63545. qSize--;
  63546. }
  63547. if (tail)
  63548. tail.nextZ = e;
  63549. else
  63550. list = e;
  63551. e.prevZ = tail;
  63552. tail = e;
  63553. }
  63554. p = q;
  63555. }
  63556. tail.nextZ = null;
  63557. inSize *= 2;
  63558. } while (numMerges > 1);
  63559. return list;
  63560. }
  63561. // z-order of a point given coords and size of the data bounding box
  63562. function zOrder(x, y, minX, minY, size) {
  63563. // coords are transformed into non-negative 15-bit integer range
  63564. x = 32767 * (x - minX) / size;
  63565. y = 32767 * (y - minY) / size;
  63566. x = (x | (x << 8)) & 0x00FF00FF;
  63567. x = (x | (x << 4)) & 0x0F0F0F0F;
  63568. x = (x | (x << 2)) & 0x33333333;
  63569. x = (x | (x << 1)) & 0x55555555;
  63570. y = (y | (y << 8)) & 0x00FF00FF;
  63571. y = (y | (y << 4)) & 0x0F0F0F0F;
  63572. y = (y | (y << 2)) & 0x33333333;
  63573. y = (y | (y << 1)) & 0x55555555;
  63574. return x | (y << 1);
  63575. }
  63576. // find the leftmost node of a polygon ring
  63577. function getLeftmost(start) {
  63578. var p = start, leftmost = start;
  63579. do {
  63580. if (p.x < leftmost.x)
  63581. leftmost = p;
  63582. p = p.next;
  63583. } while (p !== start);
  63584. return leftmost;
  63585. }
  63586. // check if a point lies within a convex triangle
  63587. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  63588. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  63589. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  63590. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  63591. }
  63592. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  63593. function isValidDiagonal(a, b) {
  63594. return a.next.i !== b.i &&
  63595. a.prev.i !== b.i &&
  63596. !intersectsPolygon(a, b) &&
  63597. locallyInside(a, b) &&
  63598. locallyInside(b, a) &&
  63599. middleInside(a, b);
  63600. }
  63601. // signed area of a triangle
  63602. function area(p, q, r) {
  63603. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  63604. }
  63605. // check if two points are equal
  63606. function equals(p1, p2) {
  63607. return p1.x === p2.x && p1.y === p2.y;
  63608. }
  63609. // check if two segments intersect
  63610. function intersects(p1, q1, p2, q2) {
  63611. if ((equals(p1, q1) && equals(p2, q2)) ||
  63612. (equals(p1, q2) && equals(p2, q1)))
  63613. return true;
  63614. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  63615. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  63616. }
  63617. // check if a polygon diagonal intersects any polygon segments
  63618. function intersectsPolygon(a, b) {
  63619. var p = a;
  63620. do {
  63621. if (p.i !== a.i &&
  63622. p.next.i !== a.i &&
  63623. p.i !== b.i &&
  63624. p.next.i !== b.i &&
  63625. intersects(p, p.next, a, b))
  63626. return true;
  63627. p = p.next;
  63628. } while (p !== a);
  63629. return false;
  63630. }
  63631. // check if a polygon diagonal is locally inside the polygon
  63632. function locallyInside(a, b) {
  63633. return area(a.prev, a, a.next) < 0
  63634. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  63635. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  63636. }
  63637. // check if the middle point of a polygon diagonal is inside the polygon
  63638. function middleInside(a, b) {
  63639. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  63640. do {
  63641. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  63642. inside = !inside;
  63643. p = p.next;
  63644. } while (p !== a);
  63645. return inside;
  63646. }
  63647. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  63648. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  63649. function splitPolygon(a, b) {
  63650. 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;
  63651. a.next = b;
  63652. b.prev = a;
  63653. a2.next = an;
  63654. an.prev = a2;
  63655. b2.next = a2;
  63656. a2.prev = b2;
  63657. bp.next = b2;
  63658. b2.prev = bp;
  63659. return b2;
  63660. }
  63661. // create a node and optionally link it with previous one (in a circular doubly linked list)
  63662. function insertNode(i, x, y, last) {
  63663. var p = new Node(i, x, y);
  63664. if (!last) {
  63665. p.prev = p;
  63666. p.next = p;
  63667. }
  63668. else {
  63669. p.next = last.next;
  63670. p.prev = last;
  63671. last.next.prev = p;
  63672. last.next = p;
  63673. }
  63674. return p;
  63675. }
  63676. function removeNode(p) {
  63677. p.next.prev = p.prev;
  63678. p.prev.next = p.next;
  63679. if (p.prevZ)
  63680. p.prevZ.nextZ = p.nextZ;
  63681. if (p.nextZ)
  63682. p.nextZ.prevZ = p.prevZ;
  63683. }
  63684. /**
  63685. * return a percentage difference between the polygon area and its triangulation area;
  63686. * used to verify correctness of triangulation
  63687. */
  63688. function deviation(data, holeIndices, dim, triangles) {
  63689. var hasHoles = holeIndices && holeIndices.length;
  63690. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  63691. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  63692. if (hasHoles) {
  63693. for (var i = 0, len = holeIndices.length; i < len; i++) {
  63694. var start = holeIndices[i] * dim;
  63695. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63696. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  63697. }
  63698. }
  63699. var trianglesArea = 0;
  63700. for (i = 0; i < triangles.length; i += 3) {
  63701. var a = triangles[i] * dim;
  63702. var b = triangles[i + 1] * dim;
  63703. var c = triangles[i + 2] * dim;
  63704. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  63705. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  63706. }
  63707. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  63708. }
  63709. Earcut.deviation = deviation;
  63710. ;
  63711. function signedArea(data, start, end, dim) {
  63712. var sum = 0;
  63713. for (var i = start, j = end - dim; i < end; i += dim) {
  63714. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  63715. j = i;
  63716. }
  63717. return sum;
  63718. }
  63719. /**
  63720. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  63721. */
  63722. function flatten(data) {
  63723. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  63724. for (var i = 0; i < data.length; i++) {
  63725. for (var j = 0; j < data[i].length; j++) {
  63726. for (var d = 0; d < dim; d++)
  63727. result.vertices.push(data[i][j][d]);
  63728. }
  63729. if (i > 0) {
  63730. holeIndex += data[i - 1].length;
  63731. result.holes.push(holeIndex);
  63732. }
  63733. }
  63734. return result;
  63735. }
  63736. Earcut.flatten = flatten;
  63737. ;
  63738. })(Earcut || (Earcut = {}));
  63739. //# sourceMappingURL=babylon.earcut.js.map
  63740. var BABYLON;
  63741. (function (BABYLON) {
  63742. var IndexedVector2 = /** @class */ (function (_super) {
  63743. __extends(IndexedVector2, _super);
  63744. function IndexedVector2(original, index) {
  63745. var _this = _super.call(this, original.x, original.y) || this;
  63746. _this.index = index;
  63747. return _this;
  63748. }
  63749. return IndexedVector2;
  63750. }(BABYLON.Vector2));
  63751. var PolygonPoints = /** @class */ (function () {
  63752. function PolygonPoints() {
  63753. this.elements = new Array();
  63754. }
  63755. PolygonPoints.prototype.add = function (originalPoints) {
  63756. var _this = this;
  63757. var result = new Array();
  63758. originalPoints.forEach(function (point) {
  63759. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  63760. var newPoint = new IndexedVector2(point, _this.elements.length);
  63761. result.push(newPoint);
  63762. _this.elements.push(newPoint);
  63763. }
  63764. });
  63765. return result;
  63766. };
  63767. PolygonPoints.prototype.computeBounds = function () {
  63768. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63769. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63770. this.elements.forEach(function (point) {
  63771. // x
  63772. if (point.x < lmin.x) {
  63773. lmin.x = point.x;
  63774. }
  63775. else if (point.x > lmax.x) {
  63776. lmax.x = point.x;
  63777. }
  63778. // y
  63779. if (point.y < lmin.y) {
  63780. lmin.y = point.y;
  63781. }
  63782. else if (point.y > lmax.y) {
  63783. lmax.y = point.y;
  63784. }
  63785. });
  63786. return {
  63787. min: lmin,
  63788. max: lmax,
  63789. width: lmax.x - lmin.x,
  63790. height: lmax.y - lmin.y
  63791. };
  63792. };
  63793. return PolygonPoints;
  63794. }());
  63795. var Polygon = /** @class */ (function () {
  63796. function Polygon() {
  63797. }
  63798. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  63799. return [
  63800. new BABYLON.Vector2(xmin, ymin),
  63801. new BABYLON.Vector2(xmax, ymin),
  63802. new BABYLON.Vector2(xmax, ymax),
  63803. new BABYLON.Vector2(xmin, ymax)
  63804. ];
  63805. };
  63806. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  63807. if (cx === void 0) { cx = 0; }
  63808. if (cy === void 0) { cy = 0; }
  63809. if (numberOfSides === void 0) { numberOfSides = 32; }
  63810. var result = new Array();
  63811. var angle = 0;
  63812. var increment = (Math.PI * 2) / numberOfSides;
  63813. for (var i = 0; i < numberOfSides; i++) {
  63814. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  63815. angle -= increment;
  63816. }
  63817. return result;
  63818. };
  63819. Polygon.Parse = function (input) {
  63820. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  63821. var i, result = [];
  63822. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  63823. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  63824. }
  63825. return result;
  63826. };
  63827. Polygon.StartingAt = function (x, y) {
  63828. return BABYLON.Path2.StartingAt(x, y);
  63829. };
  63830. return Polygon;
  63831. }());
  63832. BABYLON.Polygon = Polygon;
  63833. var PolygonMeshBuilder = /** @class */ (function () {
  63834. function PolygonMeshBuilder(name, contours, scene) {
  63835. this._points = new PolygonPoints();
  63836. this._outlinepoints = new PolygonPoints();
  63837. this._holes = new Array();
  63838. this._epoints = new Array();
  63839. this._eholes = new Array();
  63840. this._name = name;
  63841. this._scene = scene;
  63842. var points;
  63843. if (contours instanceof BABYLON.Path2) {
  63844. points = contours.getPoints();
  63845. }
  63846. else {
  63847. points = contours;
  63848. }
  63849. this._addToepoint(points);
  63850. this._points.add(points);
  63851. this._outlinepoints.add(points);
  63852. }
  63853. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  63854. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  63855. var p = points_1[_i];
  63856. this._epoints.push(p.x, p.y);
  63857. }
  63858. };
  63859. PolygonMeshBuilder.prototype.addHole = function (hole) {
  63860. this._points.add(hole);
  63861. var holepoints = new PolygonPoints();
  63862. holepoints.add(hole);
  63863. this._holes.push(holepoints);
  63864. this._eholes.push(this._epoints.length / 2);
  63865. this._addToepoint(hole);
  63866. return this;
  63867. };
  63868. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  63869. var _this = this;
  63870. if (updatable === void 0) { updatable = false; }
  63871. if (depth === void 0) { depth = 0; }
  63872. var result = new BABYLON.Mesh(this._name, this._scene);
  63873. var normals = new Array();
  63874. var positions = new Array();
  63875. var uvs = new Array();
  63876. var bounds = this._points.computeBounds();
  63877. this._points.elements.forEach(function (p) {
  63878. normals.push(0, 1.0, 0);
  63879. positions.push(p.x, 0, p.y);
  63880. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  63881. });
  63882. var indices = new Array();
  63883. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  63884. for (var i = 0; i < res.length; i++) {
  63885. indices.push(res[i]);
  63886. }
  63887. if (depth > 0) {
  63888. var positionscount = (positions.length / 3); //get the current pointcount
  63889. this._points.elements.forEach(function (p) {
  63890. normals.push(0, -1.0, 0);
  63891. positions.push(p.x, -depth, p.y);
  63892. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  63893. });
  63894. var totalCount = indices.length;
  63895. for (var i = 0; i < totalCount; i += 3) {
  63896. var i0 = indices[i + 0];
  63897. var i1 = indices[i + 1];
  63898. var i2 = indices[i + 2];
  63899. indices.push(i2 + positionscount);
  63900. indices.push(i1 + positionscount);
  63901. indices.push(i0 + positionscount);
  63902. }
  63903. //Add the sides
  63904. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  63905. this._holes.forEach(function (hole) {
  63906. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  63907. });
  63908. }
  63909. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  63910. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  63911. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  63912. result.setIndices(indices);
  63913. return result;
  63914. };
  63915. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  63916. var StartIndex = positions.length / 3;
  63917. var ulength = 0;
  63918. for (var i = 0; i < points.elements.length; i++) {
  63919. var p = points.elements[i];
  63920. var p1;
  63921. if ((i + 1) > points.elements.length - 1) {
  63922. p1 = points.elements[0];
  63923. }
  63924. else {
  63925. p1 = points.elements[i + 1];
  63926. }
  63927. positions.push(p.x, 0, p.y);
  63928. positions.push(p.x, -depth, p.y);
  63929. positions.push(p1.x, 0, p1.y);
  63930. positions.push(p1.x, -depth, p1.y);
  63931. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  63932. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  63933. var v3 = v2.subtract(v1);
  63934. var v4 = new BABYLON.Vector3(0, 1, 0);
  63935. var vn = BABYLON.Vector3.Cross(v3, v4);
  63936. vn = vn.normalize();
  63937. uvs.push(ulength / bounds.width, 0);
  63938. uvs.push(ulength / bounds.width, 1);
  63939. ulength += v3.length();
  63940. uvs.push((ulength / bounds.width), 0);
  63941. uvs.push((ulength / bounds.width), 1);
  63942. if (!flip) {
  63943. normals.push(-vn.x, -vn.y, -vn.z);
  63944. normals.push(-vn.x, -vn.y, -vn.z);
  63945. normals.push(-vn.x, -vn.y, -vn.z);
  63946. normals.push(-vn.x, -vn.y, -vn.z);
  63947. indices.push(StartIndex);
  63948. indices.push(StartIndex + 1);
  63949. indices.push(StartIndex + 2);
  63950. indices.push(StartIndex + 1);
  63951. indices.push(StartIndex + 3);
  63952. indices.push(StartIndex + 2);
  63953. }
  63954. else {
  63955. normals.push(vn.x, vn.y, vn.z);
  63956. normals.push(vn.x, vn.y, vn.z);
  63957. normals.push(vn.x, vn.y, vn.z);
  63958. normals.push(vn.x, vn.y, vn.z);
  63959. indices.push(StartIndex);
  63960. indices.push(StartIndex + 2);
  63961. indices.push(StartIndex + 1);
  63962. indices.push(StartIndex + 1);
  63963. indices.push(StartIndex + 2);
  63964. indices.push(StartIndex + 3);
  63965. }
  63966. StartIndex += 4;
  63967. }
  63968. ;
  63969. };
  63970. return PolygonMeshBuilder;
  63971. }());
  63972. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  63973. })(BABYLON || (BABYLON = {}));
  63974. //# sourceMappingURL=babylon.polygonMesh.js.map
  63975. var BABYLON;
  63976. (function (BABYLON) {
  63977. // Unique ID when we import meshes from Babylon to CSG
  63978. var currentCSGMeshId = 0;
  63979. // # class Vertex
  63980. // Represents a vertex of a polygon. Use your own vertex class instead of this
  63981. // one to provide additional features like texture coordinates and vertex
  63982. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  63983. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  63984. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  63985. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  63986. // is not used anywhere else.
  63987. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  63988. var Vertex = /** @class */ (function () {
  63989. function Vertex(pos, normal, uv) {
  63990. this.pos = pos;
  63991. this.normal = normal;
  63992. this.uv = uv;
  63993. }
  63994. Vertex.prototype.clone = function () {
  63995. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  63996. };
  63997. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  63998. // orientation of a polygon is flipped.
  63999. Vertex.prototype.flip = function () {
  64000. this.normal = this.normal.scale(-1);
  64001. };
  64002. // Create a new vertex between this vertex and `other` by linearly
  64003. // interpolating all properties using a parameter of `t`. Subclasses should
  64004. // override this to interpolate additional properties.
  64005. Vertex.prototype.interpolate = function (other, t) {
  64006. 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));
  64007. };
  64008. return Vertex;
  64009. }());
  64010. // # class Plane
  64011. // Represents a plane in 3D space.
  64012. var Plane = /** @class */ (function () {
  64013. function Plane(normal, w) {
  64014. this.normal = normal;
  64015. this.w = w;
  64016. }
  64017. Plane.FromPoints = function (a, b, c) {
  64018. var v0 = c.subtract(a);
  64019. var v1 = b.subtract(a);
  64020. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64021. return null;
  64022. }
  64023. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64024. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64025. };
  64026. Plane.prototype.clone = function () {
  64027. return new Plane(this.normal.clone(), this.w);
  64028. };
  64029. Plane.prototype.flip = function () {
  64030. this.normal.scaleInPlace(-1);
  64031. this.w = -this.w;
  64032. };
  64033. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64034. // fragments in the appropriate lists. Coplanar polygons go into either
  64035. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64036. // respect to this plane. Polygons in front or in back of this plane go into
  64037. // either `front` or `back`.
  64038. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64039. var COPLANAR = 0;
  64040. var FRONT = 1;
  64041. var BACK = 2;
  64042. var SPANNING = 3;
  64043. // Classify each point as well as the entire polygon into one of the above
  64044. // four classes.
  64045. var polygonType = 0;
  64046. var types = [];
  64047. var i;
  64048. var t;
  64049. for (i = 0; i < polygon.vertices.length; i++) {
  64050. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64051. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64052. polygonType |= type;
  64053. types.push(type);
  64054. }
  64055. // Put the polygon in the correct list, splitting it when necessary.
  64056. switch (polygonType) {
  64057. case COPLANAR:
  64058. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64059. break;
  64060. case FRONT:
  64061. front.push(polygon);
  64062. break;
  64063. case BACK:
  64064. back.push(polygon);
  64065. break;
  64066. case SPANNING:
  64067. var f = [], b = [];
  64068. for (i = 0; i < polygon.vertices.length; i++) {
  64069. var j = (i + 1) % polygon.vertices.length;
  64070. var ti = types[i], tj = types[j];
  64071. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64072. if (ti !== BACK)
  64073. f.push(vi);
  64074. if (ti !== FRONT)
  64075. b.push(ti !== BACK ? vi.clone() : vi);
  64076. if ((ti | tj) === SPANNING) {
  64077. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  64078. var v = vi.interpolate(vj, t);
  64079. f.push(v);
  64080. b.push(v.clone());
  64081. }
  64082. }
  64083. var poly;
  64084. if (f.length >= 3) {
  64085. poly = new Polygon(f, polygon.shared);
  64086. if (poly.plane)
  64087. front.push(poly);
  64088. }
  64089. if (b.length >= 3) {
  64090. poly = new Polygon(b, polygon.shared);
  64091. if (poly.plane)
  64092. back.push(poly);
  64093. }
  64094. break;
  64095. }
  64096. };
  64097. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  64098. // point is on the plane.
  64099. Plane.EPSILON = 1e-5;
  64100. return Plane;
  64101. }());
  64102. // # class Polygon
  64103. // Represents a convex polygon. The vertices used to initialize a polygon must
  64104. // be coplanar and form a convex loop.
  64105. //
  64106. // Each convex polygon has a `shared` property, which is shared between all
  64107. // polygons that are clones of each other or were split from the same polygon.
  64108. // This can be used to define per-polygon properties (such as surface color).
  64109. var Polygon = /** @class */ (function () {
  64110. function Polygon(vertices, shared) {
  64111. this.vertices = vertices;
  64112. this.shared = shared;
  64113. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  64114. }
  64115. Polygon.prototype.clone = function () {
  64116. var vertices = this.vertices.map(function (v) { return v.clone(); });
  64117. return new Polygon(vertices, this.shared);
  64118. };
  64119. Polygon.prototype.flip = function () {
  64120. this.vertices.reverse().map(function (v) { v.flip(); });
  64121. this.plane.flip();
  64122. };
  64123. return Polygon;
  64124. }());
  64125. // # class Node
  64126. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  64127. // by picking a polygon to split along. That polygon (and all other coplanar
  64128. // polygons) are added directly to that node and the other polygons are added to
  64129. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  64130. // no distinction between internal and leaf nodes.
  64131. var Node = /** @class */ (function () {
  64132. function Node(polygons) {
  64133. this.plane = null;
  64134. this.front = null;
  64135. this.back = null;
  64136. this.polygons = new Array();
  64137. if (polygons) {
  64138. this.build(polygons);
  64139. }
  64140. }
  64141. Node.prototype.clone = function () {
  64142. var node = new Node();
  64143. node.plane = this.plane && this.plane.clone();
  64144. node.front = this.front && this.front.clone();
  64145. node.back = this.back && this.back.clone();
  64146. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  64147. return node;
  64148. };
  64149. // Convert solid space to empty space and empty space to solid space.
  64150. Node.prototype.invert = function () {
  64151. for (var i = 0; i < this.polygons.length; i++) {
  64152. this.polygons[i].flip();
  64153. }
  64154. if (this.plane) {
  64155. this.plane.flip();
  64156. }
  64157. if (this.front) {
  64158. this.front.invert();
  64159. }
  64160. if (this.back) {
  64161. this.back.invert();
  64162. }
  64163. var temp = this.front;
  64164. this.front = this.back;
  64165. this.back = temp;
  64166. };
  64167. // Recursively remove all polygons in `polygons` that are inside this BSP
  64168. // tree.
  64169. Node.prototype.clipPolygons = function (polygons) {
  64170. if (!this.plane)
  64171. return polygons.slice();
  64172. var front = new Array(), back = new Array();
  64173. for (var i = 0; i < polygons.length; i++) {
  64174. this.plane.splitPolygon(polygons[i], front, back, front, back);
  64175. }
  64176. if (this.front) {
  64177. front = this.front.clipPolygons(front);
  64178. }
  64179. if (this.back) {
  64180. back = this.back.clipPolygons(back);
  64181. }
  64182. else {
  64183. back = [];
  64184. }
  64185. return front.concat(back);
  64186. };
  64187. // Remove all polygons in this BSP tree that are inside the other BSP tree
  64188. // `bsp`.
  64189. Node.prototype.clipTo = function (bsp) {
  64190. this.polygons = bsp.clipPolygons(this.polygons);
  64191. if (this.front)
  64192. this.front.clipTo(bsp);
  64193. if (this.back)
  64194. this.back.clipTo(bsp);
  64195. };
  64196. // Return a list of all polygons in this BSP tree.
  64197. Node.prototype.allPolygons = function () {
  64198. var polygons = this.polygons.slice();
  64199. if (this.front)
  64200. polygons = polygons.concat(this.front.allPolygons());
  64201. if (this.back)
  64202. polygons = polygons.concat(this.back.allPolygons());
  64203. return polygons;
  64204. };
  64205. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  64206. // new polygons are filtered down to the bottom of the tree and become new
  64207. // nodes there. Each set of polygons is partitioned using the first polygon
  64208. // (no heuristic is used to pick a good split).
  64209. Node.prototype.build = function (polygons) {
  64210. if (!polygons.length)
  64211. return;
  64212. if (!this.plane)
  64213. this.plane = polygons[0].plane.clone();
  64214. var front = new Array(), back = new Array();
  64215. for (var i = 0; i < polygons.length; i++) {
  64216. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  64217. }
  64218. if (front.length) {
  64219. if (!this.front)
  64220. this.front = new Node();
  64221. this.front.build(front);
  64222. }
  64223. if (back.length) {
  64224. if (!this.back)
  64225. this.back = new Node();
  64226. this.back.build(back);
  64227. }
  64228. };
  64229. return Node;
  64230. }());
  64231. var CSG = /** @class */ (function () {
  64232. function CSG() {
  64233. this.polygons = new Array();
  64234. }
  64235. // Convert BABYLON.Mesh to BABYLON.CSG
  64236. CSG.FromMesh = function (mesh) {
  64237. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  64238. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  64239. if (mesh instanceof BABYLON.Mesh) {
  64240. mesh.computeWorldMatrix(true);
  64241. matrix = mesh.getWorldMatrix();
  64242. meshPosition = mesh.position.clone();
  64243. meshRotation = mesh.rotation.clone();
  64244. if (mesh.rotationQuaternion) {
  64245. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  64246. }
  64247. meshScaling = mesh.scaling.clone();
  64248. }
  64249. else {
  64250. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  64251. }
  64252. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64253. var subMeshes = mesh.subMeshes;
  64254. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  64255. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  64256. vertices = [];
  64257. for (var j = 0; j < 3; j++) {
  64258. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  64259. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  64260. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  64261. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  64262. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  64263. vertex = new Vertex(position, normal, uv);
  64264. vertices.push(vertex);
  64265. }
  64266. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  64267. // To handle the case of degenerated triangle
  64268. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  64269. if (polygon.plane)
  64270. polygons.push(polygon);
  64271. }
  64272. }
  64273. var csg = CSG.FromPolygons(polygons);
  64274. csg.matrix = matrix;
  64275. csg.position = meshPosition;
  64276. csg.rotation = meshRotation;
  64277. csg.scaling = meshScaling;
  64278. csg.rotationQuaternion = meshRotationQuaternion;
  64279. currentCSGMeshId++;
  64280. return csg;
  64281. };
  64282. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  64283. CSG.FromPolygons = function (polygons) {
  64284. var csg = new CSG();
  64285. csg.polygons = polygons;
  64286. return csg;
  64287. };
  64288. CSG.prototype.clone = function () {
  64289. var csg = new CSG();
  64290. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  64291. csg.copyTransformAttributes(this);
  64292. return csg;
  64293. };
  64294. CSG.prototype.union = function (csg) {
  64295. var a = new Node(this.clone().polygons);
  64296. var b = new Node(csg.clone().polygons);
  64297. a.clipTo(b);
  64298. b.clipTo(a);
  64299. b.invert();
  64300. b.clipTo(a);
  64301. b.invert();
  64302. a.build(b.allPolygons());
  64303. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64304. };
  64305. CSG.prototype.unionInPlace = function (csg) {
  64306. var a = new Node(this.polygons);
  64307. var b = new Node(csg.polygons);
  64308. a.clipTo(b);
  64309. b.clipTo(a);
  64310. b.invert();
  64311. b.clipTo(a);
  64312. b.invert();
  64313. a.build(b.allPolygons());
  64314. this.polygons = a.allPolygons();
  64315. };
  64316. CSG.prototype.subtract = function (csg) {
  64317. var a = new Node(this.clone().polygons);
  64318. var b = new Node(csg.clone().polygons);
  64319. a.invert();
  64320. a.clipTo(b);
  64321. b.clipTo(a);
  64322. b.invert();
  64323. b.clipTo(a);
  64324. b.invert();
  64325. a.build(b.allPolygons());
  64326. a.invert();
  64327. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64328. };
  64329. CSG.prototype.subtractInPlace = function (csg) {
  64330. var a = new Node(this.polygons);
  64331. var b = new Node(csg.polygons);
  64332. a.invert();
  64333. a.clipTo(b);
  64334. b.clipTo(a);
  64335. b.invert();
  64336. b.clipTo(a);
  64337. b.invert();
  64338. a.build(b.allPolygons());
  64339. a.invert();
  64340. this.polygons = a.allPolygons();
  64341. };
  64342. CSG.prototype.intersect = function (csg) {
  64343. var a = new Node(this.clone().polygons);
  64344. var b = new Node(csg.clone().polygons);
  64345. a.invert();
  64346. b.clipTo(a);
  64347. b.invert();
  64348. a.clipTo(b);
  64349. b.clipTo(a);
  64350. a.build(b.allPolygons());
  64351. a.invert();
  64352. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64353. };
  64354. CSG.prototype.intersectInPlace = function (csg) {
  64355. var a = new Node(this.polygons);
  64356. var b = new Node(csg.polygons);
  64357. a.invert();
  64358. b.clipTo(a);
  64359. b.invert();
  64360. a.clipTo(b);
  64361. b.clipTo(a);
  64362. a.build(b.allPolygons());
  64363. a.invert();
  64364. this.polygons = a.allPolygons();
  64365. };
  64366. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  64367. // not modified.
  64368. CSG.prototype.inverse = function () {
  64369. var csg = this.clone();
  64370. csg.inverseInPlace();
  64371. return csg;
  64372. };
  64373. CSG.prototype.inverseInPlace = function () {
  64374. this.polygons.map(function (p) { p.flip(); });
  64375. };
  64376. // This is used to keep meshes transformations so they can be restored
  64377. // when we build back a Babylon Mesh
  64378. // NB : All CSG operations are performed in world coordinates
  64379. CSG.prototype.copyTransformAttributes = function (csg) {
  64380. this.matrix = csg.matrix;
  64381. this.position = csg.position;
  64382. this.rotation = csg.rotation;
  64383. this.scaling = csg.scaling;
  64384. this.rotationQuaternion = csg.rotationQuaternion;
  64385. return this;
  64386. };
  64387. // Build Raw mesh from CSG
  64388. // Coordinates here are in world space
  64389. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  64390. var matrix = this.matrix.clone();
  64391. matrix.invert();
  64392. 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;
  64393. if (keepSubMeshes) {
  64394. // Sort Polygons, since subMeshes are indices range
  64395. polygons.sort(function (a, b) {
  64396. if (a.shared.meshId === b.shared.meshId) {
  64397. return a.shared.subMeshId - b.shared.subMeshId;
  64398. }
  64399. else {
  64400. return a.shared.meshId - b.shared.meshId;
  64401. }
  64402. });
  64403. }
  64404. for (var i = 0, il = polygons.length; i < il; i++) {
  64405. polygon = polygons[i];
  64406. // Building SubMeshes
  64407. if (!subMesh_dict[polygon.shared.meshId]) {
  64408. subMesh_dict[polygon.shared.meshId] = {};
  64409. }
  64410. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  64411. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  64412. indexStart: +Infinity,
  64413. indexEnd: -Infinity,
  64414. materialIndex: polygon.shared.materialIndex
  64415. };
  64416. }
  64417. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  64418. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  64419. polygonIndices[0] = 0;
  64420. polygonIndices[1] = j - 1;
  64421. polygonIndices[2] = j;
  64422. for (var k = 0; k < 3; k++) {
  64423. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  64424. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  64425. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  64426. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  64427. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  64428. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  64429. // Check if 2 points can be merged
  64430. if (!(typeof vertex_idx !== 'undefined' &&
  64431. normals[vertex_idx * 3] === localNormal.x &&
  64432. normals[vertex_idx * 3 + 1] === localNormal.y &&
  64433. normals[vertex_idx * 3 + 2] === localNormal.z &&
  64434. uvs[vertex_idx * 2] === uv.x &&
  64435. uvs[vertex_idx * 2 + 1] === uv.y)) {
  64436. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  64437. uvs.push(uv.x, uv.y);
  64438. normals.push(normal.x, normal.y, normal.z);
  64439. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  64440. }
  64441. indices.push(vertex_idx);
  64442. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  64443. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  64444. currentIndex++;
  64445. }
  64446. }
  64447. }
  64448. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  64449. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  64450. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  64451. mesh.setIndices(indices, null);
  64452. if (keepSubMeshes) {
  64453. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  64454. var materialIndexOffset = 0, materialMaxIndex;
  64455. mesh.subMeshes = new Array();
  64456. for (var m in subMesh_dict) {
  64457. materialMaxIndex = -1;
  64458. for (var sm in subMesh_dict[m]) {
  64459. subMesh_obj = subMesh_dict[m][sm];
  64460. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  64461. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  64462. }
  64463. materialIndexOffset += ++materialMaxIndex;
  64464. }
  64465. }
  64466. return mesh;
  64467. };
  64468. // Build Mesh from CSG taking material and transforms into account
  64469. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  64470. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  64471. mesh.material = material;
  64472. mesh.position.copyFrom(this.position);
  64473. mesh.rotation.copyFrom(this.rotation);
  64474. if (this.rotationQuaternion) {
  64475. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  64476. }
  64477. mesh.scaling.copyFrom(this.scaling);
  64478. mesh.computeWorldMatrix(true);
  64479. return mesh;
  64480. };
  64481. return CSG;
  64482. }());
  64483. BABYLON.CSG = CSG;
  64484. })(BABYLON || (BABYLON = {}));
  64485. //# sourceMappingURL=babylon.csg.js.map
  64486. var BABYLON;
  64487. (function (BABYLON) {
  64488. var LensFlare = /** @class */ (function () {
  64489. function LensFlare(size, position, color, imgUrl, system) {
  64490. this.size = size;
  64491. this.position = position;
  64492. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  64493. this.color = color || new BABYLON.Color3(1, 1, 1);
  64494. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  64495. this._system = system;
  64496. system.lensFlares.push(this);
  64497. }
  64498. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  64499. return new LensFlare(size, position, color, imgUrl, system);
  64500. };
  64501. LensFlare.prototype.dispose = function () {
  64502. if (this.texture) {
  64503. this.texture.dispose();
  64504. }
  64505. // Remove from scene
  64506. var index = this._system.lensFlares.indexOf(this);
  64507. this._system.lensFlares.splice(index, 1);
  64508. };
  64509. ;
  64510. return LensFlare;
  64511. }());
  64512. BABYLON.LensFlare = LensFlare;
  64513. })(BABYLON || (BABYLON = {}));
  64514. //# sourceMappingURL=babylon.lensFlare.js.map
  64515. var BABYLON;
  64516. (function (BABYLON) {
  64517. var LensFlareSystem = /** @class */ (function () {
  64518. function LensFlareSystem(name, emitter, scene) {
  64519. this.name = name;
  64520. this.lensFlares = new Array();
  64521. this.borderLimit = 300;
  64522. this.viewportBorder = 0;
  64523. this.layerMask = 0x0FFFFFFF;
  64524. this._vertexBuffers = {};
  64525. this._isEnabled = true;
  64526. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64527. this._emitter = emitter;
  64528. this.id = name;
  64529. scene.lensFlareSystems.push(this);
  64530. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  64531. var engine = scene.getEngine();
  64532. // VBO
  64533. var vertices = [];
  64534. vertices.push(1, 1);
  64535. vertices.push(-1, 1);
  64536. vertices.push(-1, -1);
  64537. vertices.push(1, -1);
  64538. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64539. // Indices
  64540. var indices = [];
  64541. indices.push(0);
  64542. indices.push(1);
  64543. indices.push(2);
  64544. indices.push(0);
  64545. indices.push(2);
  64546. indices.push(3);
  64547. this._indexBuffer = engine.createIndexBuffer(indices);
  64548. // Effects
  64549. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  64550. }
  64551. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  64552. get: function () {
  64553. return this._isEnabled;
  64554. },
  64555. set: function (value) {
  64556. this._isEnabled = value;
  64557. },
  64558. enumerable: true,
  64559. configurable: true
  64560. });
  64561. LensFlareSystem.prototype.getScene = function () {
  64562. return this._scene;
  64563. };
  64564. LensFlareSystem.prototype.getEmitter = function () {
  64565. return this._emitter;
  64566. };
  64567. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  64568. this._emitter = newEmitter;
  64569. };
  64570. LensFlareSystem.prototype.getEmitterPosition = function () {
  64571. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  64572. };
  64573. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  64574. var position = this.getEmitterPosition();
  64575. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  64576. this._positionX = position.x;
  64577. this._positionY = position.y;
  64578. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  64579. if (this.viewportBorder > 0) {
  64580. globalViewport.x -= this.viewportBorder;
  64581. globalViewport.y -= this.viewportBorder;
  64582. globalViewport.width += this.viewportBorder * 2;
  64583. globalViewport.height += this.viewportBorder * 2;
  64584. position.x += this.viewportBorder;
  64585. position.y += this.viewportBorder;
  64586. this._positionX += this.viewportBorder;
  64587. this._positionY += this.viewportBorder;
  64588. }
  64589. if (position.z > 0) {
  64590. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  64591. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  64592. return true;
  64593. }
  64594. return true;
  64595. }
  64596. return false;
  64597. };
  64598. LensFlareSystem.prototype._isVisible = function () {
  64599. if (!this._isEnabled || !this._scene.activeCamera) {
  64600. return false;
  64601. }
  64602. var emitterPosition = this.getEmitterPosition();
  64603. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  64604. var distance = direction.length();
  64605. direction.normalize();
  64606. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  64607. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  64608. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  64609. };
  64610. LensFlareSystem.prototype.render = function () {
  64611. if (!this._effect.isReady() || !this._scene.activeCamera)
  64612. return false;
  64613. var engine = this._scene.getEngine();
  64614. var viewport = this._scene.activeCamera.viewport;
  64615. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  64616. // Position
  64617. if (!this.computeEffectivePosition(globalViewport)) {
  64618. return false;
  64619. }
  64620. // Visibility
  64621. if (!this._isVisible()) {
  64622. return false;
  64623. }
  64624. // Intensity
  64625. var awayX;
  64626. var awayY;
  64627. if (this._positionX < this.borderLimit + globalViewport.x) {
  64628. awayX = this.borderLimit + globalViewport.x - this._positionX;
  64629. }
  64630. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  64631. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  64632. }
  64633. else {
  64634. awayX = 0;
  64635. }
  64636. if (this._positionY < this.borderLimit + globalViewport.y) {
  64637. awayY = this.borderLimit + globalViewport.y - this._positionY;
  64638. }
  64639. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  64640. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  64641. }
  64642. else {
  64643. awayY = 0;
  64644. }
  64645. var away = (awayX > awayY) ? awayX : awayY;
  64646. away -= this.viewportBorder;
  64647. if (away > this.borderLimit) {
  64648. away = this.borderLimit;
  64649. }
  64650. var intensity = 1.0 - (away / this.borderLimit);
  64651. if (intensity < 0) {
  64652. return false;
  64653. }
  64654. if (intensity > 1.0) {
  64655. intensity = 1.0;
  64656. }
  64657. if (this.viewportBorder > 0) {
  64658. globalViewport.x += this.viewportBorder;
  64659. globalViewport.y += this.viewportBorder;
  64660. globalViewport.width -= this.viewportBorder * 2;
  64661. globalViewport.height -= this.viewportBorder * 2;
  64662. this._positionX -= this.viewportBorder;
  64663. this._positionY -= this.viewportBorder;
  64664. }
  64665. // Position
  64666. var centerX = globalViewport.x + globalViewport.width / 2;
  64667. var centerY = globalViewport.y + globalViewport.height / 2;
  64668. var distX = centerX - this._positionX;
  64669. var distY = centerY - this._positionY;
  64670. // Effects
  64671. engine.enableEffect(this._effect);
  64672. engine.setState(false);
  64673. engine.setDepthBuffer(false);
  64674. // VBOs
  64675. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64676. // Flares
  64677. for (var index = 0; index < this.lensFlares.length; index++) {
  64678. var flare = this.lensFlares[index];
  64679. engine.setAlphaMode(flare.alphaMode);
  64680. var x = centerX - (distX * flare.position);
  64681. var y = centerY - (distY * flare.position);
  64682. var cw = flare.size;
  64683. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  64684. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  64685. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  64686. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  64687. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  64688. // Texture
  64689. this._effect.setTexture("textureSampler", flare.texture);
  64690. // Color
  64691. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  64692. // Draw order
  64693. engine.draw(true, 0, 6);
  64694. }
  64695. engine.setDepthBuffer(true);
  64696. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64697. return true;
  64698. };
  64699. LensFlareSystem.prototype.dispose = function () {
  64700. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64701. if (vertexBuffer) {
  64702. vertexBuffer.dispose();
  64703. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64704. }
  64705. if (this._indexBuffer) {
  64706. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64707. this._indexBuffer = null;
  64708. }
  64709. while (this.lensFlares.length) {
  64710. this.lensFlares[0].dispose();
  64711. }
  64712. // Remove from scene
  64713. var index = this._scene.lensFlareSystems.indexOf(this);
  64714. this._scene.lensFlareSystems.splice(index, 1);
  64715. };
  64716. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  64717. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  64718. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  64719. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  64720. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  64721. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  64722. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  64723. var parsedFlare = parsedLensFlareSystem.flares[index];
  64724. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  64725. }
  64726. return lensFlareSystem;
  64727. };
  64728. LensFlareSystem.prototype.serialize = function () {
  64729. var serializationObject = {};
  64730. serializationObject.id = this.id;
  64731. serializationObject.name = this.name;
  64732. serializationObject.emitterId = this.getEmitter().id;
  64733. serializationObject.borderLimit = this.borderLimit;
  64734. serializationObject.flares = [];
  64735. for (var index = 0; index < this.lensFlares.length; index++) {
  64736. var flare = this.lensFlares[index];
  64737. serializationObject.flares.push({
  64738. size: flare.size,
  64739. position: flare.position,
  64740. color: flare.color.asArray(),
  64741. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  64742. });
  64743. }
  64744. return serializationObject;
  64745. };
  64746. return LensFlareSystem;
  64747. }());
  64748. BABYLON.LensFlareSystem = LensFlareSystem;
  64749. })(BABYLON || (BABYLON = {}));
  64750. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  64751. var BABYLON;
  64752. (function (BABYLON) {
  64753. /**
  64754. * This is a holder class for the physics joint created by the physics plugin.
  64755. * It holds a set of functions to control the underlying joint.
  64756. */
  64757. var PhysicsJoint = /** @class */ (function () {
  64758. function PhysicsJoint(type, jointData) {
  64759. this.type = type;
  64760. this.jointData = jointData;
  64761. jointData.nativeParams = jointData.nativeParams || {};
  64762. }
  64763. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  64764. get: function () {
  64765. return this._physicsJoint;
  64766. },
  64767. set: function (newJoint) {
  64768. if (this._physicsJoint) {
  64769. //remove from the wolrd
  64770. }
  64771. this._physicsJoint = newJoint;
  64772. },
  64773. enumerable: true,
  64774. configurable: true
  64775. });
  64776. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  64777. set: function (physicsPlugin) {
  64778. this._physicsPlugin = physicsPlugin;
  64779. },
  64780. enumerable: true,
  64781. configurable: true
  64782. });
  64783. /**
  64784. * Execute a function that is physics-plugin specific.
  64785. * @param {Function} func the function that will be executed.
  64786. * It accepts two parameters: the physics world and the physics joint.
  64787. */
  64788. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  64789. func(this._physicsPlugin.world, this._physicsJoint);
  64790. };
  64791. //TODO check if the native joints are the same
  64792. //Joint Types
  64793. PhysicsJoint.DistanceJoint = 0;
  64794. PhysicsJoint.HingeJoint = 1;
  64795. PhysicsJoint.BallAndSocketJoint = 2;
  64796. PhysicsJoint.WheelJoint = 3;
  64797. PhysicsJoint.SliderJoint = 4;
  64798. //OIMO
  64799. PhysicsJoint.PrismaticJoint = 5;
  64800. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  64801. PhysicsJoint.UniversalJoint = 6;
  64802. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  64803. //Cannon
  64804. //Similar to a Ball-Joint. Different in params
  64805. PhysicsJoint.PointToPointJoint = 8;
  64806. //Cannon only at the moment
  64807. PhysicsJoint.SpringJoint = 9;
  64808. PhysicsJoint.LockJoint = 10;
  64809. return PhysicsJoint;
  64810. }());
  64811. BABYLON.PhysicsJoint = PhysicsJoint;
  64812. /**
  64813. * A class representing a physics distance joint.
  64814. */
  64815. var DistanceJoint = /** @class */ (function (_super) {
  64816. __extends(DistanceJoint, _super);
  64817. function DistanceJoint(jointData) {
  64818. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  64819. }
  64820. /**
  64821. * Update the predefined distance.
  64822. */
  64823. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  64824. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  64825. };
  64826. return DistanceJoint;
  64827. }(PhysicsJoint));
  64828. BABYLON.DistanceJoint = DistanceJoint;
  64829. var MotorEnabledJoint = /** @class */ (function (_super) {
  64830. __extends(MotorEnabledJoint, _super);
  64831. function MotorEnabledJoint(type, jointData) {
  64832. return _super.call(this, type, jointData) || this;
  64833. }
  64834. /**
  64835. * Set the motor values.
  64836. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64837. * @param {number} force the force to apply
  64838. * @param {number} maxForce max force for this motor.
  64839. */
  64840. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  64841. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  64842. };
  64843. /**
  64844. * Set the motor's limits.
  64845. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64846. */
  64847. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  64848. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  64849. };
  64850. return MotorEnabledJoint;
  64851. }(PhysicsJoint));
  64852. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  64853. /**
  64854. * This class represents a single hinge physics joint
  64855. */
  64856. var HingeJoint = /** @class */ (function (_super) {
  64857. __extends(HingeJoint, _super);
  64858. function HingeJoint(jointData) {
  64859. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  64860. }
  64861. /**
  64862. * Set the motor values.
  64863. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64864. * @param {number} force the force to apply
  64865. * @param {number} maxForce max force for this motor.
  64866. */
  64867. HingeJoint.prototype.setMotor = function (force, maxForce) {
  64868. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  64869. };
  64870. /**
  64871. * Set the motor's limits.
  64872. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64873. */
  64874. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  64875. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  64876. };
  64877. return HingeJoint;
  64878. }(MotorEnabledJoint));
  64879. BABYLON.HingeJoint = HingeJoint;
  64880. /**
  64881. * This class represents a dual hinge physics joint (same as wheel joint)
  64882. */
  64883. var Hinge2Joint = /** @class */ (function (_super) {
  64884. __extends(Hinge2Joint, _super);
  64885. function Hinge2Joint(jointData) {
  64886. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  64887. }
  64888. /**
  64889. * Set the motor values.
  64890. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64891. * @param {number} force the force to apply
  64892. * @param {number} maxForce max force for this motor.
  64893. * @param {motorIndex} the motor's index, 0 or 1.
  64894. */
  64895. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  64896. if (motorIndex === void 0) { motorIndex = 0; }
  64897. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  64898. };
  64899. /**
  64900. * Set the motor limits.
  64901. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64902. * @param {number} upperLimit the upper limit
  64903. * @param {number} lowerLimit lower limit
  64904. * @param {motorIndex} the motor's index, 0 or 1.
  64905. */
  64906. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  64907. if (motorIndex === void 0) { motorIndex = 0; }
  64908. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  64909. };
  64910. return Hinge2Joint;
  64911. }(MotorEnabledJoint));
  64912. BABYLON.Hinge2Joint = Hinge2Joint;
  64913. })(BABYLON || (BABYLON = {}));
  64914. //# sourceMappingURL=babylon.physicsJoint.js.map
  64915. var BABYLON;
  64916. (function (BABYLON) {
  64917. var PhysicsImpostor = /** @class */ (function () {
  64918. function PhysicsImpostor(object, type, _options, _scene) {
  64919. if (_options === void 0) { _options = { mass: 0 }; }
  64920. var _this = this;
  64921. this.object = object;
  64922. this.type = type;
  64923. this._options = _options;
  64924. this._scene = _scene;
  64925. this._bodyUpdateRequired = false;
  64926. this._onBeforePhysicsStepCallbacks = new Array();
  64927. this._onAfterPhysicsStepCallbacks = new Array();
  64928. this._onPhysicsCollideCallbacks = [];
  64929. this._deltaPosition = BABYLON.Vector3.Zero();
  64930. this._isDisposed = false;
  64931. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  64932. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  64933. /**
  64934. * this function is executed by the physics engine.
  64935. */
  64936. this.beforeStep = function () {
  64937. if (!_this._physicsEngine) {
  64938. return;
  64939. }
  64940. if (_this._options.ignoreParent && _this.object.parent) {
  64941. _this._tmpPositionWithDelta.copyFrom(_this.object.getAbsolutePosition());
  64942. //this.object.getAbsolutePosition().subtractToRef(this._deltaPosition, this._tmpPositionWithDelta);
  64943. }
  64944. else {
  64945. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  64946. }
  64947. //conjugate deltaRotation
  64948. if (_this.object.rotationQuaternion) {
  64949. if (_this._deltaRotationConjugated) {
  64950. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  64951. }
  64952. else {
  64953. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  64954. }
  64955. }
  64956. // Only if not disabled
  64957. if (!_this._options.disableBidirectionalTransformation) {
  64958. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  64959. }
  64960. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  64961. func(_this);
  64962. });
  64963. };
  64964. /**
  64965. * this function is executed by the physics engine.
  64966. */
  64967. this.afterStep = function () {
  64968. if (!_this._physicsEngine) {
  64969. return;
  64970. }
  64971. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  64972. func(_this);
  64973. });
  64974. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  64975. if (_this._options.ignoreParent && _this.object.parent) {
  64976. _this.object.position.subtractInPlace(_this.object.parent.getAbsolutePosition());
  64977. }
  64978. else {
  64979. _this.object.position.addInPlace(_this._deltaPosition);
  64980. }
  64981. if (_this._deltaRotation && _this.object.rotationQuaternion) {
  64982. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  64983. }
  64984. };
  64985. /**
  64986. * Legacy collision detection event support
  64987. */
  64988. this.onCollideEvent = null;
  64989. //event and body object due to cannon's event-based architecture.
  64990. this.onCollide = function (e) {
  64991. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  64992. return;
  64993. }
  64994. if (!_this._physicsEngine) {
  64995. return;
  64996. }
  64997. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  64998. if (otherImpostor) {
  64999. // Legacy collision detection event support
  65000. if (_this.onCollideEvent) {
  65001. _this.onCollideEvent(_this, otherImpostor);
  65002. }
  65003. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65004. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65005. }).forEach(function (obj) {
  65006. obj.callback(_this, otherImpostor);
  65007. });
  65008. }
  65009. };
  65010. //sanity check!
  65011. if (!this.object) {
  65012. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65013. return;
  65014. }
  65015. //legacy support for old syntax.
  65016. if (!this._scene && object.getScene) {
  65017. this._scene = object.getScene();
  65018. }
  65019. if (!this._scene) {
  65020. return;
  65021. }
  65022. this._physicsEngine = this._scene.getPhysicsEngine();
  65023. if (!this._physicsEngine) {
  65024. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65025. }
  65026. else {
  65027. //set the object's quaternion, if not set
  65028. if (!this.object.rotationQuaternion) {
  65029. if (this.object.rotation) {
  65030. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65031. }
  65032. else {
  65033. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65034. }
  65035. }
  65036. //default options params
  65037. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65038. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65039. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65040. this._joints = [];
  65041. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65042. if (!this.object.parent || this._options.ignoreParent) {
  65043. this._init();
  65044. }
  65045. else if (this.object.parent.physicsImpostor) {
  65046. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65047. }
  65048. }
  65049. }
  65050. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65051. get: function () {
  65052. return this._isDisposed;
  65053. },
  65054. enumerable: true,
  65055. configurable: true
  65056. });
  65057. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65058. get: function () {
  65059. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65060. },
  65061. set: function (value) {
  65062. this.setMass(value);
  65063. },
  65064. enumerable: true,
  65065. configurable: true
  65066. });
  65067. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65068. get: function () {
  65069. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65070. },
  65071. set: function (value) {
  65072. if (!this._physicsEngine) {
  65073. return;
  65074. }
  65075. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65076. },
  65077. enumerable: true,
  65078. configurable: true
  65079. });
  65080. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  65081. get: function () {
  65082. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  65083. },
  65084. set: function (value) {
  65085. if (!this._physicsEngine) {
  65086. return;
  65087. }
  65088. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  65089. },
  65090. enumerable: true,
  65091. configurable: true
  65092. });
  65093. /**
  65094. * This function will completly initialize this impostor.
  65095. * It will create a new body - but only if this mesh has no parent.
  65096. * If it has, this impostor will not be used other than to define the impostor
  65097. * of the child mesh.
  65098. */
  65099. PhysicsImpostor.prototype._init = function () {
  65100. if (!this._physicsEngine) {
  65101. return;
  65102. }
  65103. this._physicsEngine.removeImpostor(this);
  65104. this.physicsBody = null;
  65105. this._parent = this._parent || this._getPhysicsParent();
  65106. if (!this.parent || this._options.ignoreParent) {
  65107. this._physicsEngine.addImpostor(this);
  65108. }
  65109. };
  65110. PhysicsImpostor.prototype._getPhysicsParent = function () {
  65111. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  65112. var parentMesh = this.object.parent;
  65113. return parentMesh.physicsImpostor;
  65114. }
  65115. return null;
  65116. };
  65117. /**
  65118. * Should a new body be generated.
  65119. */
  65120. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  65121. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  65122. };
  65123. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  65124. this.forceUpdate();
  65125. };
  65126. /**
  65127. * Force a regeneration of this or the parent's impostor's body.
  65128. * Use under cautious - This will remove all joints already implemented.
  65129. */
  65130. PhysicsImpostor.prototype.forceUpdate = function () {
  65131. this._init();
  65132. if (this.parent && !this._options.ignoreParent) {
  65133. this.parent.forceUpdate();
  65134. }
  65135. };
  65136. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  65137. /*public get mesh(): AbstractMesh {
  65138. return this._mesh;
  65139. }*/
  65140. /**
  65141. * Gets the body that holds this impostor. Either its own, or its parent.
  65142. */
  65143. get: function () {
  65144. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  65145. },
  65146. /**
  65147. * Set the physics body. Used mainly by the physics engine/plugin
  65148. */
  65149. set: function (physicsBody) {
  65150. if (this._physicsBody && this._physicsEngine) {
  65151. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  65152. }
  65153. this._physicsBody = physicsBody;
  65154. this.resetUpdateFlags();
  65155. },
  65156. enumerable: true,
  65157. configurable: true
  65158. });
  65159. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  65160. get: function () {
  65161. return !this._options.ignoreParent && this._parent ? this._parent : null;
  65162. },
  65163. set: function (value) {
  65164. this._parent = value;
  65165. },
  65166. enumerable: true,
  65167. configurable: true
  65168. });
  65169. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  65170. this._bodyUpdateRequired = false;
  65171. };
  65172. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  65173. if (this.object.getBoundingInfo) {
  65174. var q = this.object.rotationQuaternion;
  65175. //reset rotation
  65176. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  65177. //calculate the world matrix with no rotation
  65178. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65179. var boundingInfo = this.object.getBoundingInfo();
  65180. var size = void 0;
  65181. if (boundingInfo) {
  65182. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  65183. }
  65184. else {
  65185. size = BABYLON.Vector3.Zero();
  65186. }
  65187. //bring back the rotation
  65188. this.object.rotationQuaternion = q;
  65189. //calculate the world matrix with the new rotation
  65190. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65191. return size;
  65192. }
  65193. else {
  65194. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  65195. }
  65196. };
  65197. PhysicsImpostor.prototype.getObjectCenter = function () {
  65198. if (this.object.getBoundingInfo) {
  65199. var boundingInfo = this.object.getBoundingInfo();
  65200. if (!boundingInfo) {
  65201. return this.object.position;
  65202. }
  65203. return boundingInfo.boundingBox.centerWorld;
  65204. }
  65205. else {
  65206. return this.object.position;
  65207. }
  65208. };
  65209. /**
  65210. * Get a specific parametes from the options parameter.
  65211. */
  65212. PhysicsImpostor.prototype.getParam = function (paramName) {
  65213. return this._options[paramName];
  65214. };
  65215. /**
  65216. * Sets a specific parameter in the options given to the physics plugin
  65217. */
  65218. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  65219. this._options[paramName] = value;
  65220. this._bodyUpdateRequired = true;
  65221. };
  65222. /**
  65223. * Specifically change the body's mass option. Won't recreate the physics body object
  65224. */
  65225. PhysicsImpostor.prototype.setMass = function (mass) {
  65226. if (this.getParam("mass") !== mass) {
  65227. this.setParam("mass", mass);
  65228. }
  65229. if (this._physicsEngine) {
  65230. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  65231. }
  65232. };
  65233. PhysicsImpostor.prototype.getLinearVelocity = function () {
  65234. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  65235. };
  65236. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  65237. if (this._physicsEngine) {
  65238. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  65239. }
  65240. };
  65241. PhysicsImpostor.prototype.getAngularVelocity = function () {
  65242. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  65243. };
  65244. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  65245. if (this._physicsEngine) {
  65246. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  65247. }
  65248. };
  65249. /**
  65250. * Execute a function with the physics plugin native code.
  65251. * Provide a function the will have two variables - the world object and the physics body object.
  65252. */
  65253. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  65254. if (this._physicsEngine) {
  65255. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  65256. }
  65257. };
  65258. /**
  65259. * Register a function that will be executed before the physics world is stepping forward.
  65260. */
  65261. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  65262. this._onBeforePhysicsStepCallbacks.push(func);
  65263. };
  65264. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  65265. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  65266. if (index > -1) {
  65267. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  65268. }
  65269. else {
  65270. BABYLON.Tools.Warn("Function to remove was not found");
  65271. }
  65272. };
  65273. /**
  65274. * Register a function that will be executed after the physics step
  65275. */
  65276. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  65277. this._onAfterPhysicsStepCallbacks.push(func);
  65278. };
  65279. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  65280. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  65281. if (index > -1) {
  65282. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  65283. }
  65284. else {
  65285. BABYLON.Tools.Warn("Function to remove was not found");
  65286. }
  65287. };
  65288. /**
  65289. * register a function that will be executed when this impostor collides against a different body.
  65290. */
  65291. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  65292. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65293. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  65294. };
  65295. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  65296. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65297. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  65298. if (index > -1) {
  65299. this._onPhysicsCollideCallbacks.splice(index, 1);
  65300. }
  65301. else {
  65302. BABYLON.Tools.Warn("Function to remove was not found");
  65303. }
  65304. };
  65305. /**
  65306. * Apply a force
  65307. */
  65308. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  65309. if (this._physicsEngine) {
  65310. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  65311. }
  65312. return this;
  65313. };
  65314. /**
  65315. * Apply an impulse
  65316. */
  65317. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  65318. if (this._physicsEngine) {
  65319. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  65320. }
  65321. return this;
  65322. };
  65323. /**
  65324. * A help function to create a joint.
  65325. */
  65326. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  65327. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  65328. this.addJoint(otherImpostor, joint);
  65329. return this;
  65330. };
  65331. /**
  65332. * Add a joint to this impostor with a different impostor.
  65333. */
  65334. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  65335. this._joints.push({
  65336. otherImpostor: otherImpostor,
  65337. joint: joint
  65338. });
  65339. if (this._physicsEngine) {
  65340. this._physicsEngine.addJoint(this, otherImpostor, joint);
  65341. }
  65342. return this;
  65343. };
  65344. /**
  65345. * Will keep this body still, in a sleep mode.
  65346. */
  65347. PhysicsImpostor.prototype.sleep = function () {
  65348. if (this._physicsEngine) {
  65349. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  65350. }
  65351. return this;
  65352. };
  65353. /**
  65354. * Wake the body up.
  65355. */
  65356. PhysicsImpostor.prototype.wakeUp = function () {
  65357. if (this._physicsEngine) {
  65358. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  65359. }
  65360. return this;
  65361. };
  65362. PhysicsImpostor.prototype.clone = function (newObject) {
  65363. if (!newObject)
  65364. return null;
  65365. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  65366. };
  65367. PhysicsImpostor.prototype.dispose = function () {
  65368. var _this = this;
  65369. //no dispose if no physics engine is available.
  65370. if (!this._physicsEngine) {
  65371. return;
  65372. }
  65373. this._joints.forEach(function (j) {
  65374. if (_this._physicsEngine) {
  65375. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  65376. }
  65377. });
  65378. //dispose the physics body
  65379. this._physicsEngine.removeImpostor(this);
  65380. if (this.parent) {
  65381. this.parent.forceUpdate();
  65382. }
  65383. else {
  65384. /*this._object.getChildMeshes().forEach(function(mesh) {
  65385. if (mesh.physicsImpostor) {
  65386. if (disposeChildren) {
  65387. mesh.physicsImpostor.dispose();
  65388. mesh.physicsImpostor = null;
  65389. }
  65390. }
  65391. })*/
  65392. }
  65393. this._isDisposed = true;
  65394. };
  65395. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  65396. this._deltaPosition.copyFrom(position);
  65397. };
  65398. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  65399. if (!this._deltaRotation) {
  65400. this._deltaRotation = new BABYLON.Quaternion();
  65401. }
  65402. this._deltaRotation.copyFrom(rotation);
  65403. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  65404. };
  65405. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  65406. if (this._physicsEngine) {
  65407. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  65408. }
  65409. return this;
  65410. };
  65411. PhysicsImpostor.prototype.getRadius = function () {
  65412. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  65413. };
  65414. /**
  65415. * Sync a bone with this impostor
  65416. * @param bone The bone to sync to the impostor.
  65417. * @param boneMesh The mesh that the bone is influencing.
  65418. * @param jointPivot The pivot of the joint / bone in local space.
  65419. * @param distToJoint Optional distance from the impostor to the joint.
  65420. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65421. */
  65422. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  65423. var tempVec = PhysicsImpostor._tmpVecs[0];
  65424. var mesh = this.object;
  65425. if (mesh.rotationQuaternion) {
  65426. if (adjustRotation) {
  65427. var tempQuat = PhysicsImpostor._tmpQuat;
  65428. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  65429. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  65430. }
  65431. else {
  65432. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  65433. }
  65434. }
  65435. tempVec.x = 0;
  65436. tempVec.y = 0;
  65437. tempVec.z = 0;
  65438. if (jointPivot) {
  65439. tempVec.x = jointPivot.x;
  65440. tempVec.y = jointPivot.y;
  65441. tempVec.z = jointPivot.z;
  65442. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  65443. if (distToJoint === undefined || distToJoint === null) {
  65444. distToJoint = jointPivot.length();
  65445. }
  65446. tempVec.x *= distToJoint;
  65447. tempVec.y *= distToJoint;
  65448. tempVec.z *= distToJoint;
  65449. }
  65450. if (bone.getParent()) {
  65451. tempVec.addInPlace(mesh.getAbsolutePosition());
  65452. bone.setAbsolutePosition(tempVec, boneMesh);
  65453. }
  65454. else {
  65455. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  65456. boneMesh.position.x -= tempVec.x;
  65457. boneMesh.position.y -= tempVec.y;
  65458. boneMesh.position.z -= tempVec.z;
  65459. }
  65460. };
  65461. /**
  65462. * Sync impostor to a bone
  65463. * @param bone The bone that the impostor will be synced to.
  65464. * @param boneMesh The mesh that the bone is influencing.
  65465. * @param jointPivot The pivot of the joint / bone in local space.
  65466. * @param distToJoint Optional distance from the impostor to the joint.
  65467. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65468. * @param boneAxis Optional vector3 axis the bone is aligned with
  65469. */
  65470. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  65471. var mesh = this.object;
  65472. if (mesh.rotationQuaternion) {
  65473. if (adjustRotation) {
  65474. var tempQuat = PhysicsImpostor._tmpQuat;
  65475. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  65476. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  65477. }
  65478. else {
  65479. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  65480. }
  65481. }
  65482. var pos = PhysicsImpostor._tmpVecs[0];
  65483. var boneDir = PhysicsImpostor._tmpVecs[1];
  65484. if (!boneAxis) {
  65485. boneAxis = PhysicsImpostor._tmpVecs[2];
  65486. boneAxis.x = 0;
  65487. boneAxis.y = 1;
  65488. boneAxis.z = 0;
  65489. }
  65490. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  65491. bone.getAbsolutePositionToRef(boneMesh, pos);
  65492. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  65493. distToJoint = jointPivot.length();
  65494. }
  65495. if (distToJoint !== undefined && distToJoint !== null) {
  65496. pos.x += boneDir.x * distToJoint;
  65497. pos.y += boneDir.y * distToJoint;
  65498. pos.z += boneDir.z * distToJoint;
  65499. }
  65500. mesh.setAbsolutePosition(pos);
  65501. };
  65502. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  65503. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  65504. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65505. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  65506. //Impostor types
  65507. PhysicsImpostor.NoImpostor = 0;
  65508. PhysicsImpostor.SphereImpostor = 1;
  65509. PhysicsImpostor.BoxImpostor = 2;
  65510. PhysicsImpostor.PlaneImpostor = 3;
  65511. PhysicsImpostor.MeshImpostor = 4;
  65512. PhysicsImpostor.CylinderImpostor = 7;
  65513. PhysicsImpostor.ParticleImpostor = 8;
  65514. PhysicsImpostor.HeightmapImpostor = 9;
  65515. return PhysicsImpostor;
  65516. }());
  65517. BABYLON.PhysicsImpostor = PhysicsImpostor;
  65518. })(BABYLON || (BABYLON = {}));
  65519. //# sourceMappingURL=babylon.physicsImpostor.js.map
  65520. var BABYLON;
  65521. (function (BABYLON) {
  65522. var PhysicsEngine = /** @class */ (function () {
  65523. function PhysicsEngine(gravity, _physicsPlugin) {
  65524. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  65525. this._physicsPlugin = _physicsPlugin;
  65526. //new methods and parameters
  65527. this._impostors = [];
  65528. this._joints = [];
  65529. if (!this._physicsPlugin.isSupported()) {
  65530. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  65531. + "Please make sure it is included.");
  65532. }
  65533. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  65534. this.setGravity(gravity);
  65535. this.setTimeStep();
  65536. }
  65537. PhysicsEngine.prototype.setGravity = function (gravity) {
  65538. this.gravity = gravity;
  65539. this._physicsPlugin.setGravity(this.gravity);
  65540. };
  65541. /**
  65542. * Set the time step of the physics engine.
  65543. * default is 1/60.
  65544. * To slow it down, enter 1/600 for example.
  65545. * To speed it up, 1/30
  65546. * @param {number} newTimeStep the new timestep to apply to this world.
  65547. */
  65548. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  65549. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  65550. this._physicsPlugin.setTimeStep(newTimeStep);
  65551. };
  65552. /**
  65553. * Get the time step of the physics engine.
  65554. */
  65555. PhysicsEngine.prototype.getTimeStep = function () {
  65556. return this._physicsPlugin.getTimeStep();
  65557. };
  65558. PhysicsEngine.prototype.dispose = function () {
  65559. this._impostors.forEach(function (impostor) {
  65560. impostor.dispose();
  65561. });
  65562. this._physicsPlugin.dispose();
  65563. };
  65564. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  65565. return this._physicsPlugin.name;
  65566. };
  65567. /**
  65568. * Adding a new impostor for the impostor tracking.
  65569. * This will be done by the impostor itself.
  65570. * @param {PhysicsImpostor} impostor the impostor to add
  65571. */
  65572. PhysicsEngine.prototype.addImpostor = function (impostor) {
  65573. impostor.uniqueId = this._impostors.push(impostor);
  65574. //if no parent, generate the body
  65575. if (!impostor.parent) {
  65576. this._physicsPlugin.generatePhysicsBody(impostor);
  65577. }
  65578. };
  65579. /**
  65580. * Remove an impostor from the engine.
  65581. * This impostor and its mesh will not longer be updated by the physics engine.
  65582. * @param {PhysicsImpostor} impostor the impostor to remove
  65583. */
  65584. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  65585. var index = this._impostors.indexOf(impostor);
  65586. if (index > -1) {
  65587. var removed = this._impostors.splice(index, 1);
  65588. //Is it needed?
  65589. if (removed.length) {
  65590. //this will also remove it from the world.
  65591. removed[0].physicsBody = null;
  65592. }
  65593. }
  65594. };
  65595. /**
  65596. * Add a joint to the physics engine
  65597. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  65598. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  65599. * @param {PhysicsJoint} the joint that will connect both impostors.
  65600. */
  65601. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  65602. var impostorJoint = {
  65603. mainImpostor: mainImpostor,
  65604. connectedImpostor: connectedImpostor,
  65605. joint: joint
  65606. };
  65607. joint.physicsPlugin = this._physicsPlugin;
  65608. this._joints.push(impostorJoint);
  65609. this._physicsPlugin.generateJoint(impostorJoint);
  65610. };
  65611. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  65612. var matchingJoints = this._joints.filter(function (impostorJoint) {
  65613. return (impostorJoint.connectedImpostor === connectedImpostor
  65614. && impostorJoint.joint === joint
  65615. && impostorJoint.mainImpostor === mainImpostor);
  65616. });
  65617. if (matchingJoints.length) {
  65618. this._physicsPlugin.removeJoint(matchingJoints[0]);
  65619. //TODO remove it from the list as well
  65620. }
  65621. };
  65622. /**
  65623. * Called by the scene. no need to call it.
  65624. */
  65625. PhysicsEngine.prototype._step = function (delta) {
  65626. var _this = this;
  65627. //check if any mesh has no body / requires an update
  65628. this._impostors.forEach(function (impostor) {
  65629. if (impostor.isBodyInitRequired()) {
  65630. _this._physicsPlugin.generatePhysicsBody(impostor);
  65631. }
  65632. });
  65633. if (delta > 0.1) {
  65634. delta = 0.1;
  65635. }
  65636. else if (delta <= 0) {
  65637. delta = 1.0 / 60.0;
  65638. }
  65639. this._physicsPlugin.executeStep(delta, this._impostors);
  65640. };
  65641. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  65642. return this._physicsPlugin;
  65643. };
  65644. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  65645. for (var i = 0; i < this._impostors.length; ++i) {
  65646. if (this._impostors[i].object === object) {
  65647. return this._impostors[i];
  65648. }
  65649. }
  65650. return null;
  65651. };
  65652. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  65653. for (var i = 0; i < this._impostors.length; ++i) {
  65654. if (this._impostors[i].physicsBody === body) {
  65655. return this._impostors[i];
  65656. }
  65657. }
  65658. return null;
  65659. };
  65660. // Statics
  65661. PhysicsEngine.Epsilon = 0.001;
  65662. return PhysicsEngine;
  65663. }());
  65664. BABYLON.PhysicsEngine = PhysicsEngine;
  65665. })(BABYLON || (BABYLON = {}));
  65666. //# sourceMappingURL=babylon.physicsEngine.js.map
  65667. var BABYLON;
  65668. (function (BABYLON) {
  65669. var CannonJSPlugin = /** @class */ (function () {
  65670. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  65671. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  65672. if (iterations === void 0) { iterations = 10; }
  65673. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  65674. this.name = "CannonJSPlugin";
  65675. this._physicsMaterials = new Array();
  65676. this._fixedTimeStep = 1 / 60;
  65677. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  65678. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  65679. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  65680. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  65681. this._tmpPosition = BABYLON.Vector3.Zero();
  65682. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  65683. this._tmpUnityRotation = new BABYLON.Quaternion();
  65684. if (!this.isSupported()) {
  65685. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  65686. return;
  65687. }
  65688. this.world = new this.BJSCANNON.World();
  65689. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  65690. this.world.solver.iterations = iterations;
  65691. }
  65692. CannonJSPlugin.prototype.setGravity = function (gravity) {
  65693. this.world.gravity.copy(gravity);
  65694. };
  65695. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  65696. this._fixedTimeStep = timeStep;
  65697. };
  65698. CannonJSPlugin.prototype.getTimeStep = function () {
  65699. return this._fixedTimeStep;
  65700. };
  65701. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  65702. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  65703. };
  65704. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  65705. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65706. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65707. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  65708. };
  65709. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  65710. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65711. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65712. impostor.physicsBody.applyForce(impulse, worldPoint);
  65713. };
  65714. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  65715. //parent-child relationship. Does this impostor has a parent impostor?
  65716. if (impostor.parent) {
  65717. if (impostor.physicsBody) {
  65718. this.removePhysicsBody(impostor);
  65719. //TODO is that needed?
  65720. impostor.forceUpdate();
  65721. }
  65722. return;
  65723. }
  65724. //should a new body be created for this impostor?
  65725. if (impostor.isBodyInitRequired()) {
  65726. var shape = this._createShape(impostor);
  65727. //unregister events, if body is being changed
  65728. var oldBody = impostor.physicsBody;
  65729. if (oldBody) {
  65730. this.removePhysicsBody(impostor);
  65731. }
  65732. //create the body and material
  65733. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  65734. var bodyCreationObject = {
  65735. mass: impostor.getParam("mass"),
  65736. material: material
  65737. };
  65738. // A simple extend, in case native options were used.
  65739. var nativeOptions = impostor.getParam("nativeOptions");
  65740. for (var key in nativeOptions) {
  65741. if (nativeOptions.hasOwnProperty(key)) {
  65742. bodyCreationObject[key] = nativeOptions[key];
  65743. }
  65744. }
  65745. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  65746. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  65747. this.world.addEventListener("preStep", impostor.beforeStep);
  65748. this.world.addEventListener("postStep", impostor.afterStep);
  65749. impostor.physicsBody.addShape(shape);
  65750. this.world.add(impostor.physicsBody);
  65751. //try to keep the body moving in the right direction by taking old properties.
  65752. //Should be tested!
  65753. if (oldBody) {
  65754. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  65755. impostor.physicsBody[param].copy(oldBody[param]);
  65756. });
  65757. }
  65758. this._processChildMeshes(impostor);
  65759. }
  65760. //now update the body's transformation
  65761. this._updatePhysicsBodyTransformation(impostor);
  65762. };
  65763. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  65764. var _this = this;
  65765. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  65766. var currentRotation = mainImpostor.object.rotationQuaternion;
  65767. if (meshChildren.length) {
  65768. var processMesh = function (localPosition, mesh) {
  65769. if (!currentRotation || !mesh.rotationQuaternion) {
  65770. return;
  65771. }
  65772. var childImpostor = mesh.getPhysicsImpostor();
  65773. if (childImpostor) {
  65774. var parent = childImpostor.parent;
  65775. if (parent !== mainImpostor) {
  65776. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  65777. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  65778. if (childImpostor.physicsBody) {
  65779. _this.removePhysicsBody(childImpostor);
  65780. childImpostor.physicsBody = null;
  65781. }
  65782. childImpostor.parent = mainImpostor;
  65783. childImpostor.resetUpdateFlags();
  65784. 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));
  65785. //Add the mass of the children.
  65786. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  65787. }
  65788. }
  65789. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  65790. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  65791. };
  65792. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  65793. }
  65794. };
  65795. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  65796. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  65797. this.world.removeEventListener("preStep", impostor.beforeStep);
  65798. this.world.removeEventListener("postStep", impostor.afterStep);
  65799. this.world.remove(impostor.physicsBody);
  65800. };
  65801. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  65802. var mainBody = impostorJoint.mainImpostor.physicsBody;
  65803. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  65804. if (!mainBody || !connectedBody) {
  65805. return;
  65806. }
  65807. var constraint;
  65808. var jointData = impostorJoint.joint.jointData;
  65809. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  65810. var constraintData = {
  65811. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  65812. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  65813. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  65814. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  65815. maxForce: jointData.nativeParams.maxForce,
  65816. collideConnected: !!jointData.collision
  65817. };
  65818. switch (impostorJoint.joint.type) {
  65819. case BABYLON.PhysicsJoint.HingeJoint:
  65820. case BABYLON.PhysicsJoint.Hinge2Joint:
  65821. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  65822. break;
  65823. case BABYLON.PhysicsJoint.DistanceJoint:
  65824. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  65825. break;
  65826. case BABYLON.PhysicsJoint.SpringJoint:
  65827. var springData = jointData;
  65828. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  65829. restLength: springData.length,
  65830. stiffness: springData.stiffness,
  65831. damping: springData.damping,
  65832. localAnchorA: constraintData.pivotA,
  65833. localAnchorB: constraintData.pivotB
  65834. });
  65835. break;
  65836. case BABYLON.PhysicsJoint.LockJoint:
  65837. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  65838. break;
  65839. case BABYLON.PhysicsJoint.PointToPointJoint:
  65840. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  65841. default:
  65842. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  65843. break;
  65844. }
  65845. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  65846. constraint.collideConnected = !!jointData.collision;
  65847. impostorJoint.joint.physicsJoint = constraint;
  65848. //don't add spring as constraint, as it is not one.
  65849. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  65850. this.world.addConstraint(constraint);
  65851. }
  65852. else {
  65853. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  65854. constraint.applyForce();
  65855. });
  65856. }
  65857. };
  65858. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  65859. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  65860. };
  65861. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  65862. var index;
  65863. var mat;
  65864. for (index = 0; index < this._physicsMaterials.length; index++) {
  65865. mat = this._physicsMaterials[index];
  65866. if (mat.friction === friction && mat.restitution === restitution) {
  65867. return mat;
  65868. }
  65869. }
  65870. var currentMat = new this.BJSCANNON.Material(name);
  65871. currentMat.friction = friction;
  65872. currentMat.restitution = restitution;
  65873. this._physicsMaterials.push(currentMat);
  65874. return currentMat;
  65875. };
  65876. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  65877. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  65878. };
  65879. CannonJSPlugin.prototype._createShape = function (impostor) {
  65880. var object = impostor.object;
  65881. var returnValue;
  65882. var extendSize = impostor.getObjectExtendSize();
  65883. switch (impostor.type) {
  65884. case BABYLON.PhysicsImpostor.SphereImpostor:
  65885. var radiusX = extendSize.x;
  65886. var radiusY = extendSize.y;
  65887. var radiusZ = extendSize.z;
  65888. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  65889. break;
  65890. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  65891. case BABYLON.PhysicsImpostor.CylinderImpostor:
  65892. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  65893. break;
  65894. case BABYLON.PhysicsImpostor.BoxImpostor:
  65895. var box = extendSize.scale(0.5);
  65896. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  65897. break;
  65898. case BABYLON.PhysicsImpostor.PlaneImpostor:
  65899. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  65900. returnValue = new this.BJSCANNON.Plane();
  65901. break;
  65902. case BABYLON.PhysicsImpostor.MeshImpostor:
  65903. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  65904. var rawFaces = object.getIndices ? object.getIndices() : [];
  65905. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  65906. returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces);
  65907. break;
  65908. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  65909. returnValue = this._createHeightmap(object);
  65910. break;
  65911. case BABYLON.PhysicsImpostor.ParticleImpostor:
  65912. returnValue = new this.BJSCANNON.Particle();
  65913. break;
  65914. }
  65915. return returnValue;
  65916. };
  65917. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  65918. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  65919. var matrix = new Array();
  65920. //For now pointDepth will not be used and will be automatically calculated.
  65921. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  65922. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  65923. var boundingInfo = (object.getBoundingInfo());
  65924. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.z);
  65925. var minY = boundingInfo.boundingBox.extendSizeWorld.y;
  65926. var elementSize = dim * 2 / arraySize;
  65927. for (var i = 0; i < pos.length; i = i + 3) {
  65928. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  65929. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  65930. var y = pos[i + 1] + minY;
  65931. if (!matrix[x]) {
  65932. matrix[x] = [];
  65933. }
  65934. if (!matrix[x][z]) {
  65935. matrix[x][z] = y;
  65936. }
  65937. matrix[x][z] = Math.max(y, matrix[x][z]);
  65938. }
  65939. for (var x = 0; x <= arraySize; ++x) {
  65940. if (!matrix[x]) {
  65941. var loc = 1;
  65942. while (!matrix[(x + loc) % arraySize]) {
  65943. loc++;
  65944. }
  65945. matrix[x] = matrix[(x + loc) % arraySize].slice();
  65946. //console.log("missing x", x);
  65947. }
  65948. for (var z = 0; z <= arraySize; ++z) {
  65949. if (!matrix[x][z]) {
  65950. var loc = 1;
  65951. var newValue;
  65952. while (newValue === undefined) {
  65953. newValue = matrix[x][(z + loc++) % arraySize];
  65954. }
  65955. matrix[x][z] = newValue;
  65956. }
  65957. }
  65958. }
  65959. var shape = new this.BJSCANNON.Heightfield(matrix, {
  65960. elementSize: elementSize
  65961. });
  65962. //For future reference, needed for body transformation
  65963. shape.minY = minY;
  65964. return shape;
  65965. };
  65966. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  65967. var object = impostor.object;
  65968. //make sure it is updated...
  65969. object.computeWorldMatrix && object.computeWorldMatrix(true);
  65970. // The delta between the mesh position and the mesh bounding box center
  65971. var center = impostor.getObjectCenter();
  65972. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  65973. this._tmpPosition.copyFrom(center);
  65974. var quaternion = object.rotationQuaternion;
  65975. if (!quaternion) {
  65976. return;
  65977. }
  65978. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  65979. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  65980. //-90 DEG in X, precalculated
  65981. quaternion = quaternion.multiply(this._minus90X);
  65982. //Invert! (Precalculated, 90 deg in X)
  65983. //No need to clone. this will never change.
  65984. impostor.setDeltaRotation(this._plus90X);
  65985. }
  65986. //If it is a heightfield, if should be centered.
  65987. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  65988. var mesh = object;
  65989. var boundingInfo = mesh.getBoundingInfo();
  65990. //calculate the correct body position:
  65991. var rotationQuaternion = mesh.rotationQuaternion;
  65992. mesh.rotationQuaternion = this._tmpUnityRotation;
  65993. mesh.computeWorldMatrix(true);
  65994. //get original center with no rotation
  65995. var c = center.clone();
  65996. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  65997. //rotation is back
  65998. mesh.rotationQuaternion = rotationQuaternion;
  65999. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  66000. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  66001. mesh.setPivotMatrix(p);
  66002. mesh.computeWorldMatrix(true);
  66003. //calculate the translation
  66004. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  66005. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  66006. //add it inverted to the delta
  66007. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66008. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66009. mesh.setPivotMatrix(oldPivot);
  66010. mesh.computeWorldMatrix(true);
  66011. }
  66012. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66013. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66014. this._tmpPosition.copyFrom(object.position);
  66015. }
  66016. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66017. //Now update the impostor object
  66018. impostor.physicsBody.position.copy(this._tmpPosition);
  66019. impostor.physicsBody.quaternion.copy(quaternion);
  66020. };
  66021. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66022. impostor.object.position.copyFrom(impostor.physicsBody.position);
  66023. if (impostor.object.rotationQuaternion) {
  66024. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  66025. }
  66026. };
  66027. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66028. impostor.physicsBody.position.copy(newPosition);
  66029. impostor.physicsBody.quaternion.copy(newRotation);
  66030. };
  66031. CannonJSPlugin.prototype.isSupported = function () {
  66032. return this.BJSCANNON !== undefined;
  66033. };
  66034. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66035. impostor.physicsBody.velocity.copy(velocity);
  66036. };
  66037. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66038. impostor.physicsBody.angularVelocity.copy(velocity);
  66039. };
  66040. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66041. var v = impostor.physicsBody.velocity;
  66042. if (!v) {
  66043. return null;
  66044. }
  66045. return new BABYLON.Vector3(v.x, v.y, v.z);
  66046. };
  66047. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66048. var v = impostor.physicsBody.angularVelocity;
  66049. if (!v) {
  66050. return null;
  66051. }
  66052. return new BABYLON.Vector3(v.x, v.y, v.z);
  66053. };
  66054. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66055. impostor.physicsBody.mass = mass;
  66056. impostor.physicsBody.updateMassProperties();
  66057. };
  66058. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  66059. return impostor.physicsBody.mass;
  66060. };
  66061. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  66062. return impostor.physicsBody.material.friction;
  66063. };
  66064. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66065. impostor.physicsBody.material.friction = friction;
  66066. };
  66067. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66068. return impostor.physicsBody.material.restitution;
  66069. };
  66070. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66071. impostor.physicsBody.material.restitution = restitution;
  66072. };
  66073. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  66074. impostor.physicsBody.sleep();
  66075. };
  66076. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  66077. impostor.physicsBody.wakeUp();
  66078. };
  66079. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66080. joint.physicsJoint.distance = maxDistance;
  66081. };
  66082. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66083. // if (!motorIndex) {
  66084. // joint.physicsJoint.enableMotor();
  66085. // }
  66086. // }
  66087. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66088. // if (!motorIndex) {
  66089. // joint.physicsJoint.disableMotor();
  66090. // }
  66091. // }
  66092. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66093. if (!motorIndex) {
  66094. joint.physicsJoint.enableMotor();
  66095. joint.physicsJoint.setMotorSpeed(speed);
  66096. if (maxForce) {
  66097. this.setLimit(joint, maxForce);
  66098. }
  66099. }
  66100. };
  66101. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  66102. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  66103. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  66104. };
  66105. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66106. var body = impostor.physicsBody;
  66107. mesh.position.x = body.position.x;
  66108. mesh.position.y = body.position.y;
  66109. mesh.position.z = body.position.z;
  66110. if (mesh.rotationQuaternion) {
  66111. mesh.rotationQuaternion.x = body.quaternion.x;
  66112. mesh.rotationQuaternion.y = body.quaternion.y;
  66113. mesh.rotationQuaternion.z = body.quaternion.z;
  66114. mesh.rotationQuaternion.w = body.quaternion.w;
  66115. }
  66116. };
  66117. CannonJSPlugin.prototype.getRadius = function (impostor) {
  66118. var shape = impostor.physicsBody.shapes[0];
  66119. return shape.boundingSphereRadius;
  66120. };
  66121. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66122. var shape = impostor.physicsBody.shapes[0];
  66123. result.x = shape.halfExtents.x * 2;
  66124. result.y = shape.halfExtents.y * 2;
  66125. result.z = shape.halfExtents.z * 2;
  66126. };
  66127. CannonJSPlugin.prototype.dispose = function () {
  66128. };
  66129. return CannonJSPlugin;
  66130. }());
  66131. BABYLON.CannonJSPlugin = CannonJSPlugin;
  66132. })(BABYLON || (BABYLON = {}));
  66133. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  66134. var BABYLON;
  66135. (function (BABYLON) {
  66136. var OimoJSPlugin = /** @class */ (function () {
  66137. function OimoJSPlugin(iterations) {
  66138. this.name = "OimoJSPlugin";
  66139. this._tmpImpostorsArray = [];
  66140. this._tmpPositionVector = BABYLON.Vector3.Zero();
  66141. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  66142. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  66143. this.world.worldscale(1);
  66144. this.world.clear();
  66145. //making sure no stats are calculated
  66146. this.world.isNoStat = true;
  66147. }
  66148. OimoJSPlugin.prototype.setGravity = function (gravity) {
  66149. this.world.gravity.copy(gravity);
  66150. };
  66151. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  66152. this.world.timeStep = timeStep;
  66153. };
  66154. OimoJSPlugin.prototype.getTimeStep = function () {
  66155. return this.world.timeStep;
  66156. };
  66157. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  66158. var _this = this;
  66159. impostors.forEach(function (impostor) {
  66160. impostor.beforeStep();
  66161. });
  66162. this.world.step();
  66163. impostors.forEach(function (impostor) {
  66164. impostor.afterStep();
  66165. //update the ordered impostors array
  66166. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  66167. });
  66168. //check for collisions
  66169. var contact = this.world.contacts;
  66170. while (contact !== null) {
  66171. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  66172. contact = contact.next;
  66173. continue;
  66174. }
  66175. //is this body colliding with any other? get the impostor
  66176. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  66177. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  66178. if (!mainImpostor || !collidingImpostor) {
  66179. contact = contact.next;
  66180. continue;
  66181. }
  66182. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  66183. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  66184. contact = contact.next;
  66185. }
  66186. };
  66187. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66188. var mass = impostor.physicsBody.massInfo.mass;
  66189. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  66190. };
  66191. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66192. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  66193. this.applyImpulse(impostor, force, contactPoint);
  66194. };
  66195. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66196. var _this = this;
  66197. //parent-child relationship. Does this impostor has a parent impostor?
  66198. if (impostor.parent) {
  66199. if (impostor.physicsBody) {
  66200. this.removePhysicsBody(impostor);
  66201. //TODO is that needed?
  66202. impostor.forceUpdate();
  66203. }
  66204. return;
  66205. }
  66206. if (impostor.isBodyInitRequired()) {
  66207. var bodyConfig = {
  66208. name: impostor.uniqueId,
  66209. //Oimo must have mass, also for static objects.
  66210. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  66211. size: [],
  66212. type: [],
  66213. pos: [],
  66214. rot: [],
  66215. move: impostor.getParam("mass") !== 0,
  66216. //Supporting older versions of Oimo
  66217. world: this.world
  66218. };
  66219. var impostors = [impostor];
  66220. var addToArray = function (parent) {
  66221. if (!parent.getChildMeshes)
  66222. return;
  66223. parent.getChildMeshes().forEach(function (m) {
  66224. if (m.physicsImpostor) {
  66225. impostors.push(m.physicsImpostor);
  66226. //m.physicsImpostor._init();
  66227. }
  66228. });
  66229. };
  66230. addToArray(impostor.object);
  66231. var checkWithEpsilon_1 = function (value) {
  66232. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  66233. };
  66234. impostors.forEach(function (i) {
  66235. if (!impostor.object.rotationQuaternion) {
  66236. return;
  66237. }
  66238. //get the correct bounding box
  66239. var oldQuaternion = i.object.rotationQuaternion;
  66240. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  66241. x: impostor.object.rotationQuaternion.x,
  66242. y: impostor.object.rotationQuaternion.y,
  66243. z: impostor.object.rotationQuaternion.z,
  66244. s: impostor.object.rotationQuaternion.w
  66245. });
  66246. var extendSize = i.getObjectExtendSize();
  66247. if (i === impostor) {
  66248. var center = impostor.getObjectCenter();
  66249. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  66250. //Can also use Array.prototype.push.apply
  66251. bodyConfig.pos.push(center.x);
  66252. bodyConfig.pos.push(center.y);
  66253. bodyConfig.pos.push(center.z);
  66254. //tmp solution
  66255. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66256. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66257. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66258. }
  66259. else {
  66260. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  66261. bodyConfig.pos.push(localPosition.x);
  66262. bodyConfig.pos.push(localPosition.y);
  66263. bodyConfig.pos.push(localPosition.z);
  66264. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  66265. bodyConfig.rot.push(0);
  66266. bodyConfig.rot.push(0);
  66267. bodyConfig.rot.push(0);
  66268. }
  66269. // register mesh
  66270. switch (i.type) {
  66271. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66272. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  66273. case BABYLON.PhysicsImpostor.SphereImpostor:
  66274. var radiusX = extendSize.x;
  66275. var radiusY = extendSize.y;
  66276. var radiusZ = extendSize.z;
  66277. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  66278. bodyConfig.type.push('sphere');
  66279. //due to the way oimo works with compounds, add 3 times
  66280. bodyConfig.size.push(size);
  66281. bodyConfig.size.push(size);
  66282. bodyConfig.size.push(size);
  66283. break;
  66284. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66285. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  66286. var sizeY = checkWithEpsilon_1(extendSize.y);
  66287. bodyConfig.type.push('cylinder');
  66288. bodyConfig.size.push(sizeX);
  66289. bodyConfig.size.push(sizeY);
  66290. //due to the way oimo works with compounds, add one more value.
  66291. bodyConfig.size.push(sizeY);
  66292. break;
  66293. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66294. case BABYLON.PhysicsImpostor.BoxImpostor:
  66295. default:
  66296. var sizeX = checkWithEpsilon_1(extendSize.x);
  66297. var sizeY = checkWithEpsilon_1(extendSize.y);
  66298. var sizeZ = checkWithEpsilon_1(extendSize.z);
  66299. bodyConfig.type.push('box');
  66300. bodyConfig.size.push(sizeX);
  66301. bodyConfig.size.push(sizeY);
  66302. bodyConfig.size.push(sizeZ);
  66303. break;
  66304. }
  66305. //actually not needed, but hey...
  66306. i.object.rotationQuaternion = oldQuaternion;
  66307. });
  66308. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  66309. }
  66310. else {
  66311. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  66312. }
  66313. impostor.setDeltaPosition(this._tmpPositionVector);
  66314. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  66315. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  66316. };
  66317. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66318. //impostor.physicsBody.dispose();
  66319. //Same as : (older oimo versions)
  66320. this.world.removeRigidBody(impostor.physicsBody);
  66321. };
  66322. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66323. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66324. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66325. if (!mainBody || !connectedBody) {
  66326. return;
  66327. }
  66328. var jointData = impostorJoint.joint.jointData;
  66329. var options = jointData.nativeParams || {};
  66330. var type;
  66331. var nativeJointData = {
  66332. body1: mainBody,
  66333. body2: connectedBody,
  66334. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  66335. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  66336. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  66337. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  66338. min: options.min,
  66339. max: options.max,
  66340. collision: options.collision || jointData.collision,
  66341. spring: options.spring,
  66342. //supporting older version of Oimo
  66343. world: this.world
  66344. };
  66345. switch (impostorJoint.joint.type) {
  66346. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66347. type = "jointBall";
  66348. break;
  66349. case BABYLON.PhysicsJoint.SpringJoint:
  66350. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  66351. var springData = jointData;
  66352. nativeJointData.min = springData.length || nativeJointData.min;
  66353. //Max should also be set, just make sure it is at least min
  66354. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  66355. case BABYLON.PhysicsJoint.DistanceJoint:
  66356. type = "jointDistance";
  66357. nativeJointData.max = jointData.maxDistance;
  66358. break;
  66359. case BABYLON.PhysicsJoint.PrismaticJoint:
  66360. type = "jointPrisme";
  66361. break;
  66362. case BABYLON.PhysicsJoint.SliderJoint:
  66363. type = "jointSlide";
  66364. break;
  66365. case BABYLON.PhysicsJoint.WheelJoint:
  66366. type = "jointWheel";
  66367. break;
  66368. case BABYLON.PhysicsJoint.HingeJoint:
  66369. default:
  66370. type = "jointHinge";
  66371. break;
  66372. }
  66373. nativeJointData.type = type;
  66374. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  66375. };
  66376. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66377. //Bug in Oimo prevents us from disposing a joint in the playground
  66378. //joint.joint.physicsJoint.dispose();
  66379. //So we will bruteforce it!
  66380. try {
  66381. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  66382. }
  66383. catch (e) {
  66384. BABYLON.Tools.Warn(e);
  66385. }
  66386. };
  66387. OimoJSPlugin.prototype.isSupported = function () {
  66388. return this.BJSOIMO !== undefined;
  66389. };
  66390. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66391. if (!impostor.physicsBody.sleeping) {
  66392. //TODO check that
  66393. if (impostor.physicsBody.shapes.next) {
  66394. var parentShape = this._getLastShape(impostor.physicsBody);
  66395. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  66396. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  66397. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  66398. }
  66399. else {
  66400. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  66401. }
  66402. if (impostor.object.rotationQuaternion) {
  66403. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  66404. impostor.object.rotationQuaternion.normalize();
  66405. }
  66406. }
  66407. };
  66408. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66409. var body = impostor.physicsBody;
  66410. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  66411. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  66412. body.syncShapes();
  66413. body.awake();
  66414. };
  66415. OimoJSPlugin.prototype._getLastShape = function (body) {
  66416. var lastShape = body.shapes;
  66417. while (lastShape.next) {
  66418. lastShape = lastShape.next;
  66419. }
  66420. return lastShape;
  66421. };
  66422. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66423. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  66424. };
  66425. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66426. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  66427. };
  66428. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66429. var v = impostor.physicsBody.linearVelocity;
  66430. if (!v) {
  66431. return null;
  66432. }
  66433. return new BABYLON.Vector3(v.x, v.y, v.z);
  66434. };
  66435. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66436. var v = impostor.physicsBody.angularVelocity;
  66437. if (!v) {
  66438. return null;
  66439. }
  66440. return new BABYLON.Vector3(v.x, v.y, v.z);
  66441. };
  66442. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66443. var staticBody = mass === 0;
  66444. //this will actually set the body's density and not its mass.
  66445. //But this is how oimo treats the mass variable.
  66446. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  66447. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  66448. };
  66449. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  66450. return impostor.physicsBody.shapes.density;
  66451. };
  66452. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  66453. return impostor.physicsBody.shapes.friction;
  66454. };
  66455. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66456. impostor.physicsBody.shapes.friction = friction;
  66457. };
  66458. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66459. return impostor.physicsBody.shapes.restitution;
  66460. };
  66461. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66462. impostor.physicsBody.shapes.restitution = restitution;
  66463. };
  66464. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  66465. impostor.physicsBody.sleep();
  66466. };
  66467. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  66468. impostor.physicsBody.awake();
  66469. };
  66470. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66471. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  66472. if (minDistance !== void 0) {
  66473. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  66474. }
  66475. };
  66476. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66477. //TODO separate rotational and transational motors.
  66478. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66479. if (motor) {
  66480. motor.setMotor(speed, maxForce);
  66481. }
  66482. };
  66483. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  66484. //TODO separate rotational and transational motors.
  66485. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66486. if (motor) {
  66487. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  66488. }
  66489. };
  66490. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66491. var body = impostor.physicsBody;
  66492. mesh.position.x = body.position.x;
  66493. mesh.position.y = body.position.y;
  66494. mesh.position.z = body.position.z;
  66495. if (mesh.rotationQuaternion) {
  66496. mesh.rotationQuaternion.x = body.orientation.x;
  66497. mesh.rotationQuaternion.y = body.orientation.y;
  66498. mesh.rotationQuaternion.z = body.orientation.z;
  66499. mesh.rotationQuaternion.w = body.orientation.s;
  66500. }
  66501. };
  66502. OimoJSPlugin.prototype.getRadius = function (impostor) {
  66503. return impostor.physicsBody.shapes.radius;
  66504. };
  66505. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66506. var shape = impostor.physicsBody.shapes;
  66507. result.x = shape.halfWidth * 2;
  66508. result.y = shape.halfHeight * 2;
  66509. result.z = shape.halfDepth * 2;
  66510. };
  66511. OimoJSPlugin.prototype.dispose = function () {
  66512. this.world.clear();
  66513. };
  66514. return OimoJSPlugin;
  66515. }());
  66516. BABYLON.OimoJSPlugin = OimoJSPlugin;
  66517. })(BABYLON || (BABYLON = {}));
  66518. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  66519. var BABYLON;
  66520. (function (BABYLON) {
  66521. var Internals;
  66522. (function (Internals) {
  66523. /*
  66524. * Based on jsTGALoader - Javascript loader for TGA file
  66525. * By Vincent Thibault
  66526. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  66527. */
  66528. var TGATools = /** @class */ (function () {
  66529. function TGATools() {
  66530. }
  66531. TGATools.GetTGAHeader = function (data) {
  66532. var offset = 0;
  66533. var header = {
  66534. id_length: data[offset++],
  66535. colormap_type: data[offset++],
  66536. image_type: data[offset++],
  66537. colormap_index: data[offset++] | data[offset++] << 8,
  66538. colormap_length: data[offset++] | data[offset++] << 8,
  66539. colormap_size: data[offset++],
  66540. origin: [
  66541. data[offset++] | data[offset++] << 8,
  66542. data[offset++] | data[offset++] << 8
  66543. ],
  66544. width: data[offset++] | data[offset++] << 8,
  66545. height: data[offset++] | data[offset++] << 8,
  66546. pixel_size: data[offset++],
  66547. flags: data[offset++]
  66548. };
  66549. return header;
  66550. };
  66551. TGATools.UploadContent = function (gl, data) {
  66552. // Not enough data to contain header ?
  66553. if (data.length < 19) {
  66554. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  66555. return;
  66556. }
  66557. // Read Header
  66558. var offset = 18;
  66559. var header = TGATools.GetTGAHeader(data);
  66560. // Assume it's a valid Targa file.
  66561. if (header.id_length + offset > data.length) {
  66562. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  66563. return;
  66564. }
  66565. // Skip not needed data
  66566. offset += header.id_length;
  66567. var use_rle = false;
  66568. var use_pal = false;
  66569. var use_rgb = false;
  66570. var use_grey = false;
  66571. // Get some informations.
  66572. switch (header.image_type) {
  66573. case TGATools._TYPE_RLE_INDEXED:
  66574. use_rle = true;
  66575. case TGATools._TYPE_INDEXED:
  66576. use_pal = true;
  66577. break;
  66578. case TGATools._TYPE_RLE_RGB:
  66579. use_rle = true;
  66580. case TGATools._TYPE_RGB:
  66581. use_rgb = true;
  66582. break;
  66583. case TGATools._TYPE_RLE_GREY:
  66584. use_rle = true;
  66585. case TGATools._TYPE_GREY:
  66586. use_grey = true;
  66587. break;
  66588. }
  66589. var pixel_data;
  66590. // var numAlphaBits = header.flags & 0xf;
  66591. var pixel_size = header.pixel_size >> 3;
  66592. var pixel_total = header.width * header.height * pixel_size;
  66593. // Read palettes
  66594. var palettes;
  66595. if (use_pal) {
  66596. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  66597. }
  66598. // Read LRE
  66599. if (use_rle) {
  66600. pixel_data = new Uint8Array(pixel_total);
  66601. var c, count, i;
  66602. var localOffset = 0;
  66603. var pixels = new Uint8Array(pixel_size);
  66604. while (offset < pixel_total && localOffset < pixel_total) {
  66605. c = data[offset++];
  66606. count = (c & 0x7f) + 1;
  66607. // RLE pixels
  66608. if (c & 0x80) {
  66609. // Bind pixel tmp array
  66610. for (i = 0; i < pixel_size; ++i) {
  66611. pixels[i] = data[offset++];
  66612. }
  66613. // Copy pixel array
  66614. for (i = 0; i < count; ++i) {
  66615. pixel_data.set(pixels, localOffset + i * pixel_size);
  66616. }
  66617. localOffset += pixel_size * count;
  66618. }
  66619. else {
  66620. count *= pixel_size;
  66621. for (i = 0; i < count; ++i) {
  66622. pixel_data[localOffset + i] = data[offset++];
  66623. }
  66624. localOffset += count;
  66625. }
  66626. }
  66627. }
  66628. else {
  66629. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  66630. }
  66631. // Load to texture
  66632. var x_start, y_start, x_step, y_step, y_end, x_end;
  66633. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  66634. default:
  66635. case TGATools._ORIGIN_UL:
  66636. x_start = 0;
  66637. x_step = 1;
  66638. x_end = header.width;
  66639. y_start = 0;
  66640. y_step = 1;
  66641. y_end = header.height;
  66642. break;
  66643. case TGATools._ORIGIN_BL:
  66644. x_start = 0;
  66645. x_step = 1;
  66646. x_end = header.width;
  66647. y_start = header.height - 1;
  66648. y_step = -1;
  66649. y_end = -1;
  66650. break;
  66651. case TGATools._ORIGIN_UR:
  66652. x_start = header.width - 1;
  66653. x_step = -1;
  66654. x_end = -1;
  66655. y_start = 0;
  66656. y_step = 1;
  66657. y_end = header.height;
  66658. break;
  66659. case TGATools._ORIGIN_BR:
  66660. x_start = header.width - 1;
  66661. x_step = -1;
  66662. x_end = -1;
  66663. y_start = header.height - 1;
  66664. y_step = -1;
  66665. y_end = -1;
  66666. break;
  66667. }
  66668. // Load the specify method
  66669. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  66670. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  66671. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  66672. };
  66673. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66674. var image = pixel_data, colormap = palettes;
  66675. var width = header.width, height = header.height;
  66676. var color, i = 0, x, y;
  66677. var imageData = new Uint8Array(width * height * 4);
  66678. for (y = y_start; y !== y_end; y += y_step) {
  66679. for (x = x_start; x !== x_end; x += x_step, i++) {
  66680. color = image[i];
  66681. imageData[(x + width * y) * 4 + 3] = 255;
  66682. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  66683. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  66684. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  66685. }
  66686. }
  66687. return imageData;
  66688. };
  66689. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66690. var image = pixel_data;
  66691. var width = header.width, height = header.height;
  66692. var color, i = 0, x, y;
  66693. var imageData = new Uint8Array(width * height * 4);
  66694. for (y = y_start; y !== y_end; y += y_step) {
  66695. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66696. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  66697. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  66698. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  66699. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  66700. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  66701. }
  66702. }
  66703. return imageData;
  66704. };
  66705. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66706. var image = pixel_data;
  66707. var width = header.width, height = header.height;
  66708. var i = 0, x, y;
  66709. var imageData = new Uint8Array(width * height * 4);
  66710. for (y = y_start; y !== y_end; y += y_step) {
  66711. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  66712. imageData[(x + width * y) * 4 + 3] = 255;
  66713. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66714. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66715. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66716. }
  66717. }
  66718. return imageData;
  66719. };
  66720. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66721. var image = pixel_data;
  66722. var width = header.width, height = header.height;
  66723. var i = 0, x, y;
  66724. var imageData = new Uint8Array(width * height * 4);
  66725. for (y = y_start; y !== y_end; y += y_step) {
  66726. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  66727. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66728. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66729. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66730. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  66731. }
  66732. }
  66733. return imageData;
  66734. };
  66735. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66736. var image = pixel_data;
  66737. var width = header.width, height = header.height;
  66738. var color, i = 0, x, y;
  66739. var imageData = new Uint8Array(width * height * 4);
  66740. for (y = y_start; y !== y_end; y += y_step) {
  66741. for (x = x_start; x !== x_end; x += x_step, i++) {
  66742. color = image[i];
  66743. imageData[(x + width * y) * 4 + 0] = color;
  66744. imageData[(x + width * y) * 4 + 1] = color;
  66745. imageData[(x + width * y) * 4 + 2] = color;
  66746. imageData[(x + width * y) * 4 + 3] = 255;
  66747. }
  66748. }
  66749. return imageData;
  66750. };
  66751. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66752. var image = pixel_data;
  66753. var width = header.width, height = header.height;
  66754. var i = 0, x, y;
  66755. var imageData = new Uint8Array(width * height * 4);
  66756. for (y = y_start; y !== y_end; y += y_step) {
  66757. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66758. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  66759. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  66760. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66761. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  66762. }
  66763. }
  66764. return imageData;
  66765. };
  66766. //private static _TYPE_NO_DATA = 0;
  66767. TGATools._TYPE_INDEXED = 1;
  66768. TGATools._TYPE_RGB = 2;
  66769. TGATools._TYPE_GREY = 3;
  66770. TGATools._TYPE_RLE_INDEXED = 9;
  66771. TGATools._TYPE_RLE_RGB = 10;
  66772. TGATools._TYPE_RLE_GREY = 11;
  66773. TGATools._ORIGIN_MASK = 0x30;
  66774. TGATools._ORIGIN_SHIFT = 0x04;
  66775. TGATools._ORIGIN_BL = 0x00;
  66776. TGATools._ORIGIN_BR = 0x01;
  66777. TGATools._ORIGIN_UL = 0x02;
  66778. TGATools._ORIGIN_UR = 0x03;
  66779. return TGATools;
  66780. }());
  66781. Internals.TGATools = TGATools;
  66782. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66783. })(BABYLON || (BABYLON = {}));
  66784. //# sourceMappingURL=babylon.tga.js.map
  66785. var BABYLON;
  66786. (function (BABYLON) {
  66787. var Internals;
  66788. (function (Internals) {
  66789. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  66790. // All values and structures referenced from:
  66791. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  66792. var DDS_MAGIC = 0x20534444;
  66793. var
  66794. //DDSD_CAPS = 0x1,
  66795. //DDSD_HEIGHT = 0x2,
  66796. //DDSD_WIDTH = 0x4,
  66797. //DDSD_PITCH = 0x8,
  66798. //DDSD_PIXELFORMAT = 0x1000,
  66799. DDSD_MIPMAPCOUNT = 0x20000;
  66800. //DDSD_LINEARSIZE = 0x80000,
  66801. //DDSD_DEPTH = 0x800000;
  66802. // var DDSCAPS_COMPLEX = 0x8,
  66803. // DDSCAPS_MIPMAP = 0x400000,
  66804. // DDSCAPS_TEXTURE = 0x1000;
  66805. var DDSCAPS2_CUBEMAP = 0x200;
  66806. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  66807. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  66808. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  66809. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  66810. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  66811. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  66812. // DDSCAPS2_VOLUME = 0x200000;
  66813. var
  66814. //DDPF_ALPHAPIXELS = 0x1,
  66815. //DDPF_ALPHA = 0x2,
  66816. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  66817. //DDPF_YUV = 0x200,
  66818. DDPF_LUMINANCE = 0x20000;
  66819. function FourCCToInt32(value) {
  66820. return value.charCodeAt(0) +
  66821. (value.charCodeAt(1) << 8) +
  66822. (value.charCodeAt(2) << 16) +
  66823. (value.charCodeAt(3) << 24);
  66824. }
  66825. function Int32ToFourCC(value) {
  66826. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  66827. }
  66828. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  66829. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  66830. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  66831. var FOURCC_DX10 = FourCCToInt32("DX10");
  66832. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  66833. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  66834. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  66835. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  66836. var headerLengthInt = 31; // The header length in 32 bit ints
  66837. // Offsets into the header array
  66838. var off_magic = 0;
  66839. var off_size = 1;
  66840. var off_flags = 2;
  66841. var off_height = 3;
  66842. var off_width = 4;
  66843. var off_mipmapCount = 7;
  66844. var off_pfFlags = 20;
  66845. var off_pfFourCC = 21;
  66846. var off_RGBbpp = 22;
  66847. // var off_RMask = 23;
  66848. // var off_GMask = 24;
  66849. // var off_BMask = 25;
  66850. // var off_AMask = 26;
  66851. // var off_caps1 = 27;
  66852. var off_caps2 = 28;
  66853. // var off_caps3 = 29;
  66854. // var off_caps4 = 30;
  66855. var off_dxgiFormat = 32;
  66856. ;
  66857. var DDSTools = /** @class */ (function () {
  66858. function DDSTools() {
  66859. }
  66860. DDSTools.GetDDSInfo = function (arrayBuffer) {
  66861. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  66862. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  66863. var mipmapCount = 1;
  66864. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  66865. mipmapCount = Math.max(1, header[off_mipmapCount]);
  66866. }
  66867. var fourCC = header[off_pfFourCC];
  66868. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  66869. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66870. switch (fourCC) {
  66871. case FOURCC_D3DFMT_R16G16B16A16F:
  66872. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66873. break;
  66874. case FOURCC_D3DFMT_R32G32B32A32F:
  66875. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66876. break;
  66877. case FOURCC_DX10:
  66878. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  66879. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66880. break;
  66881. }
  66882. }
  66883. return {
  66884. width: header[off_width],
  66885. height: header[off_height],
  66886. mipmapCount: mipmapCount,
  66887. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  66888. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  66889. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  66890. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  66891. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  66892. dxgiFormat: dxgiFormat,
  66893. textureType: textureType
  66894. };
  66895. };
  66896. DDSTools._ToHalfFloat = function (value) {
  66897. if (!DDSTools._FloatView) {
  66898. DDSTools._FloatView = new Float32Array(1);
  66899. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  66900. }
  66901. DDSTools._FloatView[0] = value;
  66902. var x = DDSTools._Int32View[0];
  66903. var bits = (x >> 16) & 0x8000; /* Get the sign */
  66904. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  66905. var e = (x >> 23) & 0xff; /* Using int is faster here */
  66906. /* If zero, or denormal, or exponent underflows too much for a denormal
  66907. * half, return signed zero. */
  66908. if (e < 103) {
  66909. return bits;
  66910. }
  66911. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  66912. if (e > 142) {
  66913. bits |= 0x7c00;
  66914. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  66915. * not Inf, so make sure we set one mantissa bit too. */
  66916. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  66917. return bits;
  66918. }
  66919. /* If exponent underflows but not too much, return a denormal */
  66920. if (e < 113) {
  66921. m |= 0x0800;
  66922. /* Extra rounding may overflow and set mantissa to 0 and exponent
  66923. * to 1, which is OK. */
  66924. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  66925. return bits;
  66926. }
  66927. bits |= ((e - 112) << 10) | (m >> 1);
  66928. bits += m & 1;
  66929. return bits;
  66930. };
  66931. DDSTools._FromHalfFloat = function (value) {
  66932. var s = (value & 0x8000) >> 15;
  66933. var e = (value & 0x7C00) >> 10;
  66934. var f = value & 0x03FF;
  66935. if (e === 0) {
  66936. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  66937. }
  66938. else if (e == 0x1F) {
  66939. return f ? NaN : ((s ? -1 : 1) * Infinity);
  66940. }
  66941. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  66942. };
  66943. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66944. var destArray = new Float32Array(dataLength);
  66945. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  66946. var index = 0;
  66947. for (var y = 0; y < height; y++) {
  66948. for (var x = 0; x < width; x++) {
  66949. var srcPos = (x + y * width) * 4;
  66950. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  66951. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  66952. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  66953. if (DDSTools.StoreLODInAlphaChannel) {
  66954. destArray[index + 3] = lod;
  66955. }
  66956. else {
  66957. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  66958. }
  66959. index += 4;
  66960. }
  66961. }
  66962. return destArray;
  66963. };
  66964. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66965. if (DDSTools.StoreLODInAlphaChannel) {
  66966. var destArray = new Uint16Array(dataLength);
  66967. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  66968. var index = 0;
  66969. for (var y = 0; y < height; y++) {
  66970. for (var x = 0; x < width; x++) {
  66971. var srcPos = (x + y * width) * 4;
  66972. destArray[index] = srcData[srcPos];
  66973. destArray[index + 1] = srcData[srcPos + 1];
  66974. destArray[index + 2] = srcData[srcPos + 2];
  66975. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  66976. index += 4;
  66977. }
  66978. }
  66979. return destArray;
  66980. }
  66981. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  66982. };
  66983. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66984. if (DDSTools.StoreLODInAlphaChannel) {
  66985. var destArray = new Float32Array(dataLength);
  66986. var srcData = new Float32Array(arrayBuffer, dataOffset);
  66987. var index = 0;
  66988. for (var y = 0; y < height; y++) {
  66989. for (var x = 0; x < width; x++) {
  66990. var srcPos = (x + y * width) * 4;
  66991. destArray[index] = srcData[srcPos];
  66992. destArray[index + 1] = srcData[srcPos + 1];
  66993. destArray[index + 2] = srcData[srcPos + 2];
  66994. destArray[index + 3] = lod;
  66995. index += 4;
  66996. }
  66997. }
  66998. return destArray;
  66999. }
  67000. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  67001. };
  67002. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67003. var destArray = new Uint8Array(dataLength);
  67004. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67005. var index = 0;
  67006. for (var y = 0; y < height; y++) {
  67007. for (var x = 0; x < width; x++) {
  67008. var srcPos = (x + y * width) * 4;
  67009. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67010. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67011. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67012. if (DDSTools.StoreLODInAlphaChannel) {
  67013. destArray[index + 3] = lod;
  67014. }
  67015. else {
  67016. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67017. }
  67018. index += 4;
  67019. }
  67020. }
  67021. return destArray;
  67022. };
  67023. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67024. var destArray = new Uint8Array(dataLength);
  67025. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67026. var index = 0;
  67027. for (var y = 0; y < height; y++) {
  67028. for (var x = 0; x < width; x++) {
  67029. var srcPos = (x + y * width) * 4;
  67030. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  67031. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  67032. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  67033. if (DDSTools.StoreLODInAlphaChannel) {
  67034. destArray[index + 3] = lod;
  67035. }
  67036. else {
  67037. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  67038. }
  67039. index += 4;
  67040. }
  67041. }
  67042. return destArray;
  67043. };
  67044. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67045. var byteArray = new Uint8Array(dataLength);
  67046. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67047. var index = 0;
  67048. for (var y = 0; y < height; y++) {
  67049. for (var x = 0; x < width; x++) {
  67050. var srcPos = (x + y * width) * 4;
  67051. byteArray[index] = srcData[srcPos + 2];
  67052. byteArray[index + 1] = srcData[srcPos + 1];
  67053. byteArray[index + 2] = srcData[srcPos];
  67054. byteArray[index + 3] = srcData[srcPos + 3];
  67055. index += 4;
  67056. }
  67057. }
  67058. return byteArray;
  67059. };
  67060. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67061. var byteArray = new Uint8Array(dataLength);
  67062. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67063. var index = 0;
  67064. for (var y = 0; y < height; y++) {
  67065. for (var x = 0; x < width; x++) {
  67066. var srcPos = (x + y * width) * 3;
  67067. byteArray[index] = srcData[srcPos + 2];
  67068. byteArray[index + 1] = srcData[srcPos + 1];
  67069. byteArray[index + 2] = srcData[srcPos];
  67070. index += 3;
  67071. }
  67072. }
  67073. return byteArray;
  67074. };
  67075. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67076. var byteArray = new Uint8Array(dataLength);
  67077. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67078. var index = 0;
  67079. for (var y = 0; y < height; y++) {
  67080. for (var x = 0; x < width; x++) {
  67081. var srcPos = (x + y * width);
  67082. byteArray[index] = srcData[srcPos];
  67083. index++;
  67084. }
  67085. }
  67086. return byteArray;
  67087. };
  67088. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  67089. if (lodIndex === void 0) { lodIndex = -1; }
  67090. var ext = engine.getCaps().s3tc;
  67091. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  67092. var internalFormat = 0;
  67093. var format = 0;
  67094. var blockBytes = 1;
  67095. if (header[off_magic] != DDS_MAGIC) {
  67096. BABYLON.Tools.Error("Invalid magic number in DDS header");
  67097. return;
  67098. }
  67099. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  67100. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  67101. return;
  67102. }
  67103. if (info.isCompressed && !ext) {
  67104. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  67105. return;
  67106. }
  67107. var bpp = header[off_RGBbpp];
  67108. dataOffset = header[off_size] + 4;
  67109. var computeFormats = false;
  67110. if (info.isFourCC) {
  67111. fourCC = header[off_pfFourCC];
  67112. switch (fourCC) {
  67113. case FOURCC_DXT1:
  67114. blockBytes = 8;
  67115. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  67116. break;
  67117. case FOURCC_DXT3:
  67118. blockBytes = 16;
  67119. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  67120. break;
  67121. case FOURCC_DXT5:
  67122. blockBytes = 16;
  67123. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  67124. break;
  67125. case FOURCC_D3DFMT_R16G16B16A16F:
  67126. computeFormats = true;
  67127. break;
  67128. case FOURCC_D3DFMT_R32G32B32A32F:
  67129. computeFormats = true;
  67130. break;
  67131. case FOURCC_DX10:
  67132. // There is an additionnal header so dataOffset need to be changed
  67133. dataOffset += 5 * 4; // 5 uints
  67134. var supported = false;
  67135. switch (info.dxgiFormat) {
  67136. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  67137. computeFormats = true;
  67138. supported = true;
  67139. break;
  67140. case DXGI_FORMAT_B8G8R8X8_UNORM:
  67141. info.isRGB = true;
  67142. info.isFourCC = false;
  67143. bpp = 32;
  67144. supported = true;
  67145. break;
  67146. }
  67147. if (supported) {
  67148. break;
  67149. }
  67150. default:
  67151. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  67152. return;
  67153. }
  67154. }
  67155. if (computeFormats) {
  67156. format = engine._getWebGLTextureType(info.textureType);
  67157. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67158. }
  67159. mipmapCount = 1;
  67160. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  67161. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67162. }
  67163. for (var face = 0; face < faces; face++) {
  67164. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67165. width = header[off_width];
  67166. height = header[off_height];
  67167. for (mip = 0; mip < mipmapCount; ++mip) {
  67168. if (lodIndex === -1 || lodIndex === mip) {
  67169. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  67170. var i = (lodIndex === -1) ? mip : 0;
  67171. if (!info.isCompressed && info.isFourCC) {
  67172. dataLength = width * height * 4;
  67173. var FloatArray = null;
  67174. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  67175. if (bpp === 128) {
  67176. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67177. }
  67178. else if (bpp === 64) {
  67179. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67180. }
  67181. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67182. format = engine._getWebGLTextureType(info.textureType);
  67183. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67184. }
  67185. else {
  67186. if (bpp === 128) {
  67187. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67188. }
  67189. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  67190. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67191. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67192. format = engine._getWebGLTextureType(info.textureType);
  67193. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67194. }
  67195. else {
  67196. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67197. }
  67198. }
  67199. if (FloatArray) {
  67200. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  67201. }
  67202. }
  67203. else if (info.isRGB) {
  67204. if (bpp === 24) {
  67205. dataLength = width * height * 3;
  67206. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67207. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  67208. }
  67209. else {
  67210. dataLength = width * height * 4;
  67211. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67212. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  67213. }
  67214. }
  67215. else if (info.isLuminance) {
  67216. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  67217. var unpaddedRowSize = width;
  67218. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  67219. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  67220. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67221. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  67222. }
  67223. else {
  67224. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  67225. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  67226. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  67227. }
  67228. }
  67229. dataOffset += width * height * (bpp / 8);
  67230. width *= 0.5;
  67231. height *= 0.5;
  67232. width = Math.max(1.0, width);
  67233. height = Math.max(1.0, height);
  67234. }
  67235. }
  67236. };
  67237. DDSTools.StoreLODInAlphaChannel = false;
  67238. return DDSTools;
  67239. }());
  67240. Internals.DDSTools = DDSTools;
  67241. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67242. })(BABYLON || (BABYLON = {}));
  67243. //# sourceMappingURL=babylon.dds.js.map
  67244. var BABYLON;
  67245. (function (BABYLON) {
  67246. var Internals;
  67247. (function (Internals) {
  67248. /**
  67249. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  67250. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  67251. */
  67252. var KhronosTextureContainer = /** @class */ (function () {
  67253. /**
  67254. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  67255. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  67256. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  67257. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  67258. */
  67259. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  67260. this.arrayBuffer = arrayBuffer;
  67261. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  67262. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  67263. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  67264. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  67265. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  67266. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  67267. BABYLON.Tools.Error("texture missing KTX identifier");
  67268. return;
  67269. }
  67270. // load the reset of the header in native 32 bit int
  67271. var header = new Int32Array(this.arrayBuffer, 12, 13);
  67272. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  67273. var oppositeEndianess = header[0] === 0x01020304;
  67274. // read all the header elements in order they exist in the file, without modification (sans endainness)
  67275. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  67276. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  67277. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  67278. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  67279. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  67280. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  67281. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  67282. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  67283. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  67284. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  67285. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  67286. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  67287. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  67288. if (this.glType !== 0) {
  67289. BABYLON.Tools.Error("only compressed formats currently supported");
  67290. return;
  67291. }
  67292. else {
  67293. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  67294. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  67295. }
  67296. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  67297. BABYLON.Tools.Error("only 2D textures currently supported");
  67298. return;
  67299. }
  67300. if (this.numberOfArrayElements !== 0) {
  67301. BABYLON.Tools.Error("texture arrays not currently supported");
  67302. return;
  67303. }
  67304. if (this.numberOfFaces !== facesExpected) {
  67305. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  67306. return;
  67307. }
  67308. // we now have a completely validated file, so could use existence of loadType as success
  67309. // would need to make this more elaborate & adjust checks above to support more than one load type
  67310. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  67311. }
  67312. // not as fast hardware based, but will probably never need to use
  67313. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  67314. return ((val & 0xFF) << 24)
  67315. | ((val & 0xFF00) << 8)
  67316. | ((val >> 8) & 0xFF00)
  67317. | ((val >> 24) & 0xFF);
  67318. };
  67319. /**
  67320. * It is assumed that the texture has already been created & is currently bound
  67321. */
  67322. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  67323. switch (this.loadType) {
  67324. case KhronosTextureContainer.COMPRESSED_2D:
  67325. this._upload2DCompressedLevels(gl, loadMipmaps);
  67326. break;
  67327. case KhronosTextureContainer.TEX_2D:
  67328. case KhronosTextureContainer.COMPRESSED_3D:
  67329. case KhronosTextureContainer.TEX_3D:
  67330. }
  67331. };
  67332. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  67333. // initialize width & height for level 1
  67334. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  67335. var width = this.pixelWidth;
  67336. var height = this.pixelHeight;
  67337. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  67338. for (var level = 0; level < mipmapCount; level++) {
  67339. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  67340. for (var face = 0; face < this.numberOfFaces; face++) {
  67341. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67342. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  67343. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  67344. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  67345. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  67346. }
  67347. width = Math.max(1.0, width * 0.5);
  67348. height = Math.max(1.0, height * 0.5);
  67349. }
  67350. };
  67351. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  67352. // load types
  67353. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  67354. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  67355. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  67356. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  67357. return KhronosTextureContainer;
  67358. }());
  67359. Internals.KhronosTextureContainer = KhronosTextureContainer;
  67360. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67361. })(BABYLON || (BABYLON = {}));
  67362. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  67363. var BABYLON;
  67364. (function (BABYLON) {
  67365. var Debug;
  67366. (function (Debug) {
  67367. /**
  67368. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  67369. */
  67370. var SkeletonViewer = /** @class */ (function () {
  67371. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  67372. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  67373. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  67374. this.skeleton = skeleton;
  67375. this.mesh = mesh;
  67376. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  67377. this.renderingGroupId = renderingGroupId;
  67378. this.color = BABYLON.Color3.White();
  67379. this._debugLines = new Array();
  67380. this._isEnabled = false;
  67381. this._scene = scene;
  67382. this.update();
  67383. this._renderFunction = this.update.bind(this);
  67384. }
  67385. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  67386. get: function () {
  67387. return this._isEnabled;
  67388. },
  67389. set: function (value) {
  67390. if (this._isEnabled === value) {
  67391. return;
  67392. }
  67393. this._isEnabled = value;
  67394. if (value) {
  67395. this._scene.registerBeforeRender(this._renderFunction);
  67396. }
  67397. else {
  67398. this._scene.unregisterBeforeRender(this._renderFunction);
  67399. }
  67400. },
  67401. enumerable: true,
  67402. configurable: true
  67403. });
  67404. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  67405. if (x === void 0) { x = 0; }
  67406. if (y === void 0) { y = 0; }
  67407. if (z === void 0) { z = 0; }
  67408. var tmat = BABYLON.Tmp.Matrix[0];
  67409. var parentBone = bone.getParent();
  67410. tmat.copyFrom(bone.getLocalMatrix());
  67411. if (x !== 0 || y !== 0 || z !== 0) {
  67412. var tmat2 = BABYLON.Tmp.Matrix[1];
  67413. BABYLON.Matrix.IdentityToRef(tmat2);
  67414. tmat2.m[12] = x;
  67415. tmat2.m[13] = y;
  67416. tmat2.m[14] = z;
  67417. tmat2.multiplyToRef(tmat, tmat);
  67418. }
  67419. if (parentBone) {
  67420. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  67421. }
  67422. tmat.multiplyToRef(meshMat, tmat);
  67423. position.x = tmat.m[12];
  67424. position.y = tmat.m[13];
  67425. position.z = tmat.m[14];
  67426. };
  67427. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  67428. var len = bones.length;
  67429. var meshPos = this.mesh.position;
  67430. for (var i = 0; i < len; i++) {
  67431. var bone = bones[i];
  67432. var points = this._debugLines[i];
  67433. if (!points) {
  67434. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67435. this._debugLines[i] = points;
  67436. }
  67437. this._getBonePosition(points[0], bone, meshMat);
  67438. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  67439. points[0].subtractInPlace(meshPos);
  67440. points[1].subtractInPlace(meshPos);
  67441. }
  67442. };
  67443. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  67444. var len = bones.length;
  67445. var boneNum = 0;
  67446. var meshPos = this.mesh.position;
  67447. for (var i = len - 1; i >= 0; i--) {
  67448. var childBone = bones[i];
  67449. var parentBone = childBone.getParent();
  67450. if (!parentBone) {
  67451. continue;
  67452. }
  67453. var points = this._debugLines[boneNum];
  67454. if (!points) {
  67455. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67456. this._debugLines[boneNum] = points;
  67457. }
  67458. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  67459. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  67460. points[0].subtractInPlace(meshPos);
  67461. points[1].subtractInPlace(meshPos);
  67462. boneNum++;
  67463. }
  67464. };
  67465. SkeletonViewer.prototype.update = function () {
  67466. if (this.autoUpdateBonesMatrices) {
  67467. this.skeleton.computeAbsoluteTransforms();
  67468. }
  67469. if (this.skeleton.bones[0].length === undefined) {
  67470. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67471. }
  67472. else {
  67473. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67474. }
  67475. if (!this._debugMesh) {
  67476. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  67477. this._debugMesh.renderingGroupId = this.renderingGroupId;
  67478. }
  67479. else {
  67480. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  67481. }
  67482. this._debugMesh.position.copyFrom(this.mesh.position);
  67483. this._debugMesh.color = this.color;
  67484. };
  67485. SkeletonViewer.prototype.dispose = function () {
  67486. if (this._debugMesh) {
  67487. this.isEnabled = false;
  67488. this._debugMesh.dispose();
  67489. this._debugMesh = null;
  67490. }
  67491. };
  67492. return SkeletonViewer;
  67493. }());
  67494. Debug.SkeletonViewer = SkeletonViewer;
  67495. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67496. })(BABYLON || (BABYLON = {}));
  67497. //# sourceMappingURL=babylon.skeletonViewer.js.map
  67498. var BABYLON;
  67499. (function (BABYLON) {
  67500. var Debug;
  67501. (function (Debug) {
  67502. var AxesViewer = /** @class */ (function () {
  67503. function AxesViewer(scene, scaleLines) {
  67504. if (scaleLines === void 0) { scaleLines = 1; }
  67505. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67506. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67507. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67508. this.scaleLines = 1;
  67509. this.scaleLines = scaleLines;
  67510. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  67511. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  67512. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  67513. this._xmesh.renderingGroupId = 2;
  67514. this._ymesh.renderingGroupId = 2;
  67515. this._zmesh.renderingGroupId = 2;
  67516. this._xmesh.material.checkReadyOnlyOnce = true;
  67517. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  67518. this._ymesh.material.checkReadyOnlyOnce = true;
  67519. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  67520. this._zmesh.material.checkReadyOnlyOnce = true;
  67521. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  67522. this.scene = scene;
  67523. }
  67524. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  67525. var scaleLines = this.scaleLines;
  67526. if (this._xmesh) {
  67527. this._xmesh.position.copyFrom(position);
  67528. }
  67529. if (this._ymesh) {
  67530. this._ymesh.position.copyFrom(position);
  67531. }
  67532. if (this._zmesh) {
  67533. this._zmesh.position.copyFrom(position);
  67534. }
  67535. var point2 = this._xline[1];
  67536. point2.x = xaxis.x * scaleLines;
  67537. point2.y = xaxis.y * scaleLines;
  67538. point2.z = xaxis.z * scaleLines;
  67539. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  67540. point2 = this._yline[1];
  67541. point2.x = yaxis.x * scaleLines;
  67542. point2.y = yaxis.y * scaleLines;
  67543. point2.z = yaxis.z * scaleLines;
  67544. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  67545. point2 = this._zline[1];
  67546. point2.x = zaxis.x * scaleLines;
  67547. point2.y = zaxis.y * scaleLines;
  67548. point2.z = zaxis.z * scaleLines;
  67549. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  67550. };
  67551. AxesViewer.prototype.dispose = function () {
  67552. if (this._xmesh) {
  67553. this._xmesh.dispose();
  67554. }
  67555. if (this._ymesh) {
  67556. this._ymesh.dispose();
  67557. }
  67558. if (this._zmesh) {
  67559. this._zmesh.dispose();
  67560. }
  67561. this._xmesh = null;
  67562. this._ymesh = null;
  67563. this._zmesh = null;
  67564. this.scene = null;
  67565. };
  67566. return AxesViewer;
  67567. }());
  67568. Debug.AxesViewer = AxesViewer;
  67569. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67570. })(BABYLON || (BABYLON = {}));
  67571. //# sourceMappingURL=babylon.axesViewer.js.map
  67572. var BABYLON;
  67573. (function (BABYLON) {
  67574. var Debug;
  67575. (function (Debug) {
  67576. var BoneAxesViewer = /** @class */ (function (_super) {
  67577. __extends(BoneAxesViewer, _super);
  67578. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  67579. if (scaleLines === void 0) { scaleLines = 1; }
  67580. var _this = _super.call(this, scene, scaleLines) || this;
  67581. _this.pos = BABYLON.Vector3.Zero();
  67582. _this.xaxis = BABYLON.Vector3.Zero();
  67583. _this.yaxis = BABYLON.Vector3.Zero();
  67584. _this.zaxis = BABYLON.Vector3.Zero();
  67585. _this.mesh = mesh;
  67586. _this.bone = bone;
  67587. return _this;
  67588. }
  67589. BoneAxesViewer.prototype.update = function () {
  67590. if (!this.mesh || !this.bone) {
  67591. return;
  67592. }
  67593. var bone = this.bone;
  67594. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  67595. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  67596. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  67597. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  67598. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  67599. };
  67600. BoneAxesViewer.prototype.dispose = function () {
  67601. if (this.mesh) {
  67602. this.mesh = null;
  67603. this.bone = null;
  67604. _super.prototype.dispose.call(this);
  67605. }
  67606. };
  67607. return BoneAxesViewer;
  67608. }(Debug.AxesViewer));
  67609. Debug.BoneAxesViewer = BoneAxesViewer;
  67610. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67611. })(BABYLON || (BABYLON = {}));
  67612. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  67613. var BABYLON;
  67614. (function (BABYLON) {
  67615. var RayHelper = /** @class */ (function () {
  67616. function RayHelper(ray) {
  67617. this.ray = ray;
  67618. }
  67619. RayHelper.CreateAndShow = function (ray, scene, color) {
  67620. var helper = new RayHelper(ray);
  67621. helper.show(scene, color);
  67622. return helper;
  67623. };
  67624. RayHelper.prototype.show = function (scene, color) {
  67625. if (!this._renderFunction && this.ray) {
  67626. var ray = this.ray;
  67627. this._renderFunction = this._render.bind(this);
  67628. this._scene = scene;
  67629. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  67630. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  67631. if (this._renderFunction) {
  67632. this._scene.registerBeforeRender(this._renderFunction);
  67633. }
  67634. }
  67635. if (color && this._renderLine) {
  67636. this._renderLine.color.copyFrom(color);
  67637. }
  67638. };
  67639. RayHelper.prototype.hide = function () {
  67640. if (this._renderFunction && this._scene) {
  67641. this._scene.unregisterBeforeRender(this._renderFunction);
  67642. this._scene = null;
  67643. this._renderFunction = null;
  67644. if (this._renderLine) {
  67645. this._renderLine.dispose();
  67646. this._renderLine = null;
  67647. }
  67648. this._renderPoints = [];
  67649. }
  67650. };
  67651. RayHelper.prototype._render = function () {
  67652. var ray = this.ray;
  67653. if (!ray) {
  67654. return;
  67655. }
  67656. var point = this._renderPoints[1];
  67657. var len = Math.min(ray.length, 1000000);
  67658. point.copyFrom(ray.direction);
  67659. point.scaleInPlace(len);
  67660. point.addInPlace(ray.origin);
  67661. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  67662. };
  67663. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  67664. this._attachedToMesh = mesh;
  67665. var ray = this.ray;
  67666. if (!ray) {
  67667. return;
  67668. }
  67669. if (!ray.direction) {
  67670. ray.direction = BABYLON.Vector3.Zero();
  67671. }
  67672. if (!ray.origin) {
  67673. ray.origin = BABYLON.Vector3.Zero();
  67674. }
  67675. if (length) {
  67676. ray.length = length;
  67677. }
  67678. if (!meshSpaceOrigin) {
  67679. meshSpaceOrigin = BABYLON.Vector3.Zero();
  67680. }
  67681. if (!meshSpaceDirection) {
  67682. // -1 so that this will work with Mesh.lookAt
  67683. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  67684. }
  67685. if (!this._meshSpaceDirection) {
  67686. this._meshSpaceDirection = meshSpaceDirection.clone();
  67687. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  67688. }
  67689. else {
  67690. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  67691. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  67692. }
  67693. if (!this._updateToMeshFunction) {
  67694. this._updateToMeshFunction = this._updateToMesh.bind(this);
  67695. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  67696. }
  67697. this._updateToMesh();
  67698. };
  67699. RayHelper.prototype.detachFromMesh = function () {
  67700. if (this._attachedToMesh) {
  67701. if (this._updateToMeshFunction) {
  67702. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  67703. }
  67704. this._attachedToMesh = null;
  67705. this._updateToMeshFunction = null;
  67706. }
  67707. };
  67708. RayHelper.prototype._updateToMesh = function () {
  67709. var ray = this.ray;
  67710. if (!this._attachedToMesh || !ray) {
  67711. return;
  67712. }
  67713. if (this._attachedToMesh._isDisposed) {
  67714. this.detachFromMesh();
  67715. return;
  67716. }
  67717. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  67718. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  67719. };
  67720. RayHelper.prototype.dispose = function () {
  67721. this.hide();
  67722. this.detachFromMesh();
  67723. this.ray = null;
  67724. };
  67725. return RayHelper;
  67726. }());
  67727. BABYLON.RayHelper = RayHelper;
  67728. })(BABYLON || (BABYLON = {}));
  67729. //# sourceMappingURL=babylon.rayHelper.js.map
  67730. var BABYLON;
  67731. (function (BABYLON) {
  67732. var DebugLayer = /** @class */ (function () {
  67733. function DebugLayer(scene) {
  67734. this._scene = scene;
  67735. }
  67736. /** Creates the inspector window. */
  67737. DebugLayer.prototype._createInspector = function (config) {
  67738. if (config === void 0) { config = {}; }
  67739. var popup = config.popup || false;
  67740. var initialTab = config.initialTab || 0;
  67741. var parentElement = config.parentElement || null;
  67742. if (!this._inspector) {
  67743. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  67744. } // else nothing to do,; instance is already existing
  67745. };
  67746. DebugLayer.prototype.isVisible = function () {
  67747. if (!this._inspector) {
  67748. return false;
  67749. }
  67750. return true;
  67751. };
  67752. DebugLayer.prototype.hide = function () {
  67753. if (this._inspector) {
  67754. try {
  67755. this._inspector.dispose();
  67756. }
  67757. catch (e) {
  67758. // If the inspector has been removed directly from the inspector tool
  67759. }
  67760. this._inspector = null;
  67761. }
  67762. };
  67763. DebugLayer.prototype.show = function (config) {
  67764. if (config === void 0) { config = {}; }
  67765. if (typeof INSPECTOR == 'undefined') {
  67766. // Load inspector and add it to the DOM
  67767. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  67768. }
  67769. else {
  67770. // Otherwise creates the inspector
  67771. this._createInspector(config);
  67772. }
  67773. };
  67774. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  67775. return DebugLayer;
  67776. }());
  67777. BABYLON.DebugLayer = DebugLayer;
  67778. })(BABYLON || (BABYLON = {}));
  67779. //# sourceMappingURL=babylon.debugLayer.js.map
  67780. var BABYLON;
  67781. (function (BABYLON) {
  67782. var Debug;
  67783. (function (Debug) {
  67784. var PhysicsViewer = /** @class */ (function () {
  67785. function PhysicsViewer(scene) {
  67786. this._impostors = [];
  67787. this._meshes = [];
  67788. this._numMeshes = 0;
  67789. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67790. var physicEngine = this._scene.getPhysicsEngine();
  67791. if (physicEngine) {
  67792. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  67793. }
  67794. }
  67795. PhysicsViewer.prototype._updateDebugMeshes = function () {
  67796. var plugin = this._physicsEnginePlugin;
  67797. for (var i = 0; i < this._numMeshes; i++) {
  67798. var impostor = this._impostors[i];
  67799. if (!impostor) {
  67800. continue;
  67801. }
  67802. if (impostor.isDisposed) {
  67803. this.hideImpostor(this._impostors[i--]);
  67804. }
  67805. else {
  67806. var mesh = this._meshes[i];
  67807. if (mesh && plugin) {
  67808. plugin.syncMeshWithImpostor(mesh, impostor);
  67809. }
  67810. }
  67811. }
  67812. };
  67813. PhysicsViewer.prototype.showImpostor = function (impostor) {
  67814. if (!this._scene) {
  67815. return;
  67816. }
  67817. for (var i = 0; i < this._numMeshes; i++) {
  67818. if (this._impostors[i] == impostor) {
  67819. return;
  67820. }
  67821. }
  67822. var debugMesh = this._getDebugMesh(impostor, this._scene);
  67823. if (debugMesh) {
  67824. this._impostors[this._numMeshes] = impostor;
  67825. this._meshes[this._numMeshes] = debugMesh;
  67826. if (this._numMeshes === 0) {
  67827. this._renderFunction = this._updateDebugMeshes.bind(this);
  67828. this._scene.registerBeforeRender(this._renderFunction);
  67829. }
  67830. this._numMeshes++;
  67831. }
  67832. };
  67833. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  67834. if (!impostor || !this._scene) {
  67835. return;
  67836. }
  67837. var removed = false;
  67838. for (var i = 0; i < this._numMeshes; i++) {
  67839. if (this._impostors[i] == impostor) {
  67840. var mesh = this._meshes[i];
  67841. if (!mesh) {
  67842. continue;
  67843. }
  67844. this._scene.removeMesh(mesh);
  67845. mesh.dispose();
  67846. this._numMeshes--;
  67847. if (this._numMeshes > 0) {
  67848. this._meshes[i] = this._meshes[this._numMeshes];
  67849. this._impostors[i] = this._impostors[this._numMeshes];
  67850. this._meshes[this._numMeshes] = null;
  67851. this._impostors[this._numMeshes] = null;
  67852. }
  67853. else {
  67854. this._meshes[0] = null;
  67855. this._impostors[0] = null;
  67856. }
  67857. removed = true;
  67858. break;
  67859. }
  67860. }
  67861. if (removed && this._numMeshes === 0) {
  67862. this._scene.unregisterBeforeRender(this._renderFunction);
  67863. }
  67864. };
  67865. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  67866. if (!this._debugMaterial) {
  67867. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  67868. this._debugMaterial.wireframe = true;
  67869. }
  67870. return this._debugMaterial;
  67871. };
  67872. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  67873. if (!this._debugBoxMesh) {
  67874. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  67875. this._debugBoxMesh.renderingGroupId = 1;
  67876. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67877. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  67878. scene.removeMesh(this._debugBoxMesh);
  67879. }
  67880. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  67881. };
  67882. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  67883. if (!this._debugSphereMesh) {
  67884. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  67885. this._debugSphereMesh.renderingGroupId = 1;
  67886. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67887. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  67888. scene.removeMesh(this._debugSphereMesh);
  67889. }
  67890. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  67891. };
  67892. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  67893. var mesh = null;
  67894. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  67895. mesh = this._getDebugBoxMesh(scene);
  67896. impostor.getBoxSizeToRef(mesh.scaling);
  67897. }
  67898. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  67899. mesh = this._getDebugSphereMesh(scene);
  67900. var radius = impostor.getRadius();
  67901. mesh.scaling.x = radius * 2;
  67902. mesh.scaling.y = radius * 2;
  67903. mesh.scaling.z = radius * 2;
  67904. }
  67905. return mesh;
  67906. };
  67907. PhysicsViewer.prototype.dispose = function () {
  67908. for (var i = 0; i < this._numMeshes; i++) {
  67909. this.hideImpostor(this._impostors[i]);
  67910. }
  67911. if (this._debugBoxMesh) {
  67912. this._debugBoxMesh.dispose();
  67913. }
  67914. if (this._debugSphereMesh) {
  67915. this._debugSphereMesh.dispose();
  67916. }
  67917. if (this._debugMaterial) {
  67918. this._debugMaterial.dispose();
  67919. }
  67920. this._impostors.length = 0;
  67921. this._scene = null;
  67922. this._physicsEnginePlugin = null;
  67923. };
  67924. return PhysicsViewer;
  67925. }());
  67926. Debug.PhysicsViewer = PhysicsViewer;
  67927. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67928. })(BABYLON || (BABYLON = {}));
  67929. //# sourceMappingURL=babylon.physicsViewer.js.map
  67930. var BABYLON;
  67931. (function (BABYLON) {
  67932. var BoundingBoxRenderer = /** @class */ (function () {
  67933. function BoundingBoxRenderer(scene) {
  67934. this.frontColor = new BABYLON.Color3(1, 1, 1);
  67935. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  67936. this.showBackLines = true;
  67937. this.renderList = new BABYLON.SmartArray(32);
  67938. this._vertexBuffers = {};
  67939. this._scene = scene;
  67940. }
  67941. BoundingBoxRenderer.prototype._prepareRessources = function () {
  67942. if (this._colorShader) {
  67943. return;
  67944. }
  67945. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  67946. attributes: [BABYLON.VertexBuffer.PositionKind],
  67947. uniforms: ["world", "viewProjection", "color"]
  67948. });
  67949. var engine = this._scene.getEngine();
  67950. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  67951. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  67952. this._createIndexBuffer();
  67953. };
  67954. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  67955. var engine = this._scene.getEngine();
  67956. 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]);
  67957. };
  67958. BoundingBoxRenderer.prototype._rebuild = function () {
  67959. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67960. if (vb) {
  67961. vb._rebuild();
  67962. }
  67963. this._createIndexBuffer();
  67964. };
  67965. BoundingBoxRenderer.prototype.reset = function () {
  67966. this.renderList.reset();
  67967. };
  67968. BoundingBoxRenderer.prototype.render = function () {
  67969. if (this.renderList.length === 0) {
  67970. return;
  67971. }
  67972. this._prepareRessources();
  67973. if (!this._colorShader.isReady()) {
  67974. return;
  67975. }
  67976. var engine = this._scene.getEngine();
  67977. engine.setDepthWrite(false);
  67978. this._colorShader._preBind();
  67979. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  67980. var boundingBox = this.renderList.data[boundingBoxIndex];
  67981. var min = boundingBox.minimum;
  67982. var max = boundingBox.maximum;
  67983. var diff = max.subtract(min);
  67984. var median = min.add(diff.scale(0.5));
  67985. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  67986. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  67987. .multiply(boundingBox.getWorldMatrix());
  67988. // VBOs
  67989. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  67990. if (this.showBackLines) {
  67991. // Back
  67992. engine.setDepthFunctionToGreaterOrEqual();
  67993. this._scene.resetCachedMaterial();
  67994. this._colorShader.setColor4("color", this.backColor.toColor4());
  67995. this._colorShader.bind(worldMatrix);
  67996. // Draw order
  67997. engine.draw(false, 0, 24);
  67998. }
  67999. // Front
  68000. engine.setDepthFunctionToLess();
  68001. this._scene.resetCachedMaterial();
  68002. this._colorShader.setColor4("color", this.frontColor.toColor4());
  68003. this._colorShader.bind(worldMatrix);
  68004. // Draw order
  68005. engine.draw(false, 0, 24);
  68006. }
  68007. this._colorShader.unbind();
  68008. engine.setDepthFunctionToLessOrEqual();
  68009. engine.setDepthWrite(true);
  68010. };
  68011. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68012. this._prepareRessources();
  68013. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68014. return;
  68015. }
  68016. var engine = this._scene.getEngine();
  68017. engine.setDepthWrite(false);
  68018. engine.setColorWrite(false);
  68019. this._colorShader._preBind();
  68020. var boundingBox = mesh._boundingInfo.boundingBox;
  68021. var min = boundingBox.minimum;
  68022. var max = boundingBox.maximum;
  68023. var diff = max.subtract(min);
  68024. var median = min.add(diff.scale(0.5));
  68025. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68026. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68027. .multiply(boundingBox.getWorldMatrix());
  68028. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68029. engine.setDepthFunctionToLess();
  68030. this._scene.resetCachedMaterial();
  68031. this._colorShader.bind(worldMatrix);
  68032. engine.draw(false, 0, 24);
  68033. this._colorShader.unbind();
  68034. engine.setDepthFunctionToLessOrEqual();
  68035. engine.setDepthWrite(true);
  68036. engine.setColorWrite(true);
  68037. };
  68038. BoundingBoxRenderer.prototype.dispose = function () {
  68039. if (!this._colorShader) {
  68040. return;
  68041. }
  68042. this.renderList.dispose();
  68043. this._colorShader.dispose();
  68044. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68045. if (buffer) {
  68046. buffer.dispose();
  68047. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68048. }
  68049. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68050. };
  68051. return BoundingBoxRenderer;
  68052. }());
  68053. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  68054. })(BABYLON || (BABYLON = {}));
  68055. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  68056. var BABYLON;
  68057. (function (BABYLON) {
  68058. var MorphTarget = /** @class */ (function () {
  68059. function MorphTarget(name, influence) {
  68060. if (influence === void 0) { influence = 0; }
  68061. this.name = name;
  68062. this.animations = new Array();
  68063. this.onInfluenceChanged = new BABYLON.Observable();
  68064. this.influence = influence;
  68065. }
  68066. Object.defineProperty(MorphTarget.prototype, "influence", {
  68067. get: function () {
  68068. return this._influence;
  68069. },
  68070. set: function (influence) {
  68071. if (this._influence === influence) {
  68072. return;
  68073. }
  68074. var previous = this._influence;
  68075. this._influence = influence;
  68076. if (this.onInfluenceChanged.hasObservers) {
  68077. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  68078. }
  68079. },
  68080. enumerable: true,
  68081. configurable: true
  68082. });
  68083. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  68084. get: function () {
  68085. return this._normals !== undefined;
  68086. },
  68087. enumerable: true,
  68088. configurable: true
  68089. });
  68090. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  68091. get: function () {
  68092. return this._tangents !== undefined;
  68093. },
  68094. enumerable: true,
  68095. configurable: true
  68096. });
  68097. MorphTarget.prototype.setPositions = function (data) {
  68098. this._positions = new Float32Array(data);
  68099. };
  68100. MorphTarget.prototype.getPositions = function () {
  68101. return this._positions;
  68102. };
  68103. MorphTarget.prototype.setNormals = function (data) {
  68104. this._normals = new Float32Array(data);
  68105. };
  68106. MorphTarget.prototype.getNormals = function () {
  68107. return this._normals;
  68108. };
  68109. MorphTarget.prototype.setTangents = function (data) {
  68110. this._tangents = new Float32Array(data);
  68111. };
  68112. MorphTarget.prototype.getTangents = function () {
  68113. return this._tangents;
  68114. };
  68115. /**
  68116. * Serializes the current target into a Serialization object.
  68117. * Returns the serialized object.
  68118. */
  68119. MorphTarget.prototype.serialize = function () {
  68120. var serializationObject = {};
  68121. serializationObject.name = this.name;
  68122. serializationObject.influence = this.influence;
  68123. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  68124. if (this.hasNormals) {
  68125. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  68126. }
  68127. if (this.hasTangents) {
  68128. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  68129. }
  68130. // Animations
  68131. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  68132. return serializationObject;
  68133. };
  68134. // Statics
  68135. MorphTarget.Parse = function (serializationObject) {
  68136. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  68137. result.setPositions(serializationObject.positions);
  68138. if (serializationObject.normals) {
  68139. result.setNormals(serializationObject.normals);
  68140. }
  68141. if (serializationObject.tangents) {
  68142. result.setTangents(serializationObject.tangents);
  68143. }
  68144. // Animations
  68145. if (serializationObject.animations) {
  68146. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  68147. var parsedAnimation = serializationObject.animations[animationIndex];
  68148. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68149. }
  68150. }
  68151. return result;
  68152. };
  68153. MorphTarget.FromMesh = function (mesh, name, influence) {
  68154. if (!name) {
  68155. name = mesh.name;
  68156. }
  68157. var result = new MorphTarget(name, influence);
  68158. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68159. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68160. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  68161. }
  68162. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  68163. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  68164. }
  68165. return result;
  68166. };
  68167. return MorphTarget;
  68168. }());
  68169. BABYLON.MorphTarget = MorphTarget;
  68170. })(BABYLON || (BABYLON = {}));
  68171. //# sourceMappingURL=babylon.morphTarget.js.map
  68172. var BABYLON;
  68173. (function (BABYLON) {
  68174. var MorphTargetManager = /** @class */ (function () {
  68175. function MorphTargetManager(scene) {
  68176. if (scene === void 0) { scene = null; }
  68177. this._targets = new Array();
  68178. this._targetObservable = new Array();
  68179. this._activeTargets = new BABYLON.SmartArray(16);
  68180. this._supportsNormals = false;
  68181. this._supportsTangents = false;
  68182. this._vertexCount = 0;
  68183. this._uniqueId = 0;
  68184. this._tempInfluences = new Array();
  68185. if (!scene) {
  68186. scene = BABYLON.Engine.LastCreatedScene;
  68187. }
  68188. this._scene = scene;
  68189. if (this._scene) {
  68190. this._scene.morphTargetManagers.push(this);
  68191. this._uniqueId = this._scene.getUniqueId();
  68192. }
  68193. }
  68194. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  68195. get: function () {
  68196. return this._uniqueId;
  68197. },
  68198. enumerable: true,
  68199. configurable: true
  68200. });
  68201. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  68202. get: function () {
  68203. return this._vertexCount;
  68204. },
  68205. enumerable: true,
  68206. configurable: true
  68207. });
  68208. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  68209. get: function () {
  68210. return this._supportsNormals;
  68211. },
  68212. enumerable: true,
  68213. configurable: true
  68214. });
  68215. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  68216. get: function () {
  68217. return this._supportsTangents;
  68218. },
  68219. enumerable: true,
  68220. configurable: true
  68221. });
  68222. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  68223. get: function () {
  68224. return this._targets.length;
  68225. },
  68226. enumerable: true,
  68227. configurable: true
  68228. });
  68229. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  68230. get: function () {
  68231. return this._activeTargets.length;
  68232. },
  68233. enumerable: true,
  68234. configurable: true
  68235. });
  68236. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  68237. get: function () {
  68238. return this._influences;
  68239. },
  68240. enumerable: true,
  68241. configurable: true
  68242. });
  68243. MorphTargetManager.prototype.getActiveTarget = function (index) {
  68244. return this._activeTargets.data[index];
  68245. };
  68246. MorphTargetManager.prototype.getTarget = function (index) {
  68247. return this._targets[index];
  68248. };
  68249. MorphTargetManager.prototype.addTarget = function (target) {
  68250. var _this = this;
  68251. if (this._vertexCount) {
  68252. if (this._vertexCount !== target.getPositions().length / 3) {
  68253. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  68254. return;
  68255. }
  68256. }
  68257. this._targets.push(target);
  68258. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  68259. _this._syncActiveTargets(needUpdate);
  68260. }));
  68261. this._syncActiveTargets(true);
  68262. };
  68263. MorphTargetManager.prototype.removeTarget = function (target) {
  68264. var index = this._targets.indexOf(target);
  68265. if (index >= 0) {
  68266. this._targets.splice(index, 1);
  68267. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  68268. this._vertexCount = 0;
  68269. this._syncActiveTargets(true);
  68270. }
  68271. };
  68272. /**
  68273. * Serializes the current manager into a Serialization object.
  68274. * Returns the serialized object.
  68275. */
  68276. MorphTargetManager.prototype.serialize = function () {
  68277. var serializationObject = {};
  68278. serializationObject.id = this.uniqueId;
  68279. serializationObject.targets = [];
  68280. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68281. var target = _a[_i];
  68282. serializationObject.targets.push(target.serialize());
  68283. }
  68284. return serializationObject;
  68285. };
  68286. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  68287. var influenceCount = 0;
  68288. this._activeTargets.reset();
  68289. this._supportsNormals = true;
  68290. this._supportsTangents = true;
  68291. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68292. var target = _a[_i];
  68293. if (target.influence > 0) {
  68294. this._activeTargets.push(target);
  68295. this._tempInfluences[influenceCount++] = target.influence;
  68296. this._supportsNormals = this._supportsNormals && target.hasNormals;
  68297. this._supportsTangents = this._supportsTangents && target.hasTangents;
  68298. if (this._vertexCount === 0) {
  68299. this._vertexCount = target.getPositions().length / 3;
  68300. }
  68301. }
  68302. }
  68303. if (!this._influences || this._influences.length !== influenceCount) {
  68304. this._influences = new Float32Array(influenceCount);
  68305. }
  68306. for (var index = 0; index < influenceCount; index++) {
  68307. this._influences[index] = this._tempInfluences[index];
  68308. }
  68309. if (needUpdate && this._scene) {
  68310. // Flag meshes as dirty to resync with the active targets
  68311. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  68312. var mesh = _c[_b];
  68313. if (mesh.morphTargetManager === this) {
  68314. mesh._syncGeometryWithMorphTargetManager();
  68315. }
  68316. }
  68317. }
  68318. };
  68319. // Statics
  68320. MorphTargetManager.Parse = function (serializationObject, scene) {
  68321. var result = new MorphTargetManager(scene);
  68322. result._uniqueId = serializationObject.id;
  68323. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  68324. var targetData = _a[_i];
  68325. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  68326. }
  68327. return result;
  68328. };
  68329. return MorphTargetManager;
  68330. }());
  68331. BABYLON.MorphTargetManager = MorphTargetManager;
  68332. })(BABYLON || (BABYLON = {}));
  68333. //# sourceMappingURL=babylon.morphTargetManager.js.map
  68334. var BABYLON;
  68335. (function (BABYLON) {
  68336. var Octree = /** @class */ (function () {
  68337. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  68338. if (maxDepth === void 0) { maxDepth = 2; }
  68339. this.maxDepth = maxDepth;
  68340. this.dynamicContent = new Array();
  68341. this._maxBlockCapacity = maxBlockCapacity || 64;
  68342. this._selectionContent = new BABYLON.SmartArray(1024);
  68343. this._creationFunc = creationFunc;
  68344. }
  68345. // Methods
  68346. Octree.prototype.update = function (worldMin, worldMax, entries) {
  68347. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  68348. };
  68349. Octree.prototype.addMesh = function (entry) {
  68350. for (var index = 0; index < this.blocks.length; index++) {
  68351. var block = this.blocks[index];
  68352. block.addEntry(entry);
  68353. }
  68354. };
  68355. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  68356. this._selectionContent.reset();
  68357. for (var index = 0; index < this.blocks.length; index++) {
  68358. var block = this.blocks[index];
  68359. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  68360. }
  68361. if (allowDuplicate) {
  68362. this._selectionContent.concat(this.dynamicContent);
  68363. }
  68364. else {
  68365. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68366. }
  68367. return this._selectionContent;
  68368. };
  68369. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  68370. this._selectionContent.reset();
  68371. for (var index = 0; index < this.blocks.length; index++) {
  68372. var block = this.blocks[index];
  68373. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  68374. }
  68375. if (allowDuplicate) {
  68376. this._selectionContent.concat(this.dynamicContent);
  68377. }
  68378. else {
  68379. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68380. }
  68381. return this._selectionContent;
  68382. };
  68383. Octree.prototype.intersectsRay = function (ray) {
  68384. this._selectionContent.reset();
  68385. for (var index = 0; index < this.blocks.length; index++) {
  68386. var block = this.blocks[index];
  68387. block.intersectsRay(ray, this._selectionContent);
  68388. }
  68389. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68390. return this._selectionContent;
  68391. };
  68392. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  68393. target.blocks = new Array();
  68394. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  68395. // Segmenting space
  68396. for (var x = 0; x < 2; x++) {
  68397. for (var y = 0; y < 2; y++) {
  68398. for (var z = 0; z < 2; z++) {
  68399. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  68400. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  68401. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  68402. block.addEntries(entries);
  68403. target.blocks.push(block);
  68404. }
  68405. }
  68406. }
  68407. };
  68408. Octree.CreationFuncForMeshes = function (entry, block) {
  68409. var boundingInfo = entry.getBoundingInfo();
  68410. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68411. block.entries.push(entry);
  68412. }
  68413. };
  68414. Octree.CreationFuncForSubMeshes = function (entry, block) {
  68415. var boundingInfo = entry.getBoundingInfo();
  68416. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68417. block.entries.push(entry);
  68418. }
  68419. };
  68420. return Octree;
  68421. }());
  68422. BABYLON.Octree = Octree;
  68423. })(BABYLON || (BABYLON = {}));
  68424. //# sourceMappingURL=babylon.octree.js.map
  68425. var BABYLON;
  68426. (function (BABYLON) {
  68427. var OctreeBlock = /** @class */ (function () {
  68428. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  68429. this.entries = new Array();
  68430. this._boundingVectors = new Array();
  68431. this._capacity = capacity;
  68432. this._depth = depth;
  68433. this._maxDepth = maxDepth;
  68434. this._creationFunc = creationFunc;
  68435. this._minPoint = minPoint;
  68436. this._maxPoint = maxPoint;
  68437. this._boundingVectors.push(minPoint.clone());
  68438. this._boundingVectors.push(maxPoint.clone());
  68439. this._boundingVectors.push(minPoint.clone());
  68440. this._boundingVectors[2].x = maxPoint.x;
  68441. this._boundingVectors.push(minPoint.clone());
  68442. this._boundingVectors[3].y = maxPoint.y;
  68443. this._boundingVectors.push(minPoint.clone());
  68444. this._boundingVectors[4].z = maxPoint.z;
  68445. this._boundingVectors.push(maxPoint.clone());
  68446. this._boundingVectors[5].z = minPoint.z;
  68447. this._boundingVectors.push(maxPoint.clone());
  68448. this._boundingVectors[6].x = minPoint.x;
  68449. this._boundingVectors.push(maxPoint.clone());
  68450. this._boundingVectors[7].y = minPoint.y;
  68451. }
  68452. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  68453. // Property
  68454. get: function () {
  68455. return this._capacity;
  68456. },
  68457. enumerable: true,
  68458. configurable: true
  68459. });
  68460. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  68461. get: function () {
  68462. return this._minPoint;
  68463. },
  68464. enumerable: true,
  68465. configurable: true
  68466. });
  68467. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  68468. get: function () {
  68469. return this._maxPoint;
  68470. },
  68471. enumerable: true,
  68472. configurable: true
  68473. });
  68474. // Methods
  68475. OctreeBlock.prototype.addEntry = function (entry) {
  68476. if (this.blocks) {
  68477. for (var index = 0; index < this.blocks.length; index++) {
  68478. var block = this.blocks[index];
  68479. block.addEntry(entry);
  68480. }
  68481. return;
  68482. }
  68483. this._creationFunc(entry, this);
  68484. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  68485. this.createInnerBlocks();
  68486. }
  68487. };
  68488. OctreeBlock.prototype.addEntries = function (entries) {
  68489. for (var index = 0; index < entries.length; index++) {
  68490. var mesh = entries[index];
  68491. this.addEntry(mesh);
  68492. }
  68493. };
  68494. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  68495. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  68496. if (this.blocks) {
  68497. for (var index = 0; index < this.blocks.length; index++) {
  68498. var block = this.blocks[index];
  68499. block.select(frustumPlanes, selection, allowDuplicate);
  68500. }
  68501. return;
  68502. }
  68503. if (allowDuplicate) {
  68504. selection.concat(this.entries);
  68505. }
  68506. else {
  68507. selection.concatWithNoDuplicate(this.entries);
  68508. }
  68509. }
  68510. };
  68511. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  68512. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  68513. if (this.blocks) {
  68514. for (var index = 0; index < this.blocks.length; index++) {
  68515. var block = this.blocks[index];
  68516. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  68517. }
  68518. return;
  68519. }
  68520. if (allowDuplicate) {
  68521. selection.concat(this.entries);
  68522. }
  68523. else {
  68524. selection.concatWithNoDuplicate(this.entries);
  68525. }
  68526. }
  68527. };
  68528. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  68529. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  68530. if (this.blocks) {
  68531. for (var index = 0; index < this.blocks.length; index++) {
  68532. var block = this.blocks[index];
  68533. block.intersectsRay(ray, selection);
  68534. }
  68535. return;
  68536. }
  68537. selection.concatWithNoDuplicate(this.entries);
  68538. }
  68539. };
  68540. OctreeBlock.prototype.createInnerBlocks = function () {
  68541. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  68542. };
  68543. return OctreeBlock;
  68544. }());
  68545. BABYLON.OctreeBlock = OctreeBlock;
  68546. })(BABYLON || (BABYLON = {}));
  68547. //# sourceMappingURL=babylon.octreeBlock.js.map
  68548. var BABYLON;
  68549. (function (BABYLON) {
  68550. var SIMDVector3 = /** @class */ (function () {
  68551. function SIMDVector3() {
  68552. }
  68553. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  68554. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  68555. };
  68556. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  68557. var m = transformation.m;
  68558. var m0 = SIMD.Float32x4.load(m, 0);
  68559. var m1 = SIMD.Float32x4.load(m, 4);
  68560. var m2 = SIMD.Float32x4.load(m, 8);
  68561. var m3 = SIMD.Float32x4.load(m, 12);
  68562. 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));
  68563. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  68564. result.x = SIMD.Float32x4.extractLane(r, 0);
  68565. result.y = SIMD.Float32x4.extractLane(r, 1);
  68566. result.z = SIMD.Float32x4.extractLane(r, 2);
  68567. };
  68568. return SIMDVector3;
  68569. }());
  68570. var SIMDMatrix = /** @class */ (function () {
  68571. function SIMDMatrix() {
  68572. }
  68573. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  68574. var tm = this.m;
  68575. var om = other.m;
  68576. var m0 = SIMD.Float32x4.load(om, 0);
  68577. var m1 = SIMD.Float32x4.load(om, 4);
  68578. var m2 = SIMD.Float32x4.load(om, 8);
  68579. var m3 = SIMD.Float32x4.load(om, 12);
  68580. for (var i = 0; i < 16; i += 4) {
  68581. 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)))));
  68582. }
  68583. return this;
  68584. };
  68585. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  68586. var src = this.m;
  68587. var dest = other.m;
  68588. // Load the 4 rows
  68589. var src0 = SIMD.Float32x4.load(src, 0);
  68590. var src1 = SIMD.Float32x4.load(src, 4);
  68591. var src2 = SIMD.Float32x4.load(src, 8);
  68592. var src3 = SIMD.Float32x4.load(src, 12);
  68593. // Transpose the source matrix. Sort of. Not a true transpose operation
  68594. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  68595. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  68596. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  68597. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  68598. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  68599. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  68600. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  68601. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  68602. // This is a true transposition, but it will lead to an incorrect result
  68603. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  68604. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  68605. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68606. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68607. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  68608. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  68609. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68610. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68611. // ----
  68612. tmp1 = SIMD.Float32x4.mul(row2, row3);
  68613. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68614. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  68615. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  68616. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68617. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  68618. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  68619. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  68620. // ----
  68621. tmp1 = SIMD.Float32x4.mul(row1, row2);
  68622. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68623. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  68624. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  68625. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68626. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  68627. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  68628. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  68629. // ----
  68630. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  68631. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68632. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  68633. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  68634. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  68635. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68636. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  68637. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  68638. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  68639. // ----
  68640. tmp1 = SIMD.Float32x4.mul(row0, row1);
  68641. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68642. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68643. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  68644. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68645. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68646. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  68647. // ----
  68648. tmp1 = SIMD.Float32x4.mul(row0, row3);
  68649. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68650. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  68651. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  68652. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68653. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  68654. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  68655. // ----
  68656. tmp1 = SIMD.Float32x4.mul(row0, row2);
  68657. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68658. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  68659. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  68660. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68661. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  68662. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  68663. // Compute determinant
  68664. var det = SIMD.Float32x4.mul(row0, minor0);
  68665. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  68666. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  68667. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  68668. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  68669. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  68670. // These shuffles aren't necessary if the faulty transposition is done
  68671. // up at the top of this function.
  68672. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  68673. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  68674. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  68675. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  68676. // Compute final values by multiplying with 1/det
  68677. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  68678. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  68679. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  68680. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  68681. return this;
  68682. };
  68683. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  68684. var out = result.m;
  68685. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  68686. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  68687. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  68688. // cc.kmVec3Subtract(f, pCenter, pEye);
  68689. var f = SIMD.Float32x4.sub(center, eye);
  68690. // cc.kmVec3Normalize(f, f);
  68691. var tmp = SIMD.Float32x4.mul(f, f);
  68692. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68693. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68694. // cc.kmVec3Assign(up, pUp);
  68695. // cc.kmVec3Normalize(up, up);
  68696. tmp = SIMD.Float32x4.mul(up, up);
  68697. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68698. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68699. // cc.kmVec3Cross(s, f, up);
  68700. 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)));
  68701. // cc.kmVec3Normalize(s, s);
  68702. tmp = SIMD.Float32x4.mul(s, s);
  68703. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68704. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68705. // cc.kmVec3Cross(u, s, f);
  68706. 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)));
  68707. // cc.kmVec3Normalize(s, s);
  68708. tmp = SIMD.Float32x4.mul(s, s);
  68709. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68710. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68711. var zero = SIMD.Float32x4.splat(0.0);
  68712. s = SIMD.Float32x4.neg(s);
  68713. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  68714. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  68715. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  68716. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  68717. 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);
  68718. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  68719. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  68720. 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)))));
  68721. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  68722. 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)))));
  68723. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  68724. 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)))));
  68725. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  68726. 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)))));
  68727. };
  68728. return SIMDMatrix;
  68729. }());
  68730. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  68731. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  68732. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  68733. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  68734. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  68735. var SIMDHelper = /** @class */ (function () {
  68736. function SIMDHelper() {
  68737. }
  68738. Object.defineProperty(SIMDHelper, "IsEnabled", {
  68739. get: function () {
  68740. return SIMDHelper._isEnabled;
  68741. },
  68742. enumerable: true,
  68743. configurable: true
  68744. });
  68745. SIMDHelper.DisableSIMD = function () {
  68746. // Replace functions
  68747. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  68748. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  68749. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  68750. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  68751. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  68752. SIMDHelper._isEnabled = false;
  68753. };
  68754. SIMDHelper.EnableSIMD = function () {
  68755. if (self.SIMD === undefined) {
  68756. return;
  68757. }
  68758. // check if polyfills needed
  68759. if (!self.Math.fround) {
  68760. self.Math.fround = (function (array) { return function (x) {
  68761. return array[0] = x, array[0];
  68762. }; })(new Float32Array(1));
  68763. }
  68764. if (!self.Math.imul) {
  68765. self.Math.imul = function (a, b) {
  68766. var ah = (a >>> 16) & 0xffff;
  68767. var al = a & 0xffff;
  68768. var bh = (b >>> 16) & 0xffff;
  68769. var bl = b & 0xffff;
  68770. // the shift by 0 fixes the sign on the high part
  68771. // the final |0 converts the unsigned value into a signed value
  68772. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  68773. };
  68774. }
  68775. // Replace functions
  68776. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  68777. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  68778. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  68779. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  68780. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  68781. SIMDHelper._isEnabled = true;
  68782. };
  68783. SIMDHelper._isEnabled = false;
  68784. return SIMDHelper;
  68785. }());
  68786. BABYLON.SIMDHelper = SIMDHelper;
  68787. })(BABYLON || (BABYLON = {}));
  68788. //# sourceMappingURL=babylon.math.SIMD.js.map
  68789. var BABYLON;
  68790. (function (BABYLON) {
  68791. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  68792. __extends(VRDistortionCorrectionPostProcess, _super);
  68793. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  68794. var _this = _super.call(this, name, "vrDistortionCorrection", [
  68795. 'LensCenter',
  68796. 'Scale',
  68797. 'ScaleIn',
  68798. 'HmdWarpParam'
  68799. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  68800. _this._isRightEye = isRightEye;
  68801. _this._distortionFactors = vrMetrics.distortionK;
  68802. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  68803. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  68804. _this.adaptScaleToCurrentViewport = true;
  68805. _this.onSizeChangedObservable.add(function () {
  68806. _this.aspectRatio = _this.width * .5 / _this.height;
  68807. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  68808. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  68809. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  68810. });
  68811. _this.onApplyObservable.add(function (effect) {
  68812. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  68813. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  68814. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  68815. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  68816. });
  68817. return _this;
  68818. }
  68819. return VRDistortionCorrectionPostProcess;
  68820. }(BABYLON.PostProcess));
  68821. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  68822. })(BABYLON || (BABYLON = {}));
  68823. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  68824. var BABYLON;
  68825. (function (BABYLON) {
  68826. var AnaglyphPostProcess = /** @class */ (function (_super) {
  68827. __extends(AnaglyphPostProcess, _super);
  68828. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  68829. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  68830. _this._passedProcess = rigCameras[0]._rigPostProcess;
  68831. _this.onApplyObservable.add(function (effect) {
  68832. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  68833. });
  68834. return _this;
  68835. }
  68836. return AnaglyphPostProcess;
  68837. }(BABYLON.PostProcess));
  68838. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  68839. })(BABYLON || (BABYLON = {}));
  68840. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  68841. var BABYLON;
  68842. (function (BABYLON) {
  68843. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  68844. __extends(StereoscopicInterlacePostProcess, _super);
  68845. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  68846. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  68847. _this._passedProcess = rigCameras[0]._rigPostProcess;
  68848. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  68849. _this.onSizeChangedObservable.add(function () {
  68850. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  68851. });
  68852. _this.onApplyObservable.add(function (effect) {
  68853. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  68854. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  68855. });
  68856. return _this;
  68857. }
  68858. return StereoscopicInterlacePostProcess;
  68859. }(BABYLON.PostProcess));
  68860. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  68861. })(BABYLON || (BABYLON = {}));
  68862. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  68863. var BABYLON;
  68864. (function (BABYLON) {
  68865. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  68866. function FreeCameraDeviceOrientationInput() {
  68867. var _this = this;
  68868. this._screenOrientationAngle = 0;
  68869. this._screenQuaternion = new BABYLON.Quaternion();
  68870. this._alpha = 0;
  68871. this._beta = 0;
  68872. this._gamma = 0;
  68873. this._orientationChanged = function () {
  68874. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  68875. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  68876. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  68877. };
  68878. this._deviceOrientation = function (evt) {
  68879. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  68880. _this._beta = evt.beta !== null ? evt.beta : 0;
  68881. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  68882. };
  68883. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  68884. this._orientationChanged();
  68885. }
  68886. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  68887. get: function () {
  68888. return this._camera;
  68889. },
  68890. set: function (camera) {
  68891. this._camera = camera;
  68892. if (this._camera != null && !this._camera.rotationQuaternion) {
  68893. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  68894. }
  68895. },
  68896. enumerable: true,
  68897. configurable: true
  68898. });
  68899. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  68900. window.addEventListener("orientationchange", this._orientationChanged);
  68901. window.addEventListener("deviceorientation", this._deviceOrientation);
  68902. //In certain cases, the attach control is called AFTER orientation was changed,
  68903. //So this is needed.
  68904. this._orientationChanged();
  68905. };
  68906. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  68907. window.removeEventListener("orientationchange", this._orientationChanged);
  68908. window.removeEventListener("deviceorientation", this._deviceOrientation);
  68909. };
  68910. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  68911. //if no device orientation provided, don't update the rotation.
  68912. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  68913. if (!this._alpha)
  68914. return;
  68915. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  68916. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  68917. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  68918. //Mirror on XY Plane
  68919. this._camera.rotationQuaternion.z *= -1;
  68920. this._camera.rotationQuaternion.w *= -1;
  68921. };
  68922. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  68923. return "FreeCameraDeviceOrientationInput";
  68924. };
  68925. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  68926. return "deviceOrientation";
  68927. };
  68928. return FreeCameraDeviceOrientationInput;
  68929. }());
  68930. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  68931. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  68932. })(BABYLON || (BABYLON = {}));
  68933. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  68934. var BABYLON;
  68935. (function (BABYLON) {
  68936. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  68937. function ArcRotateCameraVRDeviceOrientationInput() {
  68938. this.alphaCorrection = 1;
  68939. this.betaCorrection = 1;
  68940. this.gammaCorrection = 1;
  68941. this._alpha = 0;
  68942. this._beta = 0;
  68943. this._gamma = 0;
  68944. this._dirty = false;
  68945. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  68946. }
  68947. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  68948. this.camera.attachControl(element, noPreventDefault);
  68949. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  68950. };
  68951. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  68952. if (evt.alpha !== null) {
  68953. this._alpha = +evt.alpha | 0;
  68954. }
  68955. if (evt.beta !== null) {
  68956. this._beta = +evt.beta | 0;
  68957. }
  68958. if (evt.gamma !== null) {
  68959. this._gamma = +evt.gamma | 0;
  68960. }
  68961. this._dirty = true;
  68962. };
  68963. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  68964. if (this._dirty) {
  68965. this._dirty = false;
  68966. if (this._gamma < 0) {
  68967. this._gamma = 180 + this._gamma;
  68968. }
  68969. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  68970. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  68971. }
  68972. };
  68973. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  68974. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  68975. };
  68976. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  68977. return "ArcRotateCameraVRDeviceOrientationInput";
  68978. };
  68979. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  68980. return "VRDeviceOrientation";
  68981. };
  68982. return ArcRotateCameraVRDeviceOrientationInput;
  68983. }());
  68984. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  68985. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  68986. })(BABYLON || (BABYLON = {}));
  68987. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  68988. var BABYLON;
  68989. (function (BABYLON) {
  68990. var VRCameraMetrics = /** @class */ (function () {
  68991. function VRCameraMetrics() {
  68992. this.compensateDistortion = true;
  68993. }
  68994. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  68995. get: function () {
  68996. return this.hResolution / (2 * this.vResolution);
  68997. },
  68998. enumerable: true,
  68999. configurable: true
  69000. });
  69001. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  69002. get: function () {
  69003. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  69004. },
  69005. enumerable: true,
  69006. configurable: true
  69007. });
  69008. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  69009. get: function () {
  69010. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69011. var h = (4 * meters) / this.hScreenSize;
  69012. return BABYLON.Matrix.Translation(h, 0, 0);
  69013. },
  69014. enumerable: true,
  69015. configurable: true
  69016. });
  69017. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  69018. get: function () {
  69019. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69020. var h = (4 * meters) / this.hScreenSize;
  69021. return BABYLON.Matrix.Translation(-h, 0, 0);
  69022. },
  69023. enumerable: true,
  69024. configurable: true
  69025. });
  69026. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  69027. get: function () {
  69028. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  69029. },
  69030. enumerable: true,
  69031. configurable: true
  69032. });
  69033. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  69034. get: function () {
  69035. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  69036. },
  69037. enumerable: true,
  69038. configurable: true
  69039. });
  69040. VRCameraMetrics.GetDefault = function () {
  69041. var result = new VRCameraMetrics();
  69042. result.hResolution = 1280;
  69043. result.vResolution = 800;
  69044. result.hScreenSize = 0.149759993;
  69045. result.vScreenSize = 0.0935999975;
  69046. result.vScreenCenter = 0.0467999987;
  69047. result.eyeToScreenDistance = 0.0410000011;
  69048. result.lensSeparationDistance = 0.0635000020;
  69049. result.interpupillaryDistance = 0.0640000030;
  69050. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  69051. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  69052. result.postProcessScaleFactor = 1.714605507808412;
  69053. result.lensCenterOffset = 0.151976421;
  69054. return result;
  69055. };
  69056. return VRCameraMetrics;
  69057. }());
  69058. BABYLON.VRCameraMetrics = VRCameraMetrics;
  69059. })(BABYLON || (BABYLON = {}));
  69060. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  69061. var BABYLON;
  69062. (function (BABYLON) {
  69063. var WebVRFreeCamera = /** @class */ (function (_super) {
  69064. __extends(WebVRFreeCamera, _super);
  69065. function WebVRFreeCamera(name, position, scene, webVROptions) {
  69066. if (webVROptions === void 0) { webVROptions = {}; }
  69067. var _this = _super.call(this, name, position, scene) || this;
  69068. _this.webVROptions = webVROptions;
  69069. _this._vrDevice = null;
  69070. _this.rawPose = null;
  69071. _this._specsVersion = "1.1";
  69072. _this._attached = false;
  69073. _this._descendants = [];
  69074. _this.devicePosition = BABYLON.Vector3.Zero();
  69075. _this.deviceScaleFactor = 1;
  69076. _this.controllers = [];
  69077. _this.onControllersAttachedObservable = new BABYLON.Observable();
  69078. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  69079. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  69080. _this.minZ = 0.1;
  69081. //legacy support - the compensation boolean was removed.
  69082. if (arguments.length === 5) {
  69083. _this.webVROptions = arguments[4];
  69084. }
  69085. // default webVR options
  69086. if (_this.webVROptions.trackPosition == undefined) {
  69087. _this.webVROptions.trackPosition = true;
  69088. }
  69089. if (_this.webVROptions.controllerMeshes == undefined) {
  69090. _this.webVROptions.controllerMeshes = true;
  69091. }
  69092. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  69093. _this.webVROptions.defaultLightingOnControllers = true;
  69094. }
  69095. _this.rotationQuaternion = new BABYLON.Quaternion();
  69096. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69097. if (_this.webVROptions && _this.webVROptions.positionScale) {
  69098. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  69099. }
  69100. //enable VR
  69101. var engine = _this.getEngine();
  69102. _this._onVREnabled = function (success) { if (success) {
  69103. _this.initControllers();
  69104. } };
  69105. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  69106. engine.initWebVR().add(function (event) {
  69107. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  69108. return;
  69109. }
  69110. _this._vrDevice = event.vrDisplay;
  69111. //reset the rig parameters.
  69112. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  69113. if (_this._attached) {
  69114. _this.getEngine().enableVR();
  69115. }
  69116. });
  69117. if (typeof (VRFrameData) !== "undefined")
  69118. _this._frameData = new VRFrameData();
  69119. /**
  69120. * The idea behind the following lines:
  69121. * objects that have the camera as parent should actually have the rig cameras as a parent.
  69122. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  69123. * the second will not show it correctly.
  69124. *
  69125. * To solve this - each object that has the camera as parent will be added to a protected array.
  69126. * When the rig camera renders, it will take this array and set all of those to be its children.
  69127. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  69128. * Amazing!
  69129. */
  69130. scene.onBeforeCameraRenderObservable.add(function (camera) {
  69131. if (camera.parent === _this && _this.rigParenting) {
  69132. _this._descendants = _this.getDescendants(true, function (n) {
  69133. // don't take the cameras or the controllers!
  69134. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  69135. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  69136. return !isController && !isRigCamera;
  69137. });
  69138. _this._descendants.forEach(function (node) {
  69139. node.parent = camera;
  69140. });
  69141. }
  69142. });
  69143. scene.onAfterCameraRenderObservable.add(function (camera) {
  69144. if (camera.parent === _this && _this.rigParenting) {
  69145. _this._descendants.forEach(function (node) {
  69146. node.parent = _this;
  69147. });
  69148. }
  69149. });
  69150. return _this;
  69151. }
  69152. WebVRFreeCamera.prototype.dispose = function () {
  69153. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  69154. _super.prototype.dispose.call(this);
  69155. };
  69156. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  69157. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  69158. var gp = _a[_i];
  69159. if (gp.hand === name) {
  69160. return gp;
  69161. }
  69162. }
  69163. return null;
  69164. };
  69165. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  69166. get: function () {
  69167. if (!this._leftController) {
  69168. this._leftController = this.getControllerByName("left");
  69169. }
  69170. return this._leftController;
  69171. },
  69172. enumerable: true,
  69173. configurable: true
  69174. });
  69175. ;
  69176. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  69177. get: function () {
  69178. if (!this._rightController) {
  69179. this._rightController = this.getControllerByName("right");
  69180. }
  69181. return this._rightController;
  69182. },
  69183. enumerable: true,
  69184. configurable: true
  69185. });
  69186. ;
  69187. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  69188. if (length === void 0) { length = 100; }
  69189. if (this.leftCamera) {
  69190. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  69191. }
  69192. else {
  69193. return _super.prototype.getForwardRay.call(this, length);
  69194. }
  69195. };
  69196. WebVRFreeCamera.prototype._checkInputs = function () {
  69197. if (this._vrDevice && this._vrDevice.isPresenting) {
  69198. this._vrDevice.getFrameData(this._frameData);
  69199. this.updateFromDevice(this._frameData.pose);
  69200. }
  69201. _super.prototype._checkInputs.call(this);
  69202. };
  69203. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  69204. if (poseData && poseData.orientation) {
  69205. this.rawPose = poseData;
  69206. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  69207. if (this.getScene().useRightHandedSystem) {
  69208. this.deviceRotationQuaternion.z *= -1;
  69209. this.deviceRotationQuaternion.w *= -1;
  69210. }
  69211. if (this.webVROptions.trackPosition && this.rawPose.position) {
  69212. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  69213. if (this.getScene().useRightHandedSystem) {
  69214. this.devicePosition.z *= -1;
  69215. }
  69216. }
  69217. }
  69218. };
  69219. /**
  69220. * WebVR's attach control will start broadcasting frames to the device.
  69221. * Note that in certain browsers (chrome for example) this function must be called
  69222. * within a user-interaction callback. Example:
  69223. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  69224. *
  69225. * @param {HTMLElement} element
  69226. * @param {boolean} [noPreventDefault]
  69227. *
  69228. * @memberOf WebVRFreeCamera
  69229. */
  69230. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  69231. _super.prototype.attachControl.call(this, element, noPreventDefault);
  69232. this._attached = true;
  69233. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  69234. if (this._vrDevice) {
  69235. this.getEngine().enableVR();
  69236. }
  69237. };
  69238. WebVRFreeCamera.prototype.detachControl = function (element) {
  69239. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69240. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69241. _super.prototype.detachControl.call(this, element);
  69242. this._attached = false;
  69243. this.getEngine().disableVR();
  69244. };
  69245. WebVRFreeCamera.prototype.getClassName = function () {
  69246. return "WebVRFreeCamera";
  69247. };
  69248. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  69249. //uses the vrDisplay's "resetPose()".
  69250. //pitch and roll won't be affected.
  69251. this._vrDevice.resetPose();
  69252. };
  69253. WebVRFreeCamera.prototype._updateRigCameras = function () {
  69254. var camLeft = this._rigCameras[0];
  69255. var camRight = this._rigCameras[1];
  69256. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69257. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69258. camLeft.position.copyFrom(this.devicePosition);
  69259. camRight.position.copyFrom(this.devicePosition);
  69260. };
  69261. /**
  69262. * This function is called by the two RIG cameras.
  69263. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  69264. */
  69265. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  69266. var _this = this;
  69267. //WebVR 1.1
  69268. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  69269. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  69270. if (!this.getScene().useRightHandedSystem) {
  69271. [2, 6, 8, 9, 14].forEach(function (num) {
  69272. _this._webvrViewMatrix.m[num] *= -1;
  69273. });
  69274. }
  69275. // update the camera rotation matrix
  69276. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  69277. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  69278. // Computing target and final matrix
  69279. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  69280. var parentCamera = this._cameraRigParams["parentCamera"];
  69281. // should the view matrix be updated with scale and position offset?
  69282. if (parentCamera.deviceScaleFactor !== 1) {
  69283. this._webvrViewMatrix.invert();
  69284. // scale the position, if set
  69285. if (parentCamera.deviceScaleFactor) {
  69286. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  69287. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  69288. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  69289. }
  69290. this._webvrViewMatrix.invert();
  69291. }
  69292. return this._webvrViewMatrix;
  69293. };
  69294. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  69295. var _this = this;
  69296. var parentCamera = this.parent;
  69297. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  69298. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  69299. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  69300. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  69301. //babylon compatible matrix
  69302. if (!this.getScene().useRightHandedSystem) {
  69303. [8, 9, 10, 11].forEach(function (num) {
  69304. _this._projectionMatrix.m[num] *= -1;
  69305. });
  69306. }
  69307. return this._projectionMatrix;
  69308. };
  69309. WebVRFreeCamera.prototype.initControllers = function () {
  69310. var _this = this;
  69311. this.controllers = [];
  69312. var manager = this.getScene().gamepadManager;
  69313. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69314. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69315. var webVrController = gamepad;
  69316. if (webVrController.defaultModel) {
  69317. webVrController.defaultModel.setEnabled(false);
  69318. }
  69319. }
  69320. });
  69321. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69322. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69323. var webVrController_1 = gamepad;
  69324. if (_this.webVROptions.controllerMeshes) {
  69325. if (webVrController_1.defaultModel) {
  69326. webVrController_1.defaultModel.setEnabled(true);
  69327. }
  69328. else {
  69329. // Load the meshes
  69330. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  69331. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  69332. if (_this.webVROptions.defaultLightingOnControllers) {
  69333. if (!_this._lightOnControllers) {
  69334. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  69335. }
  69336. var activateLightOnSubMeshes_1 = function (mesh, light) {
  69337. var children = mesh.getChildren();
  69338. if (children.length !== 0) {
  69339. children.forEach(function (mesh) {
  69340. light.includedOnlyMeshes.push(mesh);
  69341. activateLightOnSubMeshes_1(mesh, light);
  69342. });
  69343. }
  69344. };
  69345. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  69346. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  69347. }
  69348. });
  69349. }
  69350. }
  69351. webVrController_1.attachToPoseControlledCamera(_this);
  69352. // since this is async - sanity check. Is the controller already stored?
  69353. if (_this.controllers.indexOf(webVrController_1) === -1) {
  69354. //add to the controllers array
  69355. _this.controllers.push(webVrController_1);
  69356. //did we find enough controllers? Great! let the developer know.
  69357. if (_this.controllers.length >= 2) {
  69358. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  69359. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  69360. // So we're overriding setting left & right manually to be sure
  69361. var firstViveWandDetected = false;
  69362. for (var i = 0; i < _this.controllers.length; i++) {
  69363. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  69364. if (!firstViveWandDetected) {
  69365. firstViveWandDetected = true;
  69366. _this.controllers[i].hand = "left";
  69367. }
  69368. else {
  69369. _this.controllers[i].hand = "right";
  69370. }
  69371. }
  69372. }
  69373. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  69374. }
  69375. }
  69376. }
  69377. });
  69378. };
  69379. return WebVRFreeCamera;
  69380. }(BABYLON.FreeCamera));
  69381. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  69382. })(BABYLON || (BABYLON = {}));
  69383. //# sourceMappingURL=babylon.webVRCamera.js.map
  69384. var BABYLON;
  69385. (function (BABYLON) {
  69386. // We're mainly based on the logic defined into the FreeCamera code
  69387. var DeviceOrientationCamera = /** @class */ (function (_super) {
  69388. __extends(DeviceOrientationCamera, _super);
  69389. function DeviceOrientationCamera(name, position, scene) {
  69390. var _this = _super.call(this, name, position, scene) || this;
  69391. _this._quaternionCache = new BABYLON.Quaternion();
  69392. _this.inputs.addDeviceOrientation();
  69393. return _this;
  69394. }
  69395. DeviceOrientationCamera.prototype.getClassName = function () {
  69396. return "DeviceOrientationCamera";
  69397. };
  69398. DeviceOrientationCamera.prototype._checkInputs = function () {
  69399. _super.prototype._checkInputs.call(this);
  69400. this._quaternionCache.copyFrom(this.rotationQuaternion);
  69401. if (this._initialQuaternion) {
  69402. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69403. }
  69404. };
  69405. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  69406. var _this = this;
  69407. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  69408. //can only work if this camera has a rotation quaternion already.
  69409. if (!this.rotationQuaternion)
  69410. return;
  69411. if (!this._initialQuaternion) {
  69412. this._initialQuaternion = new BABYLON.Quaternion();
  69413. }
  69414. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  69415. ['x', 'y', 'z'].forEach(function (axisName) {
  69416. if (!axis[axisName]) {
  69417. _this._initialQuaternion[axisName] = 0;
  69418. }
  69419. else {
  69420. _this._initialQuaternion[axisName] *= -1;
  69421. }
  69422. });
  69423. this._initialQuaternion.normalize();
  69424. //force rotation update
  69425. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69426. };
  69427. return DeviceOrientationCamera;
  69428. }(BABYLON.FreeCamera));
  69429. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  69430. })(BABYLON || (BABYLON = {}));
  69431. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  69432. var BABYLON;
  69433. (function (BABYLON) {
  69434. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  69435. __extends(VRDeviceOrientationFreeCamera, _super);
  69436. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69437. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69438. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69439. var _this = _super.call(this, name, position, scene) || this;
  69440. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69441. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69442. return _this;
  69443. }
  69444. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  69445. return "VRDeviceOrientationFreeCamera";
  69446. };
  69447. return VRDeviceOrientationFreeCamera;
  69448. }(BABYLON.DeviceOrientationCamera));
  69449. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  69450. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  69451. __extends(VRDeviceOrientationGamepadCamera, _super);
  69452. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69453. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69454. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69455. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  69456. _this.inputs.addGamepad();
  69457. return _this;
  69458. }
  69459. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  69460. return "VRDeviceOrientationGamepadCamera";
  69461. };
  69462. return VRDeviceOrientationGamepadCamera;
  69463. }(VRDeviceOrientationFreeCamera));
  69464. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  69465. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  69466. __extends(VRDeviceOrientationArcRotateCamera, _super);
  69467. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  69468. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69469. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69470. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69471. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69472. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69473. _this.inputs.addVRDeviceOrientation();
  69474. return _this;
  69475. }
  69476. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  69477. return "VRDeviceOrientationArcRotateCamera";
  69478. };
  69479. return VRDeviceOrientationArcRotateCamera;
  69480. }(BABYLON.ArcRotateCamera));
  69481. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  69482. })(BABYLON || (BABYLON = {}));
  69483. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  69484. var BABYLON;
  69485. (function (BABYLON) {
  69486. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  69487. __extends(AnaglyphFreeCamera, _super);
  69488. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  69489. var _this = _super.call(this, name, position, scene) || this;
  69490. _this.interaxialDistance = interaxialDistance;
  69491. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69492. return _this;
  69493. }
  69494. AnaglyphFreeCamera.prototype.getClassName = function () {
  69495. return "AnaglyphFreeCamera";
  69496. };
  69497. return AnaglyphFreeCamera;
  69498. }(BABYLON.FreeCamera));
  69499. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  69500. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  69501. __extends(AnaglyphArcRotateCamera, _super);
  69502. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  69503. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69504. _this.interaxialDistance = interaxialDistance;
  69505. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69506. return _this;
  69507. }
  69508. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  69509. return "AnaglyphArcRotateCamera";
  69510. };
  69511. return AnaglyphArcRotateCamera;
  69512. }(BABYLON.ArcRotateCamera));
  69513. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  69514. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  69515. __extends(AnaglyphGamepadCamera, _super);
  69516. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  69517. var _this = _super.call(this, name, position, scene) || this;
  69518. _this.interaxialDistance = interaxialDistance;
  69519. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69520. return _this;
  69521. }
  69522. AnaglyphGamepadCamera.prototype.getClassName = function () {
  69523. return "AnaglyphGamepadCamera";
  69524. };
  69525. return AnaglyphGamepadCamera;
  69526. }(BABYLON.GamepadCamera));
  69527. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  69528. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  69529. __extends(AnaglyphUniversalCamera, _super);
  69530. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  69531. var _this = _super.call(this, name, position, scene) || this;
  69532. _this.interaxialDistance = interaxialDistance;
  69533. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69534. return _this;
  69535. }
  69536. AnaglyphUniversalCamera.prototype.getClassName = function () {
  69537. return "AnaglyphUniversalCamera";
  69538. };
  69539. return AnaglyphUniversalCamera;
  69540. }(BABYLON.UniversalCamera));
  69541. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  69542. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  69543. __extends(StereoscopicFreeCamera, _super);
  69544. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69545. var _this = _super.call(this, name, position, scene) || this;
  69546. _this.interaxialDistance = interaxialDistance;
  69547. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69548. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69549. return _this;
  69550. }
  69551. StereoscopicFreeCamera.prototype.getClassName = function () {
  69552. return "StereoscopicFreeCamera";
  69553. };
  69554. return StereoscopicFreeCamera;
  69555. }(BABYLON.FreeCamera));
  69556. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  69557. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  69558. __extends(StereoscopicArcRotateCamera, _super);
  69559. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  69560. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69561. _this.interaxialDistance = interaxialDistance;
  69562. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69563. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69564. return _this;
  69565. }
  69566. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  69567. return "StereoscopicArcRotateCamera";
  69568. };
  69569. return StereoscopicArcRotateCamera;
  69570. }(BABYLON.ArcRotateCamera));
  69571. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  69572. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  69573. __extends(StereoscopicGamepadCamera, _super);
  69574. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69575. var _this = _super.call(this, name, position, scene) || this;
  69576. _this.interaxialDistance = interaxialDistance;
  69577. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69578. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69579. return _this;
  69580. }
  69581. StereoscopicGamepadCamera.prototype.getClassName = function () {
  69582. return "StereoscopicGamepadCamera";
  69583. };
  69584. return StereoscopicGamepadCamera;
  69585. }(BABYLON.GamepadCamera));
  69586. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  69587. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  69588. __extends(StereoscopicUniversalCamera, _super);
  69589. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69590. var _this = _super.call(this, name, position, scene) || this;
  69591. _this.interaxialDistance = interaxialDistance;
  69592. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69593. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69594. return _this;
  69595. }
  69596. StereoscopicUniversalCamera.prototype.getClassName = function () {
  69597. return "StereoscopicUniversalCamera";
  69598. };
  69599. return StereoscopicUniversalCamera;
  69600. }(BABYLON.UniversalCamera));
  69601. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  69602. })(BABYLON || (BABYLON = {}));
  69603. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  69604. var BABYLON;
  69605. (function (BABYLON) {
  69606. var VRExperienceHelper = /** @class */ (function () {
  69607. function VRExperienceHelper(scene, webVROptions) {
  69608. if (webVROptions === void 0) { webVROptions = {}; }
  69609. var _this = this;
  69610. this.webVROptions = webVROptions;
  69611. // Can the system support WebVR, even if a headset isn't plugged in?
  69612. this._webVRsupported = false;
  69613. // If WebVR is supported, is a headset plugged in and are we ready to present?
  69614. this._webVRready = false;
  69615. // Are we waiting for the requestPresent callback to complete?
  69616. this._webVRrequesting = false;
  69617. // Are we presenting to the headset right now?
  69618. this._webVRpresenting = false;
  69619. // Are we presenting in the fullscreen fallback?
  69620. this._fullscreenVRpresenting = false;
  69621. this._scene = scene;
  69622. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  69623. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  69624. }
  69625. else {
  69626. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  69627. if (scene.activeCamera.rotation) {
  69628. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  69629. }
  69630. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  69631. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  69632. }
  69633. this._scene.activeCamera = this._deviceOrientationCamera;
  69634. this._position = this._scene.activeCamera.position;
  69635. this._canvas = scene.getEngine().getRenderingCanvas();
  69636. if (this._canvas) {
  69637. this._scene.activeCamera.attachControl(this._canvas);
  69638. }
  69639. this._btnVR = document.createElement("BUTTON");
  69640. this._btnVR.className = "babylonVRicon";
  69641. this._btnVR.id = "babylonVRiconbtn";
  69642. this._btnVR.title = "Click to switch to VR";
  69643. 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) }";
  69644. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  69645. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  69646. // css += ".babylonVRicon.vrdisplaysupported { }";
  69647. // css += ".babylonVRicon.vrdisplayready { }";
  69648. // css += ".babylonVRicon.vrdisplayrequesting { }";
  69649. var style = document.createElement('style');
  69650. style.appendChild(document.createTextNode(css));
  69651. document.getElementsByTagName('head')[0].appendChild(style);
  69652. if (this._canvas) {
  69653. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69654. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69655. this._btnVR.addEventListener("click", function () {
  69656. _this.enterVR();
  69657. });
  69658. window.addEventListener("resize", function () {
  69659. if (_this._canvas) {
  69660. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  69661. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  69662. }
  69663. if (_this._fullscreenVRpresenting && _this._webVRready) {
  69664. _this.exitVR();
  69665. }
  69666. });
  69667. }
  69668. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69669. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69670. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69671. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69672. document.body.appendChild(this._btnVR);
  69673. // Exiting VR mode using 'ESC' key on desktop
  69674. this._onKeyDown = function (event) {
  69675. if (event.keyCode === 27 && _this.isInVRMode()) {
  69676. _this.exitVR();
  69677. }
  69678. };
  69679. document.addEventListener("keydown", this._onKeyDown);
  69680. // Exiting VR mode double tapping the touch screen
  69681. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  69682. if (_this.isInVRMode()) {
  69683. _this.exitVR();
  69684. if (_this._fullscreenVRpresenting) {
  69685. _this._scene.getEngine().switchFullscreen(true);
  69686. }
  69687. }
  69688. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  69689. // Listen for WebVR display changes
  69690. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  69691. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  69692. this._onVRRequestPresentStart = function () {
  69693. _this._webVRrequesting = true;
  69694. _this.updateButtonVisibility();
  69695. };
  69696. this._onVRRequestPresentComplete = function (success) {
  69697. _this._webVRrequesting = false;
  69698. _this.updateButtonVisibility();
  69699. };
  69700. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  69701. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  69702. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  69703. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69704. // Create the cameras
  69705. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  69706. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  69707. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  69708. this.updateButtonVisibility();
  69709. }
  69710. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  69711. if (this.onControllerMeshLoaded) {
  69712. this.onControllerMeshLoaded(webVRController);
  69713. }
  69714. };
  69715. VRExperienceHelper.prototype._onFullscreenChange = function () {
  69716. if (document.fullscreen !== undefined) {
  69717. this._fullscreenVRpresenting = document.fullscreen;
  69718. }
  69719. else if (document.mozFullScreen !== undefined) {
  69720. this._fullscreenVRpresenting = document.mozFullScreen;
  69721. }
  69722. else if (document.webkitIsFullScreen !== undefined) {
  69723. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  69724. }
  69725. else if (document.msIsFullScreen !== undefined) {
  69726. this._fullscreenVRpresenting = document.msIsFullScreen;
  69727. }
  69728. if (!this._fullscreenVRpresenting && this._canvas) {
  69729. this.exitVR();
  69730. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69731. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69732. }
  69733. };
  69734. VRExperienceHelper.prototype.isInVRMode = function () {
  69735. return this._webVRpresenting || this._fullscreenVRpresenting;
  69736. };
  69737. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  69738. var vrDisplay = this._scene.getEngine().getVRDevice();
  69739. if (vrDisplay) {
  69740. var wasPresenting = this._webVRpresenting;
  69741. // A VR display is connected
  69742. this._webVRpresenting = vrDisplay.isPresenting;
  69743. if (wasPresenting && !this._webVRpresenting)
  69744. this.exitVR();
  69745. }
  69746. else {
  69747. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  69748. }
  69749. this.updateButtonVisibility();
  69750. };
  69751. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  69752. this._webVRsupported = eventArgs.vrSupported;
  69753. this._webVRready = !!eventArgs.vrDisplay;
  69754. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  69755. this.updateButtonVisibility();
  69756. };
  69757. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  69758. if (!this._btnVR) {
  69759. return;
  69760. }
  69761. this._btnVR.className = "babylonVRicon";
  69762. if (this.isInVRMode()) {
  69763. this._btnVR.className += " vrdisplaypresenting";
  69764. }
  69765. else {
  69766. if (this._webVRready)
  69767. this._btnVR.className += " vrdisplayready";
  69768. if (this._webVRsupported)
  69769. this._btnVR.className += " vrdisplaysupported";
  69770. if (this._webVRrequesting)
  69771. this._btnVR.className += " vrdisplayrequesting";
  69772. }
  69773. };
  69774. /**
  69775. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  69776. * Otherwise, will use the fullscreen API.
  69777. */
  69778. VRExperienceHelper.prototype.enterVR = function () {
  69779. if (this.onEnteringVR) {
  69780. this.onEnteringVR();
  69781. }
  69782. if (this._webVRrequesting)
  69783. return;
  69784. // If WebVR is supported and a headset is connected
  69785. if (this._webVRready) {
  69786. if (!this._webVRpresenting) {
  69787. this._webVRCamera.position = this._position;
  69788. this._scene.activeCamera = this._webVRCamera;
  69789. }
  69790. }
  69791. else {
  69792. this._vrDeviceOrientationCamera.position = this._position;
  69793. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  69794. this._scene.getEngine().switchFullscreen(true);
  69795. this.updateButtonVisibility();
  69796. }
  69797. if (this._scene.activeCamera && this._canvas) {
  69798. this._scene.activeCamera.attachControl(this._canvas);
  69799. }
  69800. };
  69801. /**
  69802. * Attempt to exit VR, or fullscreen.
  69803. */
  69804. VRExperienceHelper.prototype.exitVR = function () {
  69805. if (this.onExitingVR) {
  69806. this.onExitingVR();
  69807. }
  69808. if (this._webVRpresenting) {
  69809. this._scene.getEngine().disableVR();
  69810. }
  69811. if (this._scene.activeCamera) {
  69812. this._position = this._scene.activeCamera.position;
  69813. }
  69814. this._deviceOrientationCamera.position = this._position;
  69815. this._scene.activeCamera = this._deviceOrientationCamera;
  69816. if (this._canvas) {
  69817. this._scene.activeCamera.attachControl(this._canvas);
  69818. }
  69819. this.updateButtonVisibility();
  69820. };
  69821. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  69822. get: function () {
  69823. return this._position;
  69824. },
  69825. set: function (value) {
  69826. this._position = value;
  69827. if (this._scene.activeCamera) {
  69828. this._scene.activeCamera.position = value;
  69829. }
  69830. },
  69831. enumerable: true,
  69832. configurable: true
  69833. });
  69834. VRExperienceHelper.prototype.dispose = function () {
  69835. if (this.isInVRMode()) {
  69836. this.exitVR();
  69837. }
  69838. this._deviceOrientationCamera.dispose();
  69839. if (this._webVRCamera) {
  69840. this._webVRCamera.dispose();
  69841. }
  69842. if (this._vrDeviceOrientationCamera) {
  69843. this._vrDeviceOrientationCamera.dispose();
  69844. }
  69845. document.body.removeChild(this._btnVR);
  69846. document.removeEventListener("keydown", this._onKeyDown);
  69847. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69848. };
  69849. VRExperienceHelper.prototype.getClassName = function () {
  69850. return "VRExperienceHelper";
  69851. };
  69852. return VRExperienceHelper;
  69853. }());
  69854. BABYLON.VRExperienceHelper = VRExperienceHelper;
  69855. })(BABYLON || (BABYLON = {}));
  69856. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  69857. // Mainly based on these 2 articles :
  69858. // 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
  69859. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  69860. var BABYLON;
  69861. (function (BABYLON) {
  69862. var JoystickAxis;
  69863. (function (JoystickAxis) {
  69864. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  69865. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  69866. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  69867. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  69868. var VirtualJoystick = /** @class */ (function () {
  69869. function VirtualJoystick(leftJoystick) {
  69870. var _this = this;
  69871. if (leftJoystick) {
  69872. this._leftJoystick = true;
  69873. }
  69874. else {
  69875. this._leftJoystick = false;
  69876. }
  69877. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  69878. VirtualJoystick._globalJoystickIndex++;
  69879. // By default left & right arrow keys are moving the X
  69880. // and up & down keys are moving the Y
  69881. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  69882. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  69883. this.reverseLeftRight = false;
  69884. this.reverseUpDown = false;
  69885. // collections of pointers
  69886. this._touches = new BABYLON.StringDictionary();
  69887. this.deltaPosition = BABYLON.Vector3.Zero();
  69888. this._joystickSensibility = 25;
  69889. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  69890. this._rotationSpeed = 25;
  69891. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  69892. this._rotateOnAxisRelativeToMesh = false;
  69893. this._onResize = function (evt) {
  69894. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  69895. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  69896. if (VirtualJoystick.vjCanvas) {
  69897. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  69898. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  69899. }
  69900. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  69901. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  69902. };
  69903. // injecting a canvas element on top of the canvas 3D game
  69904. if (!VirtualJoystick.vjCanvas) {
  69905. window.addEventListener("resize", this._onResize, false);
  69906. VirtualJoystick.vjCanvas = document.createElement("canvas");
  69907. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  69908. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  69909. VirtualJoystick.vjCanvas.width = window.innerWidth;
  69910. VirtualJoystick.vjCanvas.height = window.innerHeight;
  69911. VirtualJoystick.vjCanvas.style.width = "100%";
  69912. VirtualJoystick.vjCanvas.style.height = "100%";
  69913. VirtualJoystick.vjCanvas.style.position = "absolute";
  69914. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  69915. VirtualJoystick.vjCanvas.style.top = "0px";
  69916. VirtualJoystick.vjCanvas.style.left = "0px";
  69917. VirtualJoystick.vjCanvas.style.zIndex = "5";
  69918. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  69919. // Support for jQuery PEP polyfill
  69920. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  69921. var context = VirtualJoystick.vjCanvas.getContext('2d');
  69922. if (!context) {
  69923. throw new Error("Unable to create canvas for virtual joystick");
  69924. }
  69925. VirtualJoystick.vjCanvasContext = context;
  69926. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  69927. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  69928. document.body.appendChild(VirtualJoystick.vjCanvas);
  69929. }
  69930. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  69931. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  69932. this.pressed = false;
  69933. // default joystick color
  69934. this._joystickColor = "cyan";
  69935. this._joystickPointerID = -1;
  69936. // current joystick position
  69937. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  69938. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  69939. // origin joystick position
  69940. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  69941. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  69942. this._onPointerDownHandlerRef = function (evt) {
  69943. _this._onPointerDown(evt);
  69944. };
  69945. this._onPointerMoveHandlerRef = function (evt) {
  69946. _this._onPointerMove(evt);
  69947. };
  69948. this._onPointerOutHandlerRef = function (evt) {
  69949. _this._onPointerUp(evt);
  69950. };
  69951. this._onPointerUpHandlerRef = function (evt) {
  69952. _this._onPointerUp(evt);
  69953. };
  69954. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  69955. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  69956. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  69957. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  69958. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  69959. evt.preventDefault(); // Disables system menu
  69960. }, false);
  69961. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  69962. }
  69963. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  69964. this._joystickSensibility = newJoystickSensibility;
  69965. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  69966. };
  69967. VirtualJoystick.prototype._onPointerDown = function (e) {
  69968. var positionOnScreenCondition;
  69969. e.preventDefault();
  69970. if (this._leftJoystick === true) {
  69971. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  69972. }
  69973. else {
  69974. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  69975. }
  69976. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  69977. // First contact will be dedicated to the virtual joystick
  69978. this._joystickPointerID = e.pointerId;
  69979. this._joystickPointerStartPos.x = e.clientX;
  69980. this._joystickPointerStartPos.y = e.clientY;
  69981. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  69982. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  69983. this._deltaJoystickVector.x = 0;
  69984. this._deltaJoystickVector.y = 0;
  69985. this.pressed = true;
  69986. this._touches.add(e.pointerId.toString(), e);
  69987. }
  69988. else {
  69989. // You can only trigger the action buttons with a joystick declared
  69990. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  69991. this._action();
  69992. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  69993. }
  69994. }
  69995. };
  69996. VirtualJoystick.prototype._onPointerMove = function (e) {
  69997. // If the current pointer is the one associated to the joystick (first touch contact)
  69998. if (this._joystickPointerID == e.pointerId) {
  69999. this._joystickPointerPos.x = e.clientX;
  70000. this._joystickPointerPos.y = e.clientY;
  70001. this._deltaJoystickVector = this._joystickPointerPos.clone();
  70002. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  70003. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  70004. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  70005. switch (this._axisTargetedByLeftAndRight) {
  70006. case JoystickAxis.X:
  70007. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  70008. break;
  70009. case JoystickAxis.Y:
  70010. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  70011. break;
  70012. case JoystickAxis.Z:
  70013. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  70014. break;
  70015. }
  70016. var directionUpDown = this.reverseUpDown ? 1 : -1;
  70017. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  70018. switch (this._axisTargetedByUpAndDown) {
  70019. case JoystickAxis.X:
  70020. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  70021. break;
  70022. case JoystickAxis.Y:
  70023. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  70024. break;
  70025. case JoystickAxis.Z:
  70026. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  70027. break;
  70028. }
  70029. }
  70030. else {
  70031. var data = this._touches.get(e.pointerId.toString());
  70032. if (data) {
  70033. data.x = e.clientX;
  70034. data.y = e.clientY;
  70035. }
  70036. }
  70037. };
  70038. VirtualJoystick.prototype._onPointerUp = function (e) {
  70039. if (this._joystickPointerID == e.pointerId) {
  70040. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  70041. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  70042. this._joystickPointerID = -1;
  70043. this.pressed = false;
  70044. }
  70045. else {
  70046. var touch = this._touches.get(e.pointerId.toString());
  70047. if (touch) {
  70048. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70049. }
  70050. }
  70051. this._deltaJoystickVector.x = 0;
  70052. this._deltaJoystickVector.y = 0;
  70053. this._touches.remove(e.pointerId.toString());
  70054. };
  70055. /**
  70056. * Change the color of the virtual joystick
  70057. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  70058. */
  70059. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  70060. this._joystickColor = newColor;
  70061. };
  70062. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  70063. this._action = action;
  70064. };
  70065. // Define which axis you'd like to control for left & right
  70066. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  70067. switch (axis) {
  70068. case JoystickAxis.X:
  70069. case JoystickAxis.Y:
  70070. case JoystickAxis.Z:
  70071. this._axisTargetedByLeftAndRight = axis;
  70072. break;
  70073. default:
  70074. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70075. break;
  70076. }
  70077. };
  70078. // Define which axis you'd like to control for up & down
  70079. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  70080. switch (axis) {
  70081. case JoystickAxis.X:
  70082. case JoystickAxis.Y:
  70083. case JoystickAxis.Z:
  70084. this._axisTargetedByUpAndDown = axis;
  70085. break;
  70086. default:
  70087. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70088. break;
  70089. }
  70090. };
  70091. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  70092. var _this = this;
  70093. if (this.pressed) {
  70094. this._touches.forEach(function (key, touch) {
  70095. if (touch.pointerId === _this._joystickPointerID) {
  70096. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  70097. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  70098. VirtualJoystick.vjCanvasContext.beginPath();
  70099. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70100. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70101. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  70102. VirtualJoystick.vjCanvasContext.stroke();
  70103. VirtualJoystick.vjCanvasContext.closePath();
  70104. VirtualJoystick.vjCanvasContext.beginPath();
  70105. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70106. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70107. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  70108. VirtualJoystick.vjCanvasContext.stroke();
  70109. VirtualJoystick.vjCanvasContext.closePath();
  70110. VirtualJoystick.vjCanvasContext.beginPath();
  70111. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70112. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  70113. VirtualJoystick.vjCanvasContext.stroke();
  70114. VirtualJoystick.vjCanvasContext.closePath();
  70115. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  70116. }
  70117. else {
  70118. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70119. VirtualJoystick.vjCanvasContext.beginPath();
  70120. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  70121. VirtualJoystick.vjCanvasContext.beginPath();
  70122. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  70123. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70124. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  70125. VirtualJoystick.vjCanvasContext.stroke();
  70126. VirtualJoystick.vjCanvasContext.closePath();
  70127. touch.prevX = touch.x;
  70128. touch.prevY = touch.y;
  70129. }
  70130. ;
  70131. });
  70132. }
  70133. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70134. };
  70135. VirtualJoystick.prototype.releaseCanvas = function () {
  70136. if (VirtualJoystick.vjCanvas) {
  70137. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  70138. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  70139. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  70140. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  70141. window.removeEventListener("resize", this._onResize);
  70142. document.body.removeChild(VirtualJoystick.vjCanvas);
  70143. VirtualJoystick.vjCanvas = null;
  70144. }
  70145. };
  70146. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  70147. VirtualJoystick._globalJoystickIndex = 0;
  70148. return VirtualJoystick;
  70149. }());
  70150. BABYLON.VirtualJoystick = VirtualJoystick;
  70151. })(BABYLON || (BABYLON = {}));
  70152. //# sourceMappingURL=babylon.virtualJoystick.js.map
  70153. var BABYLON;
  70154. (function (BABYLON) {
  70155. // We're mainly based on the logic defined into the FreeCamera code
  70156. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  70157. __extends(VirtualJoysticksCamera, _super);
  70158. function VirtualJoysticksCamera(name, position, scene) {
  70159. var _this = _super.call(this, name, position, scene) || this;
  70160. _this.inputs.addVirtualJoystick();
  70161. return _this;
  70162. }
  70163. VirtualJoysticksCamera.prototype.getClassName = function () {
  70164. return "VirtualJoysticksCamera";
  70165. };
  70166. return VirtualJoysticksCamera;
  70167. }(BABYLON.FreeCamera));
  70168. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  70169. })(BABYLON || (BABYLON = {}));
  70170. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  70171. var BABYLON;
  70172. (function (BABYLON) {
  70173. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  70174. function FreeCameraVirtualJoystickInput() {
  70175. }
  70176. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  70177. return this._leftjoystick;
  70178. };
  70179. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  70180. return this._rightjoystick;
  70181. };
  70182. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  70183. if (this._leftjoystick) {
  70184. var camera = this.camera;
  70185. var speed = camera._computeLocalCameraSpeed() * 50;
  70186. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  70187. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  70188. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  70189. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  70190. if (!this._leftjoystick.pressed) {
  70191. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  70192. }
  70193. if (!this._rightjoystick.pressed) {
  70194. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  70195. }
  70196. }
  70197. };
  70198. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  70199. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  70200. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  70201. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  70202. this._leftjoystick.setJoystickSensibility(0.15);
  70203. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  70204. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  70205. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  70206. this._rightjoystick.reverseUpDown = true;
  70207. this._rightjoystick.setJoystickSensibility(0.05);
  70208. this._rightjoystick.setJoystickColor("yellow");
  70209. };
  70210. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  70211. this._leftjoystick.releaseCanvas();
  70212. this._rightjoystick.releaseCanvas();
  70213. };
  70214. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  70215. return "FreeCameraVirtualJoystickInput";
  70216. };
  70217. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  70218. return "virtualJoystick";
  70219. };
  70220. return FreeCameraVirtualJoystickInput;
  70221. }());
  70222. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  70223. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  70224. })(BABYLON || (BABYLON = {}));
  70225. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  70226. var BABYLON;
  70227. (function (BABYLON) {
  70228. var SimplificationSettings = /** @class */ (function () {
  70229. function SimplificationSettings(quality, distance, optimizeMesh) {
  70230. this.quality = quality;
  70231. this.distance = distance;
  70232. this.optimizeMesh = optimizeMesh;
  70233. }
  70234. return SimplificationSettings;
  70235. }());
  70236. BABYLON.SimplificationSettings = SimplificationSettings;
  70237. var SimplificationQueue = /** @class */ (function () {
  70238. function SimplificationQueue() {
  70239. this.running = false;
  70240. this._simplificationArray = [];
  70241. }
  70242. SimplificationQueue.prototype.addTask = function (task) {
  70243. this._simplificationArray.push(task);
  70244. };
  70245. SimplificationQueue.prototype.executeNext = function () {
  70246. var task = this._simplificationArray.pop();
  70247. if (task) {
  70248. this.running = true;
  70249. this.runSimplification(task);
  70250. }
  70251. else {
  70252. this.running = false;
  70253. }
  70254. };
  70255. SimplificationQueue.prototype.runSimplification = function (task) {
  70256. var _this = this;
  70257. if (task.parallelProcessing) {
  70258. //parallel simplifier
  70259. task.settings.forEach(function (setting) {
  70260. var simplifier = _this.getSimplifier(task);
  70261. simplifier.simplify(setting, function (newMesh) {
  70262. task.mesh.addLODLevel(setting.distance, newMesh);
  70263. newMesh.isVisible = true;
  70264. //check if it is the last
  70265. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  70266. //all done, run the success callback.
  70267. task.successCallback();
  70268. }
  70269. _this.executeNext();
  70270. });
  70271. });
  70272. }
  70273. else {
  70274. //single simplifier.
  70275. var simplifier = this.getSimplifier(task);
  70276. var runDecimation = function (setting, callback) {
  70277. simplifier.simplify(setting, function (newMesh) {
  70278. task.mesh.addLODLevel(setting.distance, newMesh);
  70279. newMesh.isVisible = true;
  70280. //run the next quality level
  70281. callback();
  70282. });
  70283. };
  70284. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  70285. runDecimation(task.settings[loop.index], function () {
  70286. loop.executeNext();
  70287. });
  70288. }, function () {
  70289. //execution ended, run the success callback.
  70290. if (task.successCallback) {
  70291. task.successCallback();
  70292. }
  70293. _this.executeNext();
  70294. });
  70295. }
  70296. };
  70297. SimplificationQueue.prototype.getSimplifier = function (task) {
  70298. switch (task.simplificationType) {
  70299. case SimplificationType.QUADRATIC:
  70300. default:
  70301. return new QuadraticErrorSimplification(task.mesh);
  70302. }
  70303. };
  70304. return SimplificationQueue;
  70305. }());
  70306. BABYLON.SimplificationQueue = SimplificationQueue;
  70307. /**
  70308. * The implemented types of simplification.
  70309. * At the moment only Quadratic Error Decimation is implemented.
  70310. */
  70311. var SimplificationType;
  70312. (function (SimplificationType) {
  70313. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  70314. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  70315. var DecimationTriangle = /** @class */ (function () {
  70316. function DecimationTriangle(vertices) {
  70317. this.vertices = vertices;
  70318. this.error = new Array(4);
  70319. this.deleted = false;
  70320. this.isDirty = false;
  70321. this.deletePending = false;
  70322. this.borderFactor = 0;
  70323. }
  70324. return DecimationTriangle;
  70325. }());
  70326. BABYLON.DecimationTriangle = DecimationTriangle;
  70327. var DecimationVertex = /** @class */ (function () {
  70328. function DecimationVertex(position, id) {
  70329. this.position = position;
  70330. this.id = id;
  70331. this.isBorder = true;
  70332. this.q = new QuadraticMatrix();
  70333. this.triangleCount = 0;
  70334. this.triangleStart = 0;
  70335. this.originalOffsets = [];
  70336. }
  70337. DecimationVertex.prototype.updatePosition = function (newPosition) {
  70338. this.position.copyFrom(newPosition);
  70339. };
  70340. return DecimationVertex;
  70341. }());
  70342. BABYLON.DecimationVertex = DecimationVertex;
  70343. var QuadraticMatrix = /** @class */ (function () {
  70344. function QuadraticMatrix(data) {
  70345. this.data = new Array(10);
  70346. for (var i = 0; i < 10; ++i) {
  70347. if (data && data[i]) {
  70348. this.data[i] = data[i];
  70349. }
  70350. else {
  70351. this.data[i] = 0;
  70352. }
  70353. }
  70354. }
  70355. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  70356. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  70357. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  70358. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  70359. return det;
  70360. };
  70361. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  70362. for (var i = 0; i < 10; ++i) {
  70363. this.data[i] += matrix.data[i];
  70364. }
  70365. };
  70366. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  70367. for (var i = 0; i < 10; ++i) {
  70368. this.data[i] += data[i];
  70369. }
  70370. };
  70371. QuadraticMatrix.prototype.add = function (matrix) {
  70372. var m = new QuadraticMatrix();
  70373. for (var i = 0; i < 10; ++i) {
  70374. m.data[i] = this.data[i] + matrix.data[i];
  70375. }
  70376. return m;
  70377. };
  70378. QuadraticMatrix.FromData = function (a, b, c, d) {
  70379. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  70380. };
  70381. //returning an array to avoid garbage collection
  70382. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  70383. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  70384. };
  70385. return QuadraticMatrix;
  70386. }());
  70387. BABYLON.QuadraticMatrix = QuadraticMatrix;
  70388. var Reference = /** @class */ (function () {
  70389. function Reference(vertexId, triangleId) {
  70390. this.vertexId = vertexId;
  70391. this.triangleId = triangleId;
  70392. }
  70393. return Reference;
  70394. }());
  70395. BABYLON.Reference = Reference;
  70396. /**
  70397. * An implementation of the Quadratic Error simplification algorithm.
  70398. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  70399. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  70400. * @author RaananW
  70401. */
  70402. var QuadraticErrorSimplification = /** @class */ (function () {
  70403. function QuadraticErrorSimplification(_mesh) {
  70404. this._mesh = _mesh;
  70405. this.initialized = false;
  70406. this.syncIterations = 5000;
  70407. this.aggressiveness = 7;
  70408. this.decimationIterations = 100;
  70409. this.boundingBoxEpsilon = BABYLON.Epsilon;
  70410. }
  70411. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  70412. var _this = this;
  70413. this.initDecimatedMesh();
  70414. //iterating through the submeshes array, one after the other.
  70415. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  70416. _this.initWithMesh(loop.index, function () {
  70417. _this.runDecimation(settings, loop.index, function () {
  70418. loop.executeNext();
  70419. });
  70420. }, settings.optimizeMesh);
  70421. }, function () {
  70422. setTimeout(function () {
  70423. successCallback(_this._reconstructedMesh);
  70424. }, 0);
  70425. });
  70426. };
  70427. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  70428. var _this = this;
  70429. var targetCount = ~~(this.triangles.length * settings.quality);
  70430. var deletedTriangles = 0;
  70431. var triangleCount = this.triangles.length;
  70432. var iterationFunction = function (iteration, callback) {
  70433. setTimeout(function () {
  70434. if (iteration % 5 === 0) {
  70435. _this.updateMesh(iteration === 0);
  70436. }
  70437. for (var i = 0; i < _this.triangles.length; ++i) {
  70438. _this.triangles[i].isDirty = false;
  70439. }
  70440. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  70441. var trianglesIterator = function (i) {
  70442. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  70443. var t = _this.triangles[tIdx];
  70444. if (!t)
  70445. return;
  70446. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  70447. return;
  70448. }
  70449. for (var j = 0; j < 3; ++j) {
  70450. if (t.error[j] < threshold) {
  70451. var deleted0 = [];
  70452. var deleted1 = [];
  70453. var v0 = t.vertices[j];
  70454. var v1 = t.vertices[(j + 1) % 3];
  70455. if (v0.isBorder || v1.isBorder)
  70456. continue;
  70457. var p = BABYLON.Vector3.Zero();
  70458. var n = BABYLON.Vector3.Zero();
  70459. var uv = BABYLON.Vector2.Zero();
  70460. var color = new BABYLON.Color4(0, 0, 0, 1);
  70461. _this.calculateError(v0, v1, p, n, uv, color);
  70462. var delTr = new Array();
  70463. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  70464. continue;
  70465. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  70466. continue;
  70467. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  70468. continue;
  70469. var uniqueArray = new Array();
  70470. delTr.forEach(function (deletedT) {
  70471. if (uniqueArray.indexOf(deletedT) === -1) {
  70472. deletedT.deletePending = true;
  70473. uniqueArray.push(deletedT);
  70474. }
  70475. });
  70476. if (uniqueArray.length % 2 !== 0) {
  70477. continue;
  70478. }
  70479. v0.q = v1.q.add(v0.q);
  70480. v0.updatePosition(p);
  70481. var tStart = _this.references.length;
  70482. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  70483. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  70484. var tCount = _this.references.length - tStart;
  70485. if (tCount <= v0.triangleCount) {
  70486. if (tCount) {
  70487. for (var c = 0; c < tCount; c++) {
  70488. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  70489. }
  70490. }
  70491. }
  70492. else {
  70493. v0.triangleStart = tStart;
  70494. }
  70495. v0.triangleCount = tCount;
  70496. break;
  70497. }
  70498. }
  70499. };
  70500. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  70501. }, 0);
  70502. };
  70503. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  70504. if (triangleCount - deletedTriangles <= targetCount)
  70505. loop.breakLoop();
  70506. else {
  70507. iterationFunction(loop.index, function () {
  70508. loop.executeNext();
  70509. });
  70510. }
  70511. }, function () {
  70512. setTimeout(function () {
  70513. //reconstruct this part of the mesh
  70514. _this.reconstructMesh(submeshIndex);
  70515. successCallback();
  70516. }, 0);
  70517. });
  70518. };
  70519. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  70520. var _this = this;
  70521. this.vertices = [];
  70522. this.triangles = [];
  70523. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70524. var indices = this._mesh.getIndices();
  70525. var submesh = this._mesh.subMeshes[submeshIndex];
  70526. var findInVertices = function (positionToSearch) {
  70527. if (optimizeMesh) {
  70528. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  70529. if (_this.vertices[ii].position.equals(positionToSearch)) {
  70530. return _this.vertices[ii];
  70531. }
  70532. }
  70533. }
  70534. return null;
  70535. };
  70536. var vertexReferences = [];
  70537. var vertexInit = function (i) {
  70538. if (!positionData) {
  70539. return;
  70540. }
  70541. var offset = i + submesh.verticesStart;
  70542. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  70543. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  70544. vertex.originalOffsets.push(offset);
  70545. if (vertex.id === _this.vertices.length) {
  70546. _this.vertices.push(vertex);
  70547. }
  70548. vertexReferences.push(vertex.id);
  70549. };
  70550. //var totalVertices = mesh.getTotalVertices();
  70551. var totalVertices = submesh.verticesCount;
  70552. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  70553. var indicesInit = function (i) {
  70554. if (!indices) {
  70555. return;
  70556. }
  70557. var offset = (submesh.indexStart / 3) + i;
  70558. var pos = (offset * 3);
  70559. var i0 = indices[pos + 0];
  70560. var i1 = indices[pos + 1];
  70561. var i2 = indices[pos + 2];
  70562. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  70563. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  70564. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  70565. var triangle = new DecimationTriangle([v0, v1, v2]);
  70566. triangle.originalOffset = pos;
  70567. _this.triangles.push(triangle);
  70568. };
  70569. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  70570. _this.init(callback);
  70571. });
  70572. });
  70573. };
  70574. QuadraticErrorSimplification.prototype.init = function (callback) {
  70575. var _this = this;
  70576. var triangleInit1 = function (i) {
  70577. var t = _this.triangles[i];
  70578. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  70579. for (var j = 0; j < 3; j++) {
  70580. 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))));
  70581. }
  70582. };
  70583. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  70584. var triangleInit2 = function (i) {
  70585. var t = _this.triangles[i];
  70586. for (var j = 0; j < 3; ++j) {
  70587. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  70588. }
  70589. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70590. };
  70591. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  70592. _this.initialized = true;
  70593. callback();
  70594. });
  70595. });
  70596. };
  70597. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  70598. var newTriangles = [];
  70599. var i;
  70600. for (i = 0; i < this.vertices.length; ++i) {
  70601. this.vertices[i].triangleCount = 0;
  70602. }
  70603. var t;
  70604. var j;
  70605. for (i = 0; i < this.triangles.length; ++i) {
  70606. if (!this.triangles[i].deleted) {
  70607. t = this.triangles[i];
  70608. for (j = 0; j < 3; ++j) {
  70609. t.vertices[j].triangleCount = 1;
  70610. }
  70611. newTriangles.push(t);
  70612. }
  70613. }
  70614. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  70615. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  70616. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  70617. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  70618. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70619. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70620. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  70621. var vertexCount = 0;
  70622. for (i = 0; i < this.vertices.length; ++i) {
  70623. var vertex = this.vertices[i];
  70624. vertex.id = vertexCount;
  70625. if (vertex.triangleCount) {
  70626. vertex.originalOffsets.forEach(function (originalOffset) {
  70627. if (!normalData) {
  70628. return;
  70629. }
  70630. newPositionData.push(vertex.position.x);
  70631. newPositionData.push(vertex.position.y);
  70632. newPositionData.push(vertex.position.z);
  70633. newNormalData.push(normalData[originalOffset * 3]);
  70634. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  70635. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  70636. if (uvs && uvs.length) {
  70637. newUVsData.push(uvs[(originalOffset * 2)]);
  70638. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  70639. }
  70640. else if (colorsData && colorsData.length) {
  70641. newColorsData.push(colorsData[(originalOffset * 4)]);
  70642. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  70643. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  70644. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  70645. }
  70646. ++vertexCount;
  70647. });
  70648. }
  70649. }
  70650. var startingIndex = this._reconstructedMesh.getTotalIndices();
  70651. var startingVertex = this._reconstructedMesh.getTotalVertices();
  70652. var submeshesArray = this._reconstructedMesh.subMeshes;
  70653. this._reconstructedMesh.subMeshes = [];
  70654. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  70655. var originalIndices = this._mesh.getIndices();
  70656. for (i = 0; i < newTriangles.length; ++i) {
  70657. t = newTriangles[i]; //now get the new referencing point for each vertex
  70658. [0, 1, 2].forEach(function (idx) {
  70659. var id = originalIndices[t.originalOffset + idx];
  70660. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  70661. if (offset < 0)
  70662. offset = 0;
  70663. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  70664. });
  70665. }
  70666. //overwriting the old vertex buffers and indices.
  70667. this._reconstructedMesh.setIndices(newIndicesArray);
  70668. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  70669. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  70670. if (newUVsData.length > 0)
  70671. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  70672. if (newColorsData.length > 0)
  70673. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  70674. //create submesh
  70675. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  70676. if (submeshIndex > 0) {
  70677. this._reconstructedMesh.subMeshes = [];
  70678. submeshesArray.forEach(function (submesh) {
  70679. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  70680. });
  70681. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  70682. }
  70683. };
  70684. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  70685. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  70686. this._reconstructedMesh.material = this._mesh.material;
  70687. this._reconstructedMesh.parent = this._mesh.parent;
  70688. this._reconstructedMesh.isVisible = false;
  70689. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  70690. };
  70691. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  70692. for (var i = 0; i < vertex1.triangleCount; ++i) {
  70693. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  70694. if (t.deleted)
  70695. continue;
  70696. var s = this.references[vertex1.triangleStart + i].vertexId;
  70697. var v1 = t.vertices[(s + 1) % 3];
  70698. var v2 = t.vertices[(s + 2) % 3];
  70699. if ((v1 === vertex2 || v2 === vertex2)) {
  70700. deletedArray[i] = true;
  70701. delTr.push(t);
  70702. continue;
  70703. }
  70704. var d1 = v1.position.subtract(point);
  70705. d1 = d1.normalize();
  70706. var d2 = v2.position.subtract(point);
  70707. d2 = d2.normalize();
  70708. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  70709. return true;
  70710. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  70711. deletedArray[i] = false;
  70712. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  70713. return true;
  70714. }
  70715. return false;
  70716. };
  70717. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  70718. var newDeleted = deletedTriangles;
  70719. for (var i = 0; i < vertex.triangleCount; ++i) {
  70720. var ref = this.references[vertex.triangleStart + i];
  70721. var t = this.triangles[ref.triangleId];
  70722. if (t.deleted)
  70723. continue;
  70724. if (deletedArray[i] && t.deletePending) {
  70725. t.deleted = true;
  70726. newDeleted++;
  70727. continue;
  70728. }
  70729. t.vertices[ref.vertexId] = origVertex;
  70730. t.isDirty = true;
  70731. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  70732. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  70733. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  70734. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70735. this.references.push(ref);
  70736. }
  70737. return newDeleted;
  70738. };
  70739. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  70740. for (var i = 0; i < this.vertices.length; ++i) {
  70741. var vCount = [];
  70742. var vId = [];
  70743. var v = this.vertices[i];
  70744. var j;
  70745. for (j = 0; j < v.triangleCount; ++j) {
  70746. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  70747. for (var ii = 0; ii < 3; ii++) {
  70748. var ofs = 0;
  70749. var vv = triangle.vertices[ii];
  70750. while (ofs < vCount.length) {
  70751. if (vId[ofs] === vv.id)
  70752. break;
  70753. ++ofs;
  70754. }
  70755. if (ofs === vCount.length) {
  70756. vCount.push(1);
  70757. vId.push(vv.id);
  70758. }
  70759. else {
  70760. vCount[ofs]++;
  70761. }
  70762. }
  70763. }
  70764. for (j = 0; j < vCount.length; ++j) {
  70765. if (vCount[j] === 1) {
  70766. this.vertices[vId[j]].isBorder = true;
  70767. }
  70768. else {
  70769. this.vertices[vId[j]].isBorder = false;
  70770. }
  70771. }
  70772. }
  70773. };
  70774. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  70775. if (identifyBorders === void 0) { identifyBorders = false; }
  70776. var i;
  70777. if (!identifyBorders) {
  70778. var newTrianglesVector = [];
  70779. for (i = 0; i < this.triangles.length; ++i) {
  70780. if (!this.triangles[i].deleted) {
  70781. newTrianglesVector.push(this.triangles[i]);
  70782. }
  70783. }
  70784. this.triangles = newTrianglesVector;
  70785. }
  70786. for (i = 0; i < this.vertices.length; ++i) {
  70787. this.vertices[i].triangleCount = 0;
  70788. this.vertices[i].triangleStart = 0;
  70789. }
  70790. var t;
  70791. var j;
  70792. var v;
  70793. for (i = 0; i < this.triangles.length; ++i) {
  70794. t = this.triangles[i];
  70795. for (j = 0; j < 3; ++j) {
  70796. v = t.vertices[j];
  70797. v.triangleCount++;
  70798. }
  70799. }
  70800. var tStart = 0;
  70801. for (i = 0; i < this.vertices.length; ++i) {
  70802. this.vertices[i].triangleStart = tStart;
  70803. tStart += this.vertices[i].triangleCount;
  70804. this.vertices[i].triangleCount = 0;
  70805. }
  70806. var newReferences = new Array(this.triangles.length * 3);
  70807. for (i = 0; i < this.triangles.length; ++i) {
  70808. t = this.triangles[i];
  70809. for (j = 0; j < 3; ++j) {
  70810. v = t.vertices[j];
  70811. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  70812. v.triangleCount++;
  70813. }
  70814. }
  70815. this.references = newReferences;
  70816. if (identifyBorders) {
  70817. this.identifyBorder();
  70818. }
  70819. };
  70820. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  70821. var x = point.x;
  70822. var y = point.y;
  70823. var z = point.z;
  70824. 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
  70825. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  70826. };
  70827. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  70828. var q = vertex1.q.add(vertex2.q);
  70829. var border = vertex1.isBorder && vertex2.isBorder;
  70830. var error = 0;
  70831. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  70832. if (qDet !== 0 && !border) {
  70833. if (!pointResult) {
  70834. pointResult = BABYLON.Vector3.Zero();
  70835. }
  70836. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  70837. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  70838. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  70839. error = this.vertexError(q, pointResult);
  70840. }
  70841. else {
  70842. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  70843. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  70844. var error1 = this.vertexError(q, vertex1.position);
  70845. var error2 = this.vertexError(q, vertex2.position);
  70846. var error3 = this.vertexError(q, p3);
  70847. error = Math.min(error1, error2, error3);
  70848. if (error === error1) {
  70849. if (pointResult) {
  70850. pointResult.copyFrom(vertex1.position);
  70851. }
  70852. }
  70853. else if (error === error2) {
  70854. if (pointResult) {
  70855. pointResult.copyFrom(vertex2.position);
  70856. }
  70857. }
  70858. else {
  70859. if (pointResult) {
  70860. pointResult.copyFrom(p3);
  70861. }
  70862. }
  70863. }
  70864. return error;
  70865. };
  70866. return QuadraticErrorSimplification;
  70867. }());
  70868. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  70869. })(BABYLON || (BABYLON = {}));
  70870. //# sourceMappingURL=babylon.meshSimplification.js.map
  70871. var BABYLON;
  70872. (function (BABYLON) {
  70873. var Internals;
  70874. (function (Internals) {
  70875. var MeshLODLevel = /** @class */ (function () {
  70876. function MeshLODLevel(distance, mesh) {
  70877. this.distance = distance;
  70878. this.mesh = mesh;
  70879. }
  70880. return MeshLODLevel;
  70881. }());
  70882. Internals.MeshLODLevel = MeshLODLevel;
  70883. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  70884. })(BABYLON || (BABYLON = {}));
  70885. //# sourceMappingURL=babylon.meshLODLevel.js.map
  70886. var BABYLON;
  70887. (function (BABYLON) {
  70888. // Standard optimizations
  70889. var SceneOptimization = /** @class */ (function () {
  70890. function SceneOptimization(priority) {
  70891. if (priority === void 0) { priority = 0; }
  70892. this.priority = priority;
  70893. this.apply = function (scene) {
  70894. return true; // Return true if everything that can be done was applied
  70895. };
  70896. }
  70897. return SceneOptimization;
  70898. }());
  70899. BABYLON.SceneOptimization = SceneOptimization;
  70900. var TextureOptimization = /** @class */ (function (_super) {
  70901. __extends(TextureOptimization, _super);
  70902. function TextureOptimization(priority, maximumSize) {
  70903. if (priority === void 0) { priority = 0; }
  70904. if (maximumSize === void 0) { maximumSize = 1024; }
  70905. var _this = _super.call(this, priority) || this;
  70906. _this.priority = priority;
  70907. _this.maximumSize = maximumSize;
  70908. _this.apply = function (scene) {
  70909. var allDone = true;
  70910. for (var index = 0; index < scene.textures.length; index++) {
  70911. var texture = scene.textures[index];
  70912. if (!texture.canRescale || texture.getContext) {
  70913. continue;
  70914. }
  70915. var currentSize = texture.getSize();
  70916. var maxDimension = Math.max(currentSize.width, currentSize.height);
  70917. if (maxDimension > _this.maximumSize) {
  70918. texture.scale(0.5);
  70919. allDone = false;
  70920. }
  70921. }
  70922. return allDone;
  70923. };
  70924. return _this;
  70925. }
  70926. return TextureOptimization;
  70927. }(SceneOptimization));
  70928. BABYLON.TextureOptimization = TextureOptimization;
  70929. var HardwareScalingOptimization = /** @class */ (function (_super) {
  70930. __extends(HardwareScalingOptimization, _super);
  70931. function HardwareScalingOptimization(priority, maximumScale) {
  70932. if (priority === void 0) { priority = 0; }
  70933. if (maximumScale === void 0) { maximumScale = 2; }
  70934. var _this = _super.call(this, priority) || this;
  70935. _this.priority = priority;
  70936. _this.maximumScale = maximumScale;
  70937. _this._currentScale = 1;
  70938. _this.apply = function (scene) {
  70939. _this._currentScale++;
  70940. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  70941. return _this._currentScale >= _this.maximumScale;
  70942. };
  70943. return _this;
  70944. }
  70945. return HardwareScalingOptimization;
  70946. }(SceneOptimization));
  70947. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  70948. var ShadowsOptimization = /** @class */ (function (_super) {
  70949. __extends(ShadowsOptimization, _super);
  70950. function ShadowsOptimization() {
  70951. var _this = _super !== null && _super.apply(this, arguments) || this;
  70952. _this.apply = function (scene) {
  70953. scene.shadowsEnabled = false;
  70954. return true;
  70955. };
  70956. return _this;
  70957. }
  70958. return ShadowsOptimization;
  70959. }(SceneOptimization));
  70960. BABYLON.ShadowsOptimization = ShadowsOptimization;
  70961. var PostProcessesOptimization = /** @class */ (function (_super) {
  70962. __extends(PostProcessesOptimization, _super);
  70963. function PostProcessesOptimization() {
  70964. var _this = _super !== null && _super.apply(this, arguments) || this;
  70965. _this.apply = function (scene) {
  70966. scene.postProcessesEnabled = false;
  70967. return true;
  70968. };
  70969. return _this;
  70970. }
  70971. return PostProcessesOptimization;
  70972. }(SceneOptimization));
  70973. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  70974. var LensFlaresOptimization = /** @class */ (function (_super) {
  70975. __extends(LensFlaresOptimization, _super);
  70976. function LensFlaresOptimization() {
  70977. var _this = _super !== null && _super.apply(this, arguments) || this;
  70978. _this.apply = function (scene) {
  70979. scene.lensFlaresEnabled = false;
  70980. return true;
  70981. };
  70982. return _this;
  70983. }
  70984. return LensFlaresOptimization;
  70985. }(SceneOptimization));
  70986. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  70987. var ParticlesOptimization = /** @class */ (function (_super) {
  70988. __extends(ParticlesOptimization, _super);
  70989. function ParticlesOptimization() {
  70990. var _this = _super !== null && _super.apply(this, arguments) || this;
  70991. _this.apply = function (scene) {
  70992. scene.particlesEnabled = false;
  70993. return true;
  70994. };
  70995. return _this;
  70996. }
  70997. return ParticlesOptimization;
  70998. }(SceneOptimization));
  70999. BABYLON.ParticlesOptimization = ParticlesOptimization;
  71000. var RenderTargetsOptimization = /** @class */ (function (_super) {
  71001. __extends(RenderTargetsOptimization, _super);
  71002. function RenderTargetsOptimization() {
  71003. var _this = _super !== null && _super.apply(this, arguments) || this;
  71004. _this.apply = function (scene) {
  71005. scene.renderTargetsEnabled = false;
  71006. return true;
  71007. };
  71008. return _this;
  71009. }
  71010. return RenderTargetsOptimization;
  71011. }(SceneOptimization));
  71012. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  71013. var MergeMeshesOptimization = /** @class */ (function (_super) {
  71014. __extends(MergeMeshesOptimization, _super);
  71015. function MergeMeshesOptimization() {
  71016. var _this = _super !== null && _super.apply(this, arguments) || this;
  71017. _this._canBeMerged = function (abstractMesh) {
  71018. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  71019. return false;
  71020. }
  71021. var mesh = abstractMesh;
  71022. if (!mesh.isVisible || !mesh.isEnabled()) {
  71023. return false;
  71024. }
  71025. if (mesh.instances.length > 0) {
  71026. return false;
  71027. }
  71028. if (mesh.skeleton || mesh.hasLODLevels) {
  71029. return false;
  71030. }
  71031. if (mesh.parent) {
  71032. return false;
  71033. }
  71034. return true;
  71035. };
  71036. _this.apply = function (scene, updateSelectionTree) {
  71037. var globalPool = scene.meshes.slice(0);
  71038. var globalLength = globalPool.length;
  71039. for (var index = 0; index < globalLength; index++) {
  71040. var currentPool = new Array();
  71041. var current = globalPool[index];
  71042. // Checks
  71043. if (!_this._canBeMerged(current)) {
  71044. continue;
  71045. }
  71046. currentPool.push(current);
  71047. // Find compatible meshes
  71048. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  71049. var otherMesh = globalPool[subIndex];
  71050. if (!_this._canBeMerged(otherMesh)) {
  71051. continue;
  71052. }
  71053. if (otherMesh.material !== current.material) {
  71054. continue;
  71055. }
  71056. if (otherMesh.checkCollisions !== current.checkCollisions) {
  71057. continue;
  71058. }
  71059. currentPool.push(otherMesh);
  71060. globalLength--;
  71061. globalPool.splice(subIndex, 1);
  71062. subIndex--;
  71063. }
  71064. if (currentPool.length < 2) {
  71065. continue;
  71066. }
  71067. // Merge meshes
  71068. BABYLON.Mesh.MergeMeshes(currentPool);
  71069. }
  71070. if (updateSelectionTree != undefined) {
  71071. if (updateSelectionTree) {
  71072. scene.createOrUpdateSelectionOctree();
  71073. }
  71074. }
  71075. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  71076. scene.createOrUpdateSelectionOctree();
  71077. }
  71078. return true;
  71079. };
  71080. return _this;
  71081. }
  71082. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  71083. get: function () {
  71084. return MergeMeshesOptimization._UpdateSelectionTree;
  71085. },
  71086. set: function (value) {
  71087. MergeMeshesOptimization._UpdateSelectionTree = value;
  71088. },
  71089. enumerable: true,
  71090. configurable: true
  71091. });
  71092. MergeMeshesOptimization._UpdateSelectionTree = false;
  71093. return MergeMeshesOptimization;
  71094. }(SceneOptimization));
  71095. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  71096. // Options
  71097. var SceneOptimizerOptions = /** @class */ (function () {
  71098. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  71099. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  71100. if (trackerDuration === void 0) { trackerDuration = 2000; }
  71101. this.targetFrameRate = targetFrameRate;
  71102. this.trackerDuration = trackerDuration;
  71103. this.optimizations = new Array();
  71104. }
  71105. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  71106. var result = new SceneOptimizerOptions(targetFrameRate);
  71107. var priority = 0;
  71108. result.optimizations.push(new MergeMeshesOptimization(priority));
  71109. result.optimizations.push(new ShadowsOptimization(priority));
  71110. result.optimizations.push(new LensFlaresOptimization(priority));
  71111. // Next priority
  71112. priority++;
  71113. result.optimizations.push(new PostProcessesOptimization(priority));
  71114. result.optimizations.push(new ParticlesOptimization(priority));
  71115. // Next priority
  71116. priority++;
  71117. result.optimizations.push(new TextureOptimization(priority, 1024));
  71118. return result;
  71119. };
  71120. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  71121. var result = new SceneOptimizerOptions(targetFrameRate);
  71122. var priority = 0;
  71123. result.optimizations.push(new MergeMeshesOptimization(priority));
  71124. result.optimizations.push(new ShadowsOptimization(priority));
  71125. result.optimizations.push(new LensFlaresOptimization(priority));
  71126. // Next priority
  71127. priority++;
  71128. result.optimizations.push(new PostProcessesOptimization(priority));
  71129. result.optimizations.push(new ParticlesOptimization(priority));
  71130. // Next priority
  71131. priority++;
  71132. result.optimizations.push(new TextureOptimization(priority, 512));
  71133. // Next priority
  71134. priority++;
  71135. result.optimizations.push(new RenderTargetsOptimization(priority));
  71136. // Next priority
  71137. priority++;
  71138. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  71139. return result;
  71140. };
  71141. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  71142. var result = new SceneOptimizerOptions(targetFrameRate);
  71143. var priority = 0;
  71144. result.optimizations.push(new MergeMeshesOptimization(priority));
  71145. result.optimizations.push(new ShadowsOptimization(priority));
  71146. result.optimizations.push(new LensFlaresOptimization(priority));
  71147. // Next priority
  71148. priority++;
  71149. result.optimizations.push(new PostProcessesOptimization(priority));
  71150. result.optimizations.push(new ParticlesOptimization(priority));
  71151. // Next priority
  71152. priority++;
  71153. result.optimizations.push(new TextureOptimization(priority, 256));
  71154. // Next priority
  71155. priority++;
  71156. result.optimizations.push(new RenderTargetsOptimization(priority));
  71157. // Next priority
  71158. priority++;
  71159. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  71160. return result;
  71161. };
  71162. return SceneOptimizerOptions;
  71163. }());
  71164. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  71165. // Scene optimizer tool
  71166. var SceneOptimizer = /** @class */ (function () {
  71167. function SceneOptimizer() {
  71168. }
  71169. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  71170. // TODO: add an epsilon
  71171. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  71172. if (onSuccess) {
  71173. onSuccess();
  71174. }
  71175. return;
  71176. }
  71177. // Apply current level of optimizations
  71178. var allDone = true;
  71179. var noOptimizationApplied = true;
  71180. for (var index = 0; index < options.optimizations.length; index++) {
  71181. var optimization = options.optimizations[index];
  71182. if (optimization.priority === currentPriorityLevel) {
  71183. noOptimizationApplied = false;
  71184. allDone = allDone && optimization.apply(scene);
  71185. }
  71186. }
  71187. // If no optimization was applied, this is a failure :(
  71188. if (noOptimizationApplied) {
  71189. if (onFailure) {
  71190. onFailure();
  71191. }
  71192. return;
  71193. }
  71194. // If all optimizations were done, move to next level
  71195. if (allDone) {
  71196. currentPriorityLevel++;
  71197. }
  71198. // Let's the system running for a specific amount of time before checking FPS
  71199. scene.executeWhenReady(function () {
  71200. setTimeout(function () {
  71201. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  71202. }, options.trackerDuration);
  71203. });
  71204. };
  71205. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  71206. if (!options) {
  71207. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  71208. }
  71209. // Let's the system running for a specific amount of time before checking FPS
  71210. scene.executeWhenReady(function () {
  71211. setTimeout(function () {
  71212. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  71213. }, options.trackerDuration);
  71214. });
  71215. };
  71216. return SceneOptimizer;
  71217. }());
  71218. BABYLON.SceneOptimizer = SceneOptimizer;
  71219. })(BABYLON || (BABYLON = {}));
  71220. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  71221. var BABYLON;
  71222. (function (BABYLON) {
  71223. var OutlineRenderer = /** @class */ (function () {
  71224. function OutlineRenderer(scene) {
  71225. this.zOffset = 1;
  71226. this._scene = scene;
  71227. }
  71228. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  71229. var _this = this;
  71230. if (useOverlay === void 0) { useOverlay = false; }
  71231. var scene = this._scene;
  71232. var engine = this._scene.getEngine();
  71233. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71234. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  71235. return;
  71236. }
  71237. var mesh = subMesh.getRenderingMesh();
  71238. var material = subMesh.getMaterial();
  71239. if (!material || !scene.activeCamera) {
  71240. return;
  71241. }
  71242. engine.enableEffect(this._effect);
  71243. // Logarithmic depth
  71244. if (material.useLogarithmicDepth) {
  71245. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  71246. }
  71247. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  71248. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  71249. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71250. // Bones
  71251. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71252. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71253. }
  71254. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71255. // Alpha test
  71256. if (material && material.needAlphaTesting()) {
  71257. var alphaTexture = material.getAlphaTestTexture();
  71258. if (alphaTexture) {
  71259. this._effect.setTexture("diffuseSampler", alphaTexture);
  71260. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71261. }
  71262. }
  71263. engine.setZOffset(-this.zOffset);
  71264. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  71265. engine.setZOffset(0);
  71266. };
  71267. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  71268. var defines = [];
  71269. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71270. var mesh = subMesh.getMesh();
  71271. var material = subMesh.getMaterial();
  71272. if (material) {
  71273. // Alpha test
  71274. if (material.needAlphaTesting()) {
  71275. defines.push("#define ALPHATEST");
  71276. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71277. attribs.push(BABYLON.VertexBuffer.UVKind);
  71278. defines.push("#define UV1");
  71279. }
  71280. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71281. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71282. defines.push("#define UV2");
  71283. }
  71284. }
  71285. //Logarithmic depth
  71286. if (material.useLogarithmicDepth) {
  71287. defines.push("#define LOGARITHMICDEPTH");
  71288. }
  71289. }
  71290. // Bones
  71291. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71292. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71293. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71294. if (mesh.numBoneInfluencers > 4) {
  71295. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71296. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71297. }
  71298. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71299. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71300. }
  71301. else {
  71302. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71303. }
  71304. // Instances
  71305. if (useInstances) {
  71306. defines.push("#define INSTANCES");
  71307. attribs.push("world0");
  71308. attribs.push("world1");
  71309. attribs.push("world2");
  71310. attribs.push("world3");
  71311. }
  71312. // Get correct effect
  71313. var join = defines.join("\n");
  71314. if (this._cachedDefines !== join) {
  71315. this._cachedDefines = join;
  71316. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  71317. }
  71318. return this._effect.isReady();
  71319. };
  71320. return OutlineRenderer;
  71321. }());
  71322. BABYLON.OutlineRenderer = OutlineRenderer;
  71323. })(BABYLON || (BABYLON = {}));
  71324. //# sourceMappingURL=babylon.outlineRenderer.js.map
  71325. var BABYLON;
  71326. (function (BABYLON) {
  71327. var FaceAdjacencies = /** @class */ (function () {
  71328. function FaceAdjacencies() {
  71329. this.edges = new Array();
  71330. this.edgesConnectedCount = 0;
  71331. }
  71332. return FaceAdjacencies;
  71333. }());
  71334. var EdgesRenderer = /** @class */ (function () {
  71335. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  71336. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  71337. if (epsilon === void 0) { epsilon = 0.95; }
  71338. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  71339. this.edgesWidthScalerForOrthographic = 1000.0;
  71340. this.edgesWidthScalerForPerspective = 50.0;
  71341. this._linesPositions = new Array();
  71342. this._linesNormals = new Array();
  71343. this._linesIndices = new Array();
  71344. this._buffers = {};
  71345. this._checkVerticesInsteadOfIndices = false;
  71346. this._source = source;
  71347. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  71348. this._epsilon = epsilon;
  71349. this._prepareRessources();
  71350. this._generateEdgesLines();
  71351. }
  71352. EdgesRenderer.prototype._prepareRessources = function () {
  71353. if (this._lineShader) {
  71354. return;
  71355. }
  71356. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  71357. attributes: ["position", "normal"],
  71358. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  71359. });
  71360. this._lineShader.disableDepthWrite = true;
  71361. this._lineShader.backFaceCulling = false;
  71362. };
  71363. EdgesRenderer.prototype._rebuild = function () {
  71364. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71365. if (buffer) {
  71366. buffer._rebuild();
  71367. }
  71368. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71369. if (buffer) {
  71370. buffer._rebuild();
  71371. }
  71372. var scene = this._source.getScene();
  71373. var engine = scene.getEngine();
  71374. this._ib = engine.createIndexBuffer(this._linesIndices);
  71375. };
  71376. EdgesRenderer.prototype.dispose = function () {
  71377. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71378. if (buffer) {
  71379. buffer.dispose();
  71380. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  71381. }
  71382. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71383. if (buffer) {
  71384. buffer.dispose();
  71385. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  71386. }
  71387. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  71388. this._lineShader.dispose();
  71389. };
  71390. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  71391. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  71392. return 0;
  71393. }
  71394. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  71395. return 1;
  71396. }
  71397. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  71398. return 2;
  71399. }
  71400. return -1;
  71401. };
  71402. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  71403. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  71404. return 0;
  71405. }
  71406. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  71407. return 1;
  71408. }
  71409. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  71410. return 2;
  71411. }
  71412. return -1;
  71413. };
  71414. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  71415. var needToCreateLine;
  71416. if (edge === undefined) {
  71417. needToCreateLine = true;
  71418. }
  71419. else {
  71420. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  71421. needToCreateLine = dotProduct < this._epsilon;
  71422. }
  71423. if (needToCreateLine) {
  71424. var offset = this._linesPositions.length / 3;
  71425. var normal = p0.subtract(p1);
  71426. normal.normalize();
  71427. // Positions
  71428. this._linesPositions.push(p0.x);
  71429. this._linesPositions.push(p0.y);
  71430. this._linesPositions.push(p0.z);
  71431. this._linesPositions.push(p0.x);
  71432. this._linesPositions.push(p0.y);
  71433. this._linesPositions.push(p0.z);
  71434. this._linesPositions.push(p1.x);
  71435. this._linesPositions.push(p1.y);
  71436. this._linesPositions.push(p1.z);
  71437. this._linesPositions.push(p1.x);
  71438. this._linesPositions.push(p1.y);
  71439. this._linesPositions.push(p1.z);
  71440. // Normals
  71441. this._linesNormals.push(p1.x);
  71442. this._linesNormals.push(p1.y);
  71443. this._linesNormals.push(p1.z);
  71444. this._linesNormals.push(-1);
  71445. this._linesNormals.push(p1.x);
  71446. this._linesNormals.push(p1.y);
  71447. this._linesNormals.push(p1.z);
  71448. this._linesNormals.push(1);
  71449. this._linesNormals.push(p0.x);
  71450. this._linesNormals.push(p0.y);
  71451. this._linesNormals.push(p0.z);
  71452. this._linesNormals.push(-1);
  71453. this._linesNormals.push(p0.x);
  71454. this._linesNormals.push(p0.y);
  71455. this._linesNormals.push(p0.z);
  71456. this._linesNormals.push(1);
  71457. // Indices
  71458. this._linesIndices.push(offset);
  71459. this._linesIndices.push(offset + 1);
  71460. this._linesIndices.push(offset + 2);
  71461. this._linesIndices.push(offset);
  71462. this._linesIndices.push(offset + 2);
  71463. this._linesIndices.push(offset + 3);
  71464. }
  71465. };
  71466. EdgesRenderer.prototype._generateEdgesLines = function () {
  71467. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71468. var indices = this._source.getIndices();
  71469. if (!indices || !positions) {
  71470. return;
  71471. }
  71472. // First let's find adjacencies
  71473. var adjacencies = new Array();
  71474. var faceNormals = new Array();
  71475. var index;
  71476. var faceAdjacencies;
  71477. // Prepare faces
  71478. for (index = 0; index < indices.length; index += 3) {
  71479. faceAdjacencies = new FaceAdjacencies();
  71480. var p0Index = indices[index];
  71481. var p1Index = indices[index + 1];
  71482. var p2Index = indices[index + 2];
  71483. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  71484. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  71485. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  71486. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  71487. faceNormal.normalize();
  71488. faceNormals.push(faceNormal);
  71489. adjacencies.push(faceAdjacencies);
  71490. }
  71491. // Scan
  71492. for (index = 0; index < adjacencies.length; index++) {
  71493. faceAdjacencies = adjacencies[index];
  71494. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  71495. var otherFaceAdjacencies = adjacencies[otherIndex];
  71496. if (faceAdjacencies.edgesConnectedCount === 3) {
  71497. break;
  71498. }
  71499. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  71500. continue;
  71501. }
  71502. var otherP0 = indices[otherIndex * 3];
  71503. var otherP1 = indices[otherIndex * 3 + 1];
  71504. var otherP2 = indices[otherIndex * 3 + 2];
  71505. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  71506. var otherEdgeIndex = 0;
  71507. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  71508. continue;
  71509. }
  71510. switch (edgeIndex) {
  71511. case 0:
  71512. if (this._checkVerticesInsteadOfIndices) {
  71513. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71514. }
  71515. else {
  71516. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  71517. }
  71518. break;
  71519. case 1:
  71520. if (this._checkVerticesInsteadOfIndices) {
  71521. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71522. }
  71523. else {
  71524. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  71525. }
  71526. break;
  71527. case 2:
  71528. if (this._checkVerticesInsteadOfIndices) {
  71529. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71530. }
  71531. else {
  71532. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  71533. }
  71534. break;
  71535. }
  71536. if (otherEdgeIndex === -1) {
  71537. continue;
  71538. }
  71539. faceAdjacencies.edges[edgeIndex] = otherIndex;
  71540. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  71541. faceAdjacencies.edgesConnectedCount++;
  71542. otherFaceAdjacencies.edgesConnectedCount++;
  71543. if (faceAdjacencies.edgesConnectedCount === 3) {
  71544. break;
  71545. }
  71546. }
  71547. }
  71548. }
  71549. // Create lines
  71550. for (index = 0; index < adjacencies.length; index++) {
  71551. // 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
  71552. var current = adjacencies[index];
  71553. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  71554. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  71555. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  71556. }
  71557. // Merge into a single mesh
  71558. var engine = this._source.getScene().getEngine();
  71559. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  71560. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  71561. this._ib = engine.createIndexBuffer(this._linesIndices);
  71562. this._indicesCount = this._linesIndices.length;
  71563. };
  71564. EdgesRenderer.prototype.render = function () {
  71565. var scene = this._source.getScene();
  71566. if (!this._lineShader.isReady() || !scene.activeCamera) {
  71567. return;
  71568. }
  71569. var engine = scene.getEngine();
  71570. this._lineShader._preBind();
  71571. // VBOs
  71572. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  71573. scene.resetCachedMaterial();
  71574. this._lineShader.setColor4("color", this._source.edgesColor);
  71575. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  71576. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  71577. }
  71578. else {
  71579. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  71580. }
  71581. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  71582. this._lineShader.bind(this._source.getWorldMatrix());
  71583. // Draw order
  71584. engine.draw(true, 0, this._indicesCount);
  71585. this._lineShader.unbind();
  71586. engine.setDepthWrite(true);
  71587. };
  71588. return EdgesRenderer;
  71589. }());
  71590. BABYLON.EdgesRenderer = EdgesRenderer;
  71591. })(BABYLON || (BABYLON = {}));
  71592. //# sourceMappingURL=babylon.edgesRenderer.js.map
  71593. var BABYLON;
  71594. (function (BABYLON) {
  71595. /**
  71596. * Special Glow Blur post process only blurring the alpha channel
  71597. * It enforces keeping the most luminous color in the color channel.
  71598. */
  71599. var GlowBlurPostProcess = /** @class */ (function (_super) {
  71600. __extends(GlowBlurPostProcess, _super);
  71601. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  71602. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71603. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  71604. _this.direction = direction;
  71605. _this.kernel = kernel;
  71606. _this.onApplyObservable.add(function (effect) {
  71607. effect.setFloat2("screenSize", _this.width, _this.height);
  71608. effect.setVector2("direction", _this.direction);
  71609. effect.setFloat("blurWidth", _this.kernel);
  71610. });
  71611. return _this;
  71612. }
  71613. return GlowBlurPostProcess;
  71614. }(BABYLON.PostProcess));
  71615. /**
  71616. * The highlight layer Helps adding a glow effect around a mesh.
  71617. *
  71618. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  71619. * glowy meshes to your scene.
  71620. *
  71621. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  71622. */
  71623. var HighlightLayer = /** @class */ (function () {
  71624. /**
  71625. * Instantiates a new highlight Layer and references it to the scene..
  71626. * @param name The name of the layer
  71627. * @param scene The scene to use the layer in
  71628. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  71629. */
  71630. function HighlightLayer(name, scene, options) {
  71631. this.name = name;
  71632. this._vertexBuffers = {};
  71633. this._mainTextureDesiredSize = { width: 0, height: 0 };
  71634. this._meshes = {};
  71635. this._maxSize = 0;
  71636. this._shouldRender = false;
  71637. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  71638. this._excludedMeshes = {};
  71639. /**
  71640. * Specifies whether or not the inner glow is ACTIVE in the layer.
  71641. */
  71642. this.innerGlow = true;
  71643. /**
  71644. * Specifies whether or not the outer glow is ACTIVE in the layer.
  71645. */
  71646. this.outerGlow = true;
  71647. /**
  71648. * Specifies wether the highlight layer is enabled or not.
  71649. */
  71650. this.isEnabled = true;
  71651. /**
  71652. * An event triggered when the highlight layer has been disposed.
  71653. * @type {BABYLON.Observable}
  71654. */
  71655. this.onDisposeObservable = new BABYLON.Observable();
  71656. /**
  71657. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  71658. * @type {BABYLON.Observable}
  71659. */
  71660. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  71661. /**
  71662. * An event triggered when the highlight layer is being blurred.
  71663. * @type {BABYLON.Observable}
  71664. */
  71665. this.onBeforeBlurObservable = new BABYLON.Observable();
  71666. /**
  71667. * An event triggered when the highlight layer has been blurred.
  71668. * @type {BABYLON.Observable}
  71669. */
  71670. this.onAfterBlurObservable = new BABYLON.Observable();
  71671. /**
  71672. * An event triggered when the glowing blurred texture is being merged in the scene.
  71673. * @type {BABYLON.Observable}
  71674. */
  71675. this.onBeforeComposeObservable = new BABYLON.Observable();
  71676. /**
  71677. * An event triggered when the glowing blurred texture has been merged in the scene.
  71678. * @type {BABYLON.Observable}
  71679. */
  71680. this.onAfterComposeObservable = new BABYLON.Observable();
  71681. /**
  71682. * An event triggered when the highlight layer changes its size.
  71683. * @type {BABYLON.Observable}
  71684. */
  71685. this.onSizeChangedObservable = new BABYLON.Observable();
  71686. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71687. var engine = scene.getEngine();
  71688. this._engine = engine;
  71689. this._maxSize = this._engine.getCaps().maxTextureSize;
  71690. this._scene.highlightLayers.push(this);
  71691. // Warn on stencil.
  71692. if (!this._engine.isStencilEnable) {
  71693. 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 }");
  71694. }
  71695. // Adapt options
  71696. this._options = options || {
  71697. mainTextureRatio: 0.5,
  71698. blurTextureSizeRatio: 0.5,
  71699. blurHorizontalSize: 1.0,
  71700. blurVerticalSize: 1.0,
  71701. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  71702. camera: null
  71703. };
  71704. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  71705. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  71706. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  71707. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  71708. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  71709. // VBO
  71710. var vertices = [];
  71711. vertices.push(1, 1);
  71712. vertices.push(-1, 1);
  71713. vertices.push(-1, -1);
  71714. vertices.push(1, -1);
  71715. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71716. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71717. this._createIndexBuffer();
  71718. // Effect
  71719. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  71720. // Render target
  71721. this.setMainTextureSize();
  71722. // Create Textures and post processes
  71723. this.createTextureAndPostProcesses();
  71724. }
  71725. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  71726. /**
  71727. * Gets the horizontal size of the blur.
  71728. */
  71729. get: function () {
  71730. return this._horizontalBlurPostprocess.kernel;
  71731. },
  71732. /**
  71733. * Specifies the horizontal size of the blur.
  71734. */
  71735. set: function (value) {
  71736. this._horizontalBlurPostprocess.kernel = value;
  71737. },
  71738. enumerable: true,
  71739. configurable: true
  71740. });
  71741. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  71742. /**
  71743. * Gets the vertical size of the blur.
  71744. */
  71745. get: function () {
  71746. return this._verticalBlurPostprocess.kernel;
  71747. },
  71748. /**
  71749. * Specifies the vertical size of the blur.
  71750. */
  71751. set: function (value) {
  71752. this._verticalBlurPostprocess.kernel = value;
  71753. },
  71754. enumerable: true,
  71755. configurable: true
  71756. });
  71757. Object.defineProperty(HighlightLayer.prototype, "camera", {
  71758. /**
  71759. * Gets the camera attached to the layer.
  71760. */
  71761. get: function () {
  71762. return this._options.camera;
  71763. },
  71764. enumerable: true,
  71765. configurable: true
  71766. });
  71767. HighlightLayer.prototype._createIndexBuffer = function () {
  71768. var engine = this._scene.getEngine();
  71769. // Indices
  71770. var indices = [];
  71771. indices.push(0);
  71772. indices.push(1);
  71773. indices.push(2);
  71774. indices.push(0);
  71775. indices.push(2);
  71776. indices.push(3);
  71777. this._indexBuffer = engine.createIndexBuffer(indices);
  71778. };
  71779. HighlightLayer.prototype._rebuild = function () {
  71780. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71781. if (vb) {
  71782. vb._rebuild();
  71783. }
  71784. this._createIndexBuffer();
  71785. };
  71786. /**
  71787. * Creates the render target textures and post processes used in the highlight layer.
  71788. */
  71789. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  71790. var _this = this;
  71791. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  71792. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  71793. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  71794. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  71795. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  71796. width: this._mainTextureDesiredSize.width,
  71797. height: this._mainTextureDesiredSize.height
  71798. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71799. this._mainTexture.activeCamera = this._options.camera;
  71800. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71801. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71802. this._mainTexture.anisotropicFilteringLevel = 1;
  71803. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71804. this._mainTexture.renderParticles = false;
  71805. this._mainTexture.renderList = null;
  71806. this._mainTexture.ignoreCameraViewport = true;
  71807. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  71808. width: blurTextureWidth,
  71809. height: blurTextureHeight
  71810. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71811. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71812. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71813. this._blurTexture.anisotropicFilteringLevel = 16;
  71814. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71815. this._blurTexture.renderParticles = false;
  71816. this._blurTexture.ignoreCameraViewport = true;
  71817. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71818. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  71819. effect.setTexture("textureSampler", _this._mainTexture);
  71820. });
  71821. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  71822. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71823. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  71824. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71825. });
  71826. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71827. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  71828. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71829. });
  71830. }
  71831. else {
  71832. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71833. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  71834. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71835. });
  71836. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71837. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  71838. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71839. });
  71840. }
  71841. this._mainTexture.onAfterUnbindObservable.add(function () {
  71842. _this.onBeforeBlurObservable.notifyObservers(_this);
  71843. var internalTexture = _this._blurTexture.getInternalTexture();
  71844. if (internalTexture) {
  71845. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  71846. }
  71847. _this.onAfterBlurObservable.notifyObservers(_this);
  71848. });
  71849. // Custom render function
  71850. var renderSubMesh = function (subMesh) {
  71851. if (!_this._meshes) {
  71852. return;
  71853. }
  71854. var material = subMesh.getMaterial();
  71855. var mesh = subMesh.getRenderingMesh();
  71856. var scene = _this._scene;
  71857. var engine = scene.getEngine();
  71858. if (!material) {
  71859. return;
  71860. }
  71861. // Culling
  71862. engine.setState(material.backFaceCulling);
  71863. // Managing instances
  71864. var batch = mesh._getInstancesRenderList(subMesh._id);
  71865. if (batch.mustReturn) {
  71866. return;
  71867. }
  71868. // Excluded Mesh
  71869. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  71870. return;
  71871. }
  71872. ;
  71873. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71874. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  71875. var emissiveTexture = null;
  71876. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  71877. emissiveTexture = material.emissiveTexture;
  71878. }
  71879. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  71880. engine.enableEffect(_this._glowMapGenerationEffect);
  71881. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  71882. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  71883. if (highlightLayerMesh) {
  71884. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  71885. }
  71886. else {
  71887. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  71888. }
  71889. // Alpha test
  71890. if (material && material.needAlphaTesting()) {
  71891. var alphaTexture = material.getAlphaTestTexture();
  71892. if (alphaTexture) {
  71893. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  71894. var textureMatrix = alphaTexture.getTextureMatrix();
  71895. if (textureMatrix) {
  71896. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  71897. }
  71898. }
  71899. }
  71900. // Glow emissive only
  71901. if (emissiveTexture) {
  71902. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  71903. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  71904. }
  71905. // Bones
  71906. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71907. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71908. }
  71909. // Draw
  71910. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  71911. }
  71912. else {
  71913. // Need to reset refresh rate of the shadowMap
  71914. _this._mainTexture.resetRefreshCounter();
  71915. }
  71916. };
  71917. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71918. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  71919. var index;
  71920. var engine = _this._scene.getEngine();
  71921. if (depthOnlySubMeshes.length) {
  71922. engine.setColorWrite(false);
  71923. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71924. renderSubMesh(depthOnlySubMeshes.data[index]);
  71925. }
  71926. engine.setColorWrite(true);
  71927. }
  71928. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71929. renderSubMesh(opaqueSubMeshes.data[index]);
  71930. }
  71931. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71932. renderSubMesh(alphaTestSubMeshes.data[index]);
  71933. }
  71934. for (index = 0; index < transparentSubMeshes.length; index++) {
  71935. renderSubMesh(transparentSubMeshes.data[index]);
  71936. }
  71937. };
  71938. this._mainTexture.onClearObservable.add(function (engine) {
  71939. engine.clear(HighlightLayer.neutralColor, true, true, true);
  71940. });
  71941. };
  71942. /**
  71943. * Checks for the readiness of the element composing the layer.
  71944. * @param subMesh the mesh to check for
  71945. * @param useInstances specify wether or not to use instances to render the mesh
  71946. * @param emissiveTexture the associated emissive texture used to generate the glow
  71947. * @return true if ready otherwise, false
  71948. */
  71949. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  71950. var material = subMesh.getMaterial();
  71951. if (!material) {
  71952. return false;
  71953. }
  71954. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  71955. return false;
  71956. }
  71957. var defines = [];
  71958. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71959. var mesh = subMesh.getMesh();
  71960. var uv1 = false;
  71961. var uv2 = false;
  71962. // Alpha test
  71963. if (material && material.needAlphaTesting()) {
  71964. var alphaTexture = material.getAlphaTestTexture();
  71965. if (alphaTexture) {
  71966. defines.push("#define ALPHATEST");
  71967. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  71968. alphaTexture.coordinatesIndex === 1) {
  71969. defines.push("#define DIFFUSEUV2");
  71970. uv2 = true;
  71971. }
  71972. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71973. defines.push("#define DIFFUSEUV1");
  71974. uv1 = true;
  71975. }
  71976. }
  71977. }
  71978. // Emissive
  71979. if (emissiveTexture) {
  71980. defines.push("#define EMISSIVE");
  71981. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  71982. emissiveTexture.coordinatesIndex === 1) {
  71983. defines.push("#define EMISSIVEUV2");
  71984. uv2 = true;
  71985. }
  71986. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71987. defines.push("#define EMISSIVEUV1");
  71988. uv1 = true;
  71989. }
  71990. }
  71991. if (uv1) {
  71992. attribs.push(BABYLON.VertexBuffer.UVKind);
  71993. defines.push("#define UV1");
  71994. }
  71995. if (uv2) {
  71996. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71997. defines.push("#define UV2");
  71998. }
  71999. // Bones
  72000. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72001. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72002. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72003. if (mesh.numBoneInfluencers > 4) {
  72004. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72005. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72006. }
  72007. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72008. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72009. }
  72010. else {
  72011. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72012. }
  72013. // Instances
  72014. if (useInstances) {
  72015. defines.push("#define INSTANCES");
  72016. attribs.push("world0");
  72017. attribs.push("world1");
  72018. attribs.push("world2");
  72019. attribs.push("world3");
  72020. }
  72021. // Get correct effect
  72022. var join = defines.join("\n");
  72023. if (this._cachedDefines !== join) {
  72024. this._cachedDefines = join;
  72025. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  72026. }
  72027. return this._glowMapGenerationEffect.isReady();
  72028. };
  72029. /**
  72030. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  72031. */
  72032. HighlightLayer.prototype.render = function () {
  72033. var currentEffect = this._glowMapMergeEffect;
  72034. // Check
  72035. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  72036. return;
  72037. var engine = this._scene.getEngine();
  72038. this.onBeforeComposeObservable.notifyObservers(this);
  72039. // Render
  72040. engine.enableEffect(currentEffect);
  72041. engine.setState(false);
  72042. // Cache
  72043. var previousStencilBuffer = engine.getStencilBuffer();
  72044. var previousStencilFunction = engine.getStencilFunction();
  72045. var previousStencilMask = engine.getStencilMask();
  72046. var previousStencilOperationPass = engine.getStencilOperationPass();
  72047. var previousStencilOperationFail = engine.getStencilOperationFail();
  72048. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  72049. var previousAlphaMode = engine.getAlphaMode();
  72050. // Texture
  72051. currentEffect.setTexture("textureSampler", this._blurTexture);
  72052. // VBOs
  72053. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72054. // Stencil operations
  72055. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  72056. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  72057. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  72058. // Draw order
  72059. engine.setAlphaMode(this._options.alphaBlendingMode);
  72060. engine.setStencilMask(0x00);
  72061. engine.setStencilBuffer(true);
  72062. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  72063. if (this.outerGlow) {
  72064. currentEffect.setFloat("offset", 0);
  72065. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  72066. engine.draw(true, 0, 6);
  72067. }
  72068. if (this.innerGlow) {
  72069. currentEffect.setFloat("offset", 1);
  72070. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  72071. engine.draw(true, 0, 6);
  72072. }
  72073. // Restore Cache
  72074. engine.setStencilFunction(previousStencilFunction);
  72075. engine.setStencilMask(previousStencilMask);
  72076. engine.setAlphaMode(previousAlphaMode);
  72077. engine.setStencilBuffer(previousStencilBuffer);
  72078. engine.setStencilOperationPass(previousStencilOperationPass);
  72079. engine.setStencilOperationFail(previousStencilOperationFail);
  72080. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  72081. engine._stencilState.reset();
  72082. this.onAfterComposeObservable.notifyObservers(this);
  72083. // Handle size changes.
  72084. var size = this._mainTexture.getSize();
  72085. this.setMainTextureSize();
  72086. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  72087. // Recreate RTT and post processes on size change.
  72088. this.onSizeChangedObservable.notifyObservers(this);
  72089. this.disposeTextureAndPostProcesses();
  72090. this.createTextureAndPostProcesses();
  72091. }
  72092. };
  72093. /**
  72094. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  72095. * @param mesh The mesh to exclude from the highlight layer
  72096. */
  72097. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  72098. if (!this._excludedMeshes) {
  72099. return;
  72100. }
  72101. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72102. if (!meshExcluded) {
  72103. this._excludedMeshes[mesh.uniqueId] = {
  72104. mesh: mesh,
  72105. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  72106. mesh.getEngine().setStencilBuffer(false);
  72107. }),
  72108. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  72109. mesh.getEngine().setStencilBuffer(true);
  72110. }),
  72111. };
  72112. }
  72113. };
  72114. /**
  72115. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  72116. * @param mesh The mesh to highlight
  72117. */
  72118. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  72119. if (!this._excludedMeshes) {
  72120. return;
  72121. }
  72122. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72123. if (meshExcluded) {
  72124. if (meshExcluded.beforeRender) {
  72125. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  72126. }
  72127. if (meshExcluded.afterRender) {
  72128. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  72129. }
  72130. }
  72131. this._excludedMeshes[mesh.uniqueId] = null;
  72132. };
  72133. /**
  72134. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  72135. * @param mesh The mesh to highlight
  72136. * @param color The color of the highlight
  72137. * @param glowEmissiveOnly Extract the glow from the emissive texture
  72138. */
  72139. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  72140. var _this = this;
  72141. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  72142. if (!this._meshes) {
  72143. return;
  72144. }
  72145. var meshHighlight = this._meshes[mesh.uniqueId];
  72146. if (meshHighlight) {
  72147. meshHighlight.color = color;
  72148. }
  72149. else {
  72150. this._meshes[mesh.uniqueId] = {
  72151. mesh: mesh,
  72152. color: color,
  72153. // Lambda required for capture due to Observable this context
  72154. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  72155. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72156. _this.defaultStencilReference(mesh);
  72157. }
  72158. else {
  72159. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  72160. }
  72161. }),
  72162. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  72163. glowEmissiveOnly: glowEmissiveOnly
  72164. };
  72165. }
  72166. this._shouldRender = true;
  72167. };
  72168. /**
  72169. * Remove a mesh from the highlight layer in order to make it stop glowing.
  72170. * @param mesh The mesh to highlight
  72171. */
  72172. HighlightLayer.prototype.removeMesh = function (mesh) {
  72173. if (!this._meshes) {
  72174. return;
  72175. }
  72176. var meshHighlight = this._meshes[mesh.uniqueId];
  72177. if (meshHighlight) {
  72178. if (meshHighlight.observerHighlight) {
  72179. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72180. }
  72181. if (meshHighlight.observerDefault) {
  72182. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72183. }
  72184. }
  72185. this._meshes[mesh.uniqueId] = null;
  72186. this._shouldRender = false;
  72187. for (var meshHighlightToCheck in this._meshes) {
  72188. if (meshHighlightToCheck) {
  72189. this._shouldRender = true;
  72190. break;
  72191. }
  72192. }
  72193. };
  72194. /**
  72195. * Returns true if the layer contains information to display, otherwise false.
  72196. */
  72197. HighlightLayer.prototype.shouldRender = function () {
  72198. return this.isEnabled && this._shouldRender;
  72199. };
  72200. /**
  72201. * Sets the main texture desired size which is the closest power of two
  72202. * of the engine canvas size.
  72203. */
  72204. HighlightLayer.prototype.setMainTextureSize = function () {
  72205. if (this._options.mainTextureFixedSize) {
  72206. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  72207. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  72208. }
  72209. else {
  72210. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  72211. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  72212. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  72213. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  72214. }
  72215. };
  72216. /**
  72217. * Force the stencil to the normal expected value for none glowing parts
  72218. */
  72219. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  72220. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  72221. };
  72222. /**
  72223. * Dispose only the render target textures and post process.
  72224. */
  72225. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  72226. this._blurTexture.dispose();
  72227. this._mainTexture.dispose();
  72228. this._downSamplePostprocess.dispose();
  72229. this._horizontalBlurPostprocess.dispose();
  72230. this._verticalBlurPostprocess.dispose();
  72231. };
  72232. /**
  72233. * Dispose the highlight layer and free resources.
  72234. */
  72235. HighlightLayer.prototype.dispose = function () {
  72236. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72237. if (vertexBuffer) {
  72238. vertexBuffer.dispose();
  72239. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72240. }
  72241. if (this._indexBuffer) {
  72242. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72243. this._indexBuffer = null;
  72244. }
  72245. // Clean textures and post processes
  72246. this.disposeTextureAndPostProcesses();
  72247. if (this._meshes) {
  72248. // Clean mesh references
  72249. for (var id in this._meshes) {
  72250. var meshHighlight = this._meshes[id];
  72251. if (meshHighlight && meshHighlight.mesh) {
  72252. if (meshHighlight.observerHighlight) {
  72253. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72254. }
  72255. if (meshHighlight.observerDefault) {
  72256. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72257. }
  72258. }
  72259. }
  72260. this._meshes = null;
  72261. }
  72262. if (this._excludedMeshes) {
  72263. for (var id in this._excludedMeshes) {
  72264. var meshHighlight = this._excludedMeshes[id];
  72265. if (meshHighlight) {
  72266. if (meshHighlight.beforeRender) {
  72267. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  72268. }
  72269. if (meshHighlight.afterRender) {
  72270. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  72271. }
  72272. }
  72273. }
  72274. this._excludedMeshes = null;
  72275. }
  72276. // Remove from scene
  72277. var index = this._scene.highlightLayers.indexOf(this, 0);
  72278. if (index > -1) {
  72279. this._scene.highlightLayers.splice(index, 1);
  72280. }
  72281. // Callback
  72282. this.onDisposeObservable.notifyObservers(this);
  72283. this.onDisposeObservable.clear();
  72284. this.onBeforeRenderMainTextureObservable.clear();
  72285. this.onBeforeBlurObservable.clear();
  72286. this.onBeforeComposeObservable.clear();
  72287. this.onAfterComposeObservable.clear();
  72288. this.onSizeChangedObservable.clear();
  72289. };
  72290. /**
  72291. * The neutral color used during the preparation of the glow effect.
  72292. * This is black by default as the blend operation is a blend operation.
  72293. */
  72294. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  72295. /**
  72296. * Stencil value used for glowing meshes.
  72297. */
  72298. HighlightLayer.glowingMeshStencilReference = 0x02;
  72299. /**
  72300. * Stencil value used for the other meshes in the scene.
  72301. */
  72302. HighlightLayer.normalMeshStencilReference = 0x01;
  72303. return HighlightLayer;
  72304. }());
  72305. BABYLON.HighlightLayer = HighlightLayer;
  72306. })(BABYLON || (BABYLON = {}));
  72307. //# sourceMappingURL=babylon.highlightlayer.js.map
  72308. var BABYLON;
  72309. (function (BABYLON) {
  72310. var AssetTaskState;
  72311. (function (AssetTaskState) {
  72312. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  72313. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  72314. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  72315. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  72316. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  72317. var AbstractAssetTask = /** @class */ (function () {
  72318. function AbstractAssetTask(name) {
  72319. this.name = name;
  72320. this.isCompleted = false;
  72321. this.taskState = AssetTaskState.INIT;
  72322. }
  72323. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72324. var _this = this;
  72325. this.taskState = AssetTaskState.RUNNING;
  72326. this.runTask(scene, function () {
  72327. _this.onDoneCallback(onSuccess, onError);
  72328. }, function (msg, exception) {
  72329. _this.onErrorCallback(onError, msg, exception);
  72330. });
  72331. };
  72332. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72333. throw new Error("runTask is not implemented");
  72334. };
  72335. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  72336. this.taskState = AssetTaskState.ERROR;
  72337. this.errorObject = {
  72338. message: message,
  72339. exception: exception
  72340. };
  72341. if (this.onError) {
  72342. this.onError(this, message, exception);
  72343. }
  72344. onError();
  72345. };
  72346. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  72347. try {
  72348. this.taskState = AssetTaskState.DONE;
  72349. this.isCompleted = true;
  72350. if (this.onSuccess) {
  72351. this.onSuccess(this);
  72352. }
  72353. onSuccess();
  72354. }
  72355. catch (e) {
  72356. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  72357. }
  72358. };
  72359. return AbstractAssetTask;
  72360. }());
  72361. BABYLON.AbstractAssetTask = AbstractAssetTask;
  72362. var AssetsProgressEvent = /** @class */ (function () {
  72363. function AssetsProgressEvent(remainingCount, totalCount, task) {
  72364. this.remainingCount = remainingCount;
  72365. this.totalCount = totalCount;
  72366. this.task = task;
  72367. }
  72368. return AssetsProgressEvent;
  72369. }());
  72370. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  72371. var MeshAssetTask = /** @class */ (function (_super) {
  72372. __extends(MeshAssetTask, _super);
  72373. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  72374. var _this = _super.call(this, name) || this;
  72375. _this.name = name;
  72376. _this.meshesNames = meshesNames;
  72377. _this.rootUrl = rootUrl;
  72378. _this.sceneFilename = sceneFilename;
  72379. return _this;
  72380. }
  72381. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72382. var _this = this;
  72383. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  72384. _this.loadedMeshes = meshes;
  72385. _this.loadedParticleSystems = particleSystems;
  72386. _this.loadedSkeletons = skeletons;
  72387. onSuccess();
  72388. }, null, function (scene, message, exception) {
  72389. onError(message, exception);
  72390. });
  72391. };
  72392. return MeshAssetTask;
  72393. }(AbstractAssetTask));
  72394. BABYLON.MeshAssetTask = MeshAssetTask;
  72395. var TextFileAssetTask = /** @class */ (function (_super) {
  72396. __extends(TextFileAssetTask, _super);
  72397. function TextFileAssetTask(name, url) {
  72398. var _this = _super.call(this, name) || this;
  72399. _this.name = name;
  72400. _this.url = url;
  72401. return _this;
  72402. }
  72403. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72404. var _this = this;
  72405. BABYLON.Tools.LoadFile(this.url, function (data) {
  72406. _this.text = data;
  72407. onSuccess();
  72408. }, undefined, scene.database, false, function (request, exception) {
  72409. if (request) {
  72410. onError(request.status + " " + request.statusText, exception);
  72411. }
  72412. });
  72413. };
  72414. return TextFileAssetTask;
  72415. }(AbstractAssetTask));
  72416. BABYLON.TextFileAssetTask = TextFileAssetTask;
  72417. var BinaryFileAssetTask = /** @class */ (function (_super) {
  72418. __extends(BinaryFileAssetTask, _super);
  72419. function BinaryFileAssetTask(name, url) {
  72420. var _this = _super.call(this, name) || this;
  72421. _this.name = name;
  72422. _this.url = url;
  72423. return _this;
  72424. }
  72425. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72426. var _this = this;
  72427. BABYLON.Tools.LoadFile(this.url, function (data) {
  72428. _this.data = data;
  72429. onSuccess();
  72430. }, undefined, scene.database, true, function (request, exception) {
  72431. if (request) {
  72432. onError(request.status + " " + request.statusText, exception);
  72433. }
  72434. });
  72435. };
  72436. return BinaryFileAssetTask;
  72437. }(AbstractAssetTask));
  72438. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  72439. var ImageAssetTask = /** @class */ (function (_super) {
  72440. __extends(ImageAssetTask, _super);
  72441. function ImageAssetTask(name, url) {
  72442. var _this = _super.call(this, name) || this;
  72443. _this.name = name;
  72444. _this.url = url;
  72445. return _this;
  72446. }
  72447. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72448. var _this = this;
  72449. var img = new Image();
  72450. BABYLON.Tools.SetCorsBehavior(this.url, img);
  72451. img.onload = function () {
  72452. _this.image = img;
  72453. onSuccess();
  72454. };
  72455. img.onerror = function (err) {
  72456. onError("Error loading image", err);
  72457. };
  72458. img.src = this.url;
  72459. };
  72460. return ImageAssetTask;
  72461. }(AbstractAssetTask));
  72462. BABYLON.ImageAssetTask = ImageAssetTask;
  72463. var TextureAssetTask = /** @class */ (function (_super) {
  72464. __extends(TextureAssetTask, _super);
  72465. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  72466. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72467. var _this = _super.call(this, name) || this;
  72468. _this.name = name;
  72469. _this.url = url;
  72470. _this.noMipmap = noMipmap;
  72471. _this.invertY = invertY;
  72472. _this.samplingMode = samplingMode;
  72473. return _this;
  72474. }
  72475. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72476. var onload = function () {
  72477. onSuccess();
  72478. };
  72479. var onerror = function (msg, exception) {
  72480. onError(msg, exception);
  72481. };
  72482. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  72483. };
  72484. return TextureAssetTask;
  72485. }(AbstractAssetTask));
  72486. BABYLON.TextureAssetTask = TextureAssetTask;
  72487. var CubeTextureAssetTask = /** @class */ (function (_super) {
  72488. __extends(CubeTextureAssetTask, _super);
  72489. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  72490. var _this = _super.call(this, name) || this;
  72491. _this.name = name;
  72492. _this.url = url;
  72493. _this.extensions = extensions;
  72494. _this.noMipmap = noMipmap;
  72495. _this.files = files;
  72496. return _this;
  72497. }
  72498. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72499. var onload = function () {
  72500. onSuccess();
  72501. };
  72502. var onerror = function (msg, exception) {
  72503. onError(msg, exception);
  72504. };
  72505. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  72506. };
  72507. return CubeTextureAssetTask;
  72508. }(AbstractAssetTask));
  72509. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  72510. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  72511. __extends(HDRCubeTextureAssetTask, _super);
  72512. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72513. if (noMipmap === void 0) { noMipmap = false; }
  72514. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72515. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72516. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72517. var _this = _super.call(this, name) || this;
  72518. _this.name = name;
  72519. _this.url = url;
  72520. _this.size = size;
  72521. _this.noMipmap = noMipmap;
  72522. _this.generateHarmonics = generateHarmonics;
  72523. _this.useInGammaSpace = useInGammaSpace;
  72524. _this.usePMREMGenerator = usePMREMGenerator;
  72525. return _this;
  72526. }
  72527. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72528. var onload = function () {
  72529. onSuccess();
  72530. };
  72531. var onerror = function (message, exception) {
  72532. onError(message, exception);
  72533. };
  72534. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  72535. };
  72536. return HDRCubeTextureAssetTask;
  72537. }(AbstractAssetTask));
  72538. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  72539. var AssetsManager = /** @class */ (function () {
  72540. function AssetsManager(scene) {
  72541. this.tasks = new Array();
  72542. this.waitingTasksCount = 0;
  72543. //Observables
  72544. this.onTaskSuccessObservable = new BABYLON.Observable();
  72545. this.onTaskErrorObservable = new BABYLON.Observable();
  72546. this.onTasksDoneObservable = new BABYLON.Observable();
  72547. this.onProgressObservable = new BABYLON.Observable();
  72548. this.useDefaultLoadingScreen = true;
  72549. this._scene = scene;
  72550. }
  72551. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  72552. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  72553. this.tasks.push(task);
  72554. return task;
  72555. };
  72556. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  72557. var task = new TextFileAssetTask(taskName, url);
  72558. this.tasks.push(task);
  72559. return task;
  72560. };
  72561. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  72562. var task = new BinaryFileAssetTask(taskName, url);
  72563. this.tasks.push(task);
  72564. return task;
  72565. };
  72566. AssetsManager.prototype.addImageTask = function (taskName, url) {
  72567. var task = new ImageAssetTask(taskName, url);
  72568. this.tasks.push(task);
  72569. return task;
  72570. };
  72571. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  72572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72573. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  72574. this.tasks.push(task);
  72575. return task;
  72576. };
  72577. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  72578. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  72579. this.tasks.push(task);
  72580. return task;
  72581. };
  72582. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72583. if (noMipmap === void 0) { noMipmap = false; }
  72584. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72585. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72586. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72587. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  72588. this.tasks.push(task);
  72589. return task;
  72590. };
  72591. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  72592. this.waitingTasksCount--;
  72593. try {
  72594. if (this.onProgress) {
  72595. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  72596. }
  72597. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  72598. }
  72599. catch (e) {
  72600. BABYLON.Tools.Error("Error running progress callbacks.");
  72601. console.log(e);
  72602. }
  72603. if (this.waitingTasksCount === 0) {
  72604. try {
  72605. if (this.onFinish) {
  72606. this.onFinish(this.tasks);
  72607. }
  72608. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72609. }
  72610. catch (e) {
  72611. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  72612. console.log(e);
  72613. }
  72614. this._scene.getEngine().hideLoadingUI();
  72615. }
  72616. };
  72617. AssetsManager.prototype._runTask = function (task) {
  72618. var _this = this;
  72619. var done = function () {
  72620. try {
  72621. if (_this.onTaskSuccess) {
  72622. _this.onTaskSuccess(task);
  72623. }
  72624. _this.onTaskSuccessObservable.notifyObservers(task);
  72625. _this._decreaseWaitingTasksCount(task);
  72626. }
  72627. catch (e) {
  72628. error("Error executing task success callbacks", e);
  72629. }
  72630. };
  72631. var error = function (message, exception) {
  72632. task.errorObject = task.errorObject || {
  72633. message: message,
  72634. exception: exception
  72635. };
  72636. if (_this.onTaskError) {
  72637. _this.onTaskError(task);
  72638. }
  72639. _this.onTaskErrorObservable.notifyObservers(task);
  72640. _this._decreaseWaitingTasksCount(task);
  72641. };
  72642. task.run(this._scene, done, error);
  72643. };
  72644. AssetsManager.prototype.reset = function () {
  72645. this.tasks = new Array();
  72646. return this;
  72647. };
  72648. AssetsManager.prototype.load = function () {
  72649. this.waitingTasksCount = this.tasks.length;
  72650. if (this.waitingTasksCount === 0) {
  72651. if (this.onFinish) {
  72652. this.onFinish(this.tasks);
  72653. }
  72654. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72655. return this;
  72656. }
  72657. if (this.useDefaultLoadingScreen) {
  72658. this._scene.getEngine().displayLoadingUI();
  72659. }
  72660. for (var index = 0; index < this.tasks.length; index++) {
  72661. var task = this.tasks[index];
  72662. this._runTask(task);
  72663. }
  72664. return this;
  72665. };
  72666. return AssetsManager;
  72667. }());
  72668. BABYLON.AssetsManager = AssetsManager;
  72669. })(BABYLON || (BABYLON = {}));
  72670. //# sourceMappingURL=babylon.assetsManager.js.map
  72671. var BABYLON;
  72672. (function (BABYLON) {
  72673. var serializedGeometries = [];
  72674. var serializeGeometry = function (geometry, serializationGeometries) {
  72675. if (serializedGeometries[geometry.id]) {
  72676. return;
  72677. }
  72678. if (geometry.doNotSerialize) {
  72679. return;
  72680. }
  72681. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  72682. serializationGeometries.boxes.push(geometry.serialize());
  72683. }
  72684. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  72685. serializationGeometries.spheres.push(geometry.serialize());
  72686. }
  72687. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  72688. serializationGeometries.cylinders.push(geometry.serialize());
  72689. }
  72690. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  72691. serializationGeometries.toruses.push(geometry.serialize());
  72692. }
  72693. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  72694. serializationGeometries.grounds.push(geometry.serialize());
  72695. }
  72696. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  72697. serializationGeometries.planes.push(geometry.serialize());
  72698. }
  72699. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  72700. serializationGeometries.torusKnots.push(geometry.serialize());
  72701. }
  72702. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  72703. throw new Error("Unknown primitive type");
  72704. }
  72705. else {
  72706. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  72707. }
  72708. serializedGeometries[geometry.id] = true;
  72709. };
  72710. var serializeMesh = function (mesh, serializationScene) {
  72711. var serializationObject = {};
  72712. // Geometry
  72713. var geometry = mesh._geometry;
  72714. if (geometry) {
  72715. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  72716. // 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
  72717. serializeGeometry(geometry, serializationScene.geometries);
  72718. }
  72719. }
  72720. // Custom
  72721. if (mesh.serialize) {
  72722. mesh.serialize(serializationObject);
  72723. }
  72724. return serializationObject;
  72725. };
  72726. var finalizeSingleMesh = function (mesh, serializationObject) {
  72727. //only works if the mesh is already loaded
  72728. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72729. //serialize material
  72730. if (mesh.material) {
  72731. if (mesh.material instanceof BABYLON.StandardMaterial) {
  72732. serializationObject.materials = serializationObject.materials || [];
  72733. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72734. serializationObject.materials.push(mesh.material.serialize());
  72735. }
  72736. }
  72737. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  72738. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  72739. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72740. serializationObject.multiMaterials.push(mesh.material.serialize());
  72741. }
  72742. }
  72743. }
  72744. //serialize geometry
  72745. var geometry = mesh._geometry;
  72746. if (geometry) {
  72747. if (!serializationObject.geometries) {
  72748. serializationObject.geometries = {};
  72749. serializationObject.geometries.boxes = [];
  72750. serializationObject.geometries.spheres = [];
  72751. serializationObject.geometries.cylinders = [];
  72752. serializationObject.geometries.toruses = [];
  72753. serializationObject.geometries.grounds = [];
  72754. serializationObject.geometries.planes = [];
  72755. serializationObject.geometries.torusKnots = [];
  72756. serializationObject.geometries.vertexData = [];
  72757. }
  72758. serializeGeometry(geometry, serializationObject.geometries);
  72759. }
  72760. // Skeletons
  72761. if (mesh.skeleton) {
  72762. serializationObject.skeletons = serializationObject.skeletons || [];
  72763. serializationObject.skeletons.push(mesh.skeleton.serialize());
  72764. }
  72765. //serialize the actual mesh
  72766. serializationObject.meshes = serializationObject.meshes || [];
  72767. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  72768. }
  72769. };
  72770. var SceneSerializer = /** @class */ (function () {
  72771. function SceneSerializer() {
  72772. }
  72773. SceneSerializer.ClearCache = function () {
  72774. serializedGeometries = [];
  72775. };
  72776. SceneSerializer.Serialize = function (scene) {
  72777. var serializationObject = {};
  72778. SceneSerializer.ClearCache();
  72779. // Scene
  72780. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  72781. serializationObject.autoClear = scene.autoClear;
  72782. serializationObject.clearColor = scene.clearColor.asArray();
  72783. serializationObject.ambientColor = scene.ambientColor.asArray();
  72784. serializationObject.gravity = scene.gravity.asArray();
  72785. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  72786. serializationObject.workerCollisions = scene.workerCollisions;
  72787. // Fog
  72788. if (scene.fogMode && scene.fogMode !== 0) {
  72789. serializationObject.fogMode = scene.fogMode;
  72790. serializationObject.fogColor = scene.fogColor.asArray();
  72791. serializationObject.fogStart = scene.fogStart;
  72792. serializationObject.fogEnd = scene.fogEnd;
  72793. serializationObject.fogDensity = scene.fogDensity;
  72794. }
  72795. //Physics
  72796. if (scene.isPhysicsEnabled()) {
  72797. var physicEngine = scene.getPhysicsEngine();
  72798. if (physicEngine) {
  72799. serializationObject.physicsEnabled = true;
  72800. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  72801. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  72802. }
  72803. }
  72804. // Metadata
  72805. if (scene.metadata) {
  72806. serializationObject.metadata = scene.metadata;
  72807. }
  72808. // Morph targets
  72809. serializationObject.morphTargetManagers = [];
  72810. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  72811. var abstractMesh = _a[_i];
  72812. var manager = abstractMesh.morphTargetManager;
  72813. if (manager) {
  72814. serializationObject.morphTargetManagers.push(manager.serialize());
  72815. }
  72816. }
  72817. // Lights
  72818. serializationObject.lights = [];
  72819. var index;
  72820. var light;
  72821. for (index = 0; index < scene.lights.length; index++) {
  72822. light = scene.lights[index];
  72823. if (!light.doNotSerialize) {
  72824. serializationObject.lights.push(light.serialize());
  72825. }
  72826. }
  72827. // Cameras
  72828. serializationObject.cameras = [];
  72829. for (index = 0; index < scene.cameras.length; index++) {
  72830. var camera = scene.cameras[index];
  72831. if (!camera.doNotSerialize) {
  72832. serializationObject.cameras.push(camera.serialize());
  72833. }
  72834. }
  72835. if (scene.activeCamera) {
  72836. serializationObject.activeCameraID = scene.activeCamera.id;
  72837. }
  72838. // Animations
  72839. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  72840. // Materials
  72841. serializationObject.materials = [];
  72842. serializationObject.multiMaterials = [];
  72843. var material;
  72844. for (index = 0; index < scene.materials.length; index++) {
  72845. material = scene.materials[index];
  72846. if (!material.doNotSerialize) {
  72847. serializationObject.materials.push(material.serialize());
  72848. }
  72849. }
  72850. // MultiMaterials
  72851. serializationObject.multiMaterials = [];
  72852. for (index = 0; index < scene.multiMaterials.length; index++) {
  72853. var multiMaterial = scene.multiMaterials[index];
  72854. serializationObject.multiMaterials.push(multiMaterial.serialize());
  72855. }
  72856. // Skeletons
  72857. serializationObject.skeletons = [];
  72858. for (index = 0; index < scene.skeletons.length; index++) {
  72859. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  72860. }
  72861. // Geometries
  72862. serializationObject.geometries = {};
  72863. serializationObject.geometries.boxes = [];
  72864. serializationObject.geometries.spheres = [];
  72865. serializationObject.geometries.cylinders = [];
  72866. serializationObject.geometries.toruses = [];
  72867. serializationObject.geometries.grounds = [];
  72868. serializationObject.geometries.planes = [];
  72869. serializationObject.geometries.torusKnots = [];
  72870. serializationObject.geometries.vertexData = [];
  72871. serializedGeometries = [];
  72872. var geometries = scene.getGeometries();
  72873. for (index = 0; index < geometries.length; index++) {
  72874. var geometry = geometries[index];
  72875. if (geometry.isReady()) {
  72876. serializeGeometry(geometry, serializationObject.geometries);
  72877. }
  72878. }
  72879. // Meshes
  72880. serializationObject.meshes = [];
  72881. for (index = 0; index < scene.meshes.length; index++) {
  72882. var abstractMesh = scene.meshes[index];
  72883. if (abstractMesh instanceof BABYLON.Mesh) {
  72884. var mesh = abstractMesh;
  72885. if (!mesh.doNotSerialize) {
  72886. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72887. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  72888. }
  72889. }
  72890. }
  72891. }
  72892. // Particles Systems
  72893. serializationObject.particleSystems = [];
  72894. for (index = 0; index < scene.particleSystems.length; index++) {
  72895. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  72896. }
  72897. // Lens flares
  72898. serializationObject.lensFlareSystems = [];
  72899. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  72900. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  72901. }
  72902. // Shadows
  72903. serializationObject.shadowGenerators = [];
  72904. for (index = 0; index < scene.lights.length; index++) {
  72905. light = scene.lights[index];
  72906. var shadowGenerator = light.getShadowGenerator();
  72907. if (shadowGenerator) {
  72908. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  72909. }
  72910. }
  72911. // Action Manager
  72912. if (scene.actionManager) {
  72913. serializationObject.actions = scene.actionManager.serialize("scene");
  72914. }
  72915. // Audio
  72916. serializationObject.sounds = [];
  72917. for (index = 0; index < scene.soundTracks.length; index++) {
  72918. var soundtrack = scene.soundTracks[index];
  72919. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  72920. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  72921. }
  72922. }
  72923. return serializationObject;
  72924. };
  72925. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  72926. if (withParents === void 0) { withParents = false; }
  72927. if (withChildren === void 0) { withChildren = false; }
  72928. var serializationObject = {};
  72929. SceneSerializer.ClearCache();
  72930. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  72931. if (withParents || withChildren) {
  72932. //deliberate for loop! not for each, appended should be processed as well.
  72933. for (var i = 0; i < toSerialize.length; ++i) {
  72934. if (withChildren) {
  72935. toSerialize[i].getDescendants().forEach(function (node) {
  72936. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  72937. toSerialize.push(node);
  72938. }
  72939. });
  72940. }
  72941. //make sure the array doesn't contain the object already
  72942. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  72943. toSerialize.push(toSerialize[i].parent);
  72944. }
  72945. }
  72946. }
  72947. toSerialize.forEach(function (mesh) {
  72948. finalizeSingleMesh(mesh, serializationObject);
  72949. });
  72950. return serializationObject;
  72951. };
  72952. return SceneSerializer;
  72953. }());
  72954. BABYLON.SceneSerializer = SceneSerializer;
  72955. })(BABYLON || (BABYLON = {}));
  72956. //# sourceMappingURL=babylon.sceneSerializer.js.map
  72957. var BABYLON;
  72958. (function (BABYLON) {
  72959. var ReflectionProbe = /** @class */ (function () {
  72960. function ReflectionProbe(name, size, scene, generateMipMaps) {
  72961. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72962. var _this = this;
  72963. this.name = name;
  72964. this._viewMatrix = BABYLON.Matrix.Identity();
  72965. this._target = BABYLON.Vector3.Zero();
  72966. this._add = BABYLON.Vector3.Zero();
  72967. this.invertYAxis = false;
  72968. this.position = BABYLON.Vector3.Zero();
  72969. this._scene = scene;
  72970. this._scene.reflectionProbes.push(this);
  72971. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  72972. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  72973. switch (faceIndex) {
  72974. case 0:
  72975. _this._add.copyFromFloats(1, 0, 0);
  72976. break;
  72977. case 1:
  72978. _this._add.copyFromFloats(-1, 0, 0);
  72979. break;
  72980. case 2:
  72981. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  72982. break;
  72983. case 3:
  72984. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  72985. break;
  72986. case 4:
  72987. _this._add.copyFromFloats(0, 0, 1);
  72988. break;
  72989. case 5:
  72990. _this._add.copyFromFloats(0, 0, -1);
  72991. break;
  72992. }
  72993. if (_this._attachedMesh) {
  72994. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  72995. }
  72996. _this.position.addToRef(_this._add, _this._target);
  72997. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  72998. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  72999. scene._forcedViewPosition = _this.position;
  73000. });
  73001. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  73002. scene._forcedViewPosition = null;
  73003. scene.updateTransformMatrix(true);
  73004. });
  73005. if (scene.activeCamera) {
  73006. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73007. }
  73008. }
  73009. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  73010. get: function () {
  73011. return this._renderTargetTexture.samples;
  73012. },
  73013. set: function (value) {
  73014. this._renderTargetTexture.samples = value;
  73015. },
  73016. enumerable: true,
  73017. configurable: true
  73018. });
  73019. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  73020. get: function () {
  73021. return this._renderTargetTexture.refreshRate;
  73022. },
  73023. set: function (value) {
  73024. this._renderTargetTexture.refreshRate = value;
  73025. },
  73026. enumerable: true,
  73027. configurable: true
  73028. });
  73029. ReflectionProbe.prototype.getScene = function () {
  73030. return this._scene;
  73031. };
  73032. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  73033. get: function () {
  73034. return this._renderTargetTexture;
  73035. },
  73036. enumerable: true,
  73037. configurable: true
  73038. });
  73039. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  73040. get: function () {
  73041. return this._renderTargetTexture.renderList;
  73042. },
  73043. enumerable: true,
  73044. configurable: true
  73045. });
  73046. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  73047. this._attachedMesh = mesh;
  73048. };
  73049. /**
  73050. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73051. *
  73052. * @param renderingGroupId The rendering group id corresponding to its index
  73053. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73054. */
  73055. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73056. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73057. };
  73058. ReflectionProbe.prototype.dispose = function () {
  73059. var index = this._scene.reflectionProbes.indexOf(this);
  73060. if (index !== -1) {
  73061. // Remove from the scene if found
  73062. this._scene.reflectionProbes.splice(index, 1);
  73063. }
  73064. if (this._renderTargetTexture) {
  73065. this._renderTargetTexture.dispose();
  73066. this._renderTargetTexture = null;
  73067. }
  73068. };
  73069. return ReflectionProbe;
  73070. }());
  73071. BABYLON.ReflectionProbe = ReflectionProbe;
  73072. })(BABYLON || (BABYLON = {}));
  73073. //# sourceMappingURL=babylon.reflectionProbe.js.map
  73074. var BABYLON;
  73075. (function (BABYLON) {
  73076. var Layer = /** @class */ (function () {
  73077. function Layer(name, imgUrl, scene, isBackground, color) {
  73078. this.name = name;
  73079. this.scale = new BABYLON.Vector2(1, 1);
  73080. this.offset = new BABYLON.Vector2(0, 0);
  73081. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  73082. this.layerMask = 0x0FFFFFFF;
  73083. this._vertexBuffers = {};
  73084. // Events
  73085. /**
  73086. * An event triggered when the layer is disposed.
  73087. * @type {BABYLON.Observable}
  73088. */
  73089. this.onDisposeObservable = new BABYLON.Observable();
  73090. /**
  73091. * An event triggered before rendering the scene
  73092. * @type {BABYLON.Observable}
  73093. */
  73094. this.onBeforeRenderObservable = new BABYLON.Observable();
  73095. /**
  73096. * An event triggered after rendering the scene
  73097. * @type {BABYLON.Observable}
  73098. */
  73099. this.onAfterRenderObservable = new BABYLON.Observable();
  73100. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  73101. this.isBackground = isBackground === undefined ? true : isBackground;
  73102. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  73103. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  73104. this._scene.layers.push(this);
  73105. var engine = this._scene.getEngine();
  73106. // VBO
  73107. var vertices = [];
  73108. vertices.push(1, 1);
  73109. vertices.push(-1, 1);
  73110. vertices.push(-1, -1);
  73111. vertices.push(1, -1);
  73112. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73113. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73114. this._createIndexBuffer();
  73115. // Effects
  73116. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  73117. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  73118. }
  73119. Object.defineProperty(Layer.prototype, "onDispose", {
  73120. set: function (callback) {
  73121. if (this._onDisposeObserver) {
  73122. this.onDisposeObservable.remove(this._onDisposeObserver);
  73123. }
  73124. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  73125. },
  73126. enumerable: true,
  73127. configurable: true
  73128. });
  73129. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  73130. set: function (callback) {
  73131. if (this._onBeforeRenderObserver) {
  73132. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73133. }
  73134. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73135. },
  73136. enumerable: true,
  73137. configurable: true
  73138. });
  73139. Object.defineProperty(Layer.prototype, "onAfterRender", {
  73140. set: function (callback) {
  73141. if (this._onAfterRenderObserver) {
  73142. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73143. }
  73144. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73145. },
  73146. enumerable: true,
  73147. configurable: true
  73148. });
  73149. Layer.prototype._createIndexBuffer = function () {
  73150. var engine = this._scene.getEngine();
  73151. // Indices
  73152. var indices = [];
  73153. indices.push(0);
  73154. indices.push(1);
  73155. indices.push(2);
  73156. indices.push(0);
  73157. indices.push(2);
  73158. indices.push(3);
  73159. this._indexBuffer = engine.createIndexBuffer(indices);
  73160. };
  73161. Layer.prototype._rebuild = function () {
  73162. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73163. if (vb) {
  73164. vb._rebuild();
  73165. }
  73166. this._createIndexBuffer();
  73167. };
  73168. Layer.prototype.render = function () {
  73169. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  73170. // Check
  73171. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  73172. return;
  73173. var engine = this._scene.getEngine();
  73174. this.onBeforeRenderObservable.notifyObservers(this);
  73175. // Render
  73176. engine.enableEffect(currentEffect);
  73177. engine.setState(false);
  73178. // Texture
  73179. currentEffect.setTexture("textureSampler", this.texture);
  73180. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  73181. // Color
  73182. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  73183. // Scale / offset
  73184. currentEffect.setVector2("offset", this.offset);
  73185. currentEffect.setVector2("scale", this.scale);
  73186. // VBOs
  73187. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73188. // Draw order
  73189. if (!this.alphaTest) {
  73190. engine.setAlphaMode(this.alphaBlendingMode);
  73191. engine.draw(true, 0, 6);
  73192. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73193. }
  73194. else {
  73195. engine.draw(true, 0, 6);
  73196. }
  73197. this.onAfterRenderObservable.notifyObservers(this);
  73198. };
  73199. Layer.prototype.dispose = function () {
  73200. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73201. if (vertexBuffer) {
  73202. vertexBuffer.dispose();
  73203. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73204. }
  73205. if (this._indexBuffer) {
  73206. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73207. this._indexBuffer = null;
  73208. }
  73209. if (this.texture) {
  73210. this.texture.dispose();
  73211. this.texture = null;
  73212. }
  73213. // Remove from scene
  73214. var index = this._scene.layers.indexOf(this);
  73215. this._scene.layers.splice(index, 1);
  73216. // Callback
  73217. this.onDisposeObservable.notifyObservers(this);
  73218. this.onDisposeObservable.clear();
  73219. this.onAfterRenderObservable.clear();
  73220. this.onBeforeRenderObservable.clear();
  73221. };
  73222. return Layer;
  73223. }());
  73224. BABYLON.Layer = Layer;
  73225. })(BABYLON || (BABYLON = {}));
  73226. //# sourceMappingURL=babylon.layer.js.map
  73227. var BABYLON;
  73228. (function (BABYLON) {
  73229. var TextureTools = /** @class */ (function () {
  73230. function TextureTools() {
  73231. }
  73232. /**
  73233. * Uses the GPU to create a copy texture rescaled at a given size
  73234. * @param texture Texture to copy from
  73235. * @param width Desired width
  73236. * @param height Desired height
  73237. * @return Generated texture
  73238. */
  73239. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  73240. if (useBilinearMode === void 0) { useBilinearMode = true; }
  73241. var scene = texture.getScene();
  73242. var engine = scene.getEngine();
  73243. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  73244. rtt.wrapU = texture.wrapU;
  73245. rtt.wrapV = texture.wrapV;
  73246. rtt.uOffset = texture.uOffset;
  73247. rtt.vOffset = texture.vOffset;
  73248. rtt.uScale = texture.uScale;
  73249. rtt.vScale = texture.vScale;
  73250. rtt.uAng = texture.uAng;
  73251. rtt.vAng = texture.vAng;
  73252. rtt.wAng = texture.wAng;
  73253. rtt.coordinatesIndex = texture.coordinatesIndex;
  73254. rtt.level = texture.level;
  73255. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  73256. rtt._texture.isReady = false;
  73257. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73258. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73259. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73260. passPostProcess.getEffect().executeWhenCompiled(function () {
  73261. passPostProcess.onApply = function (effect) {
  73262. effect.setTexture("textureSampler", texture);
  73263. };
  73264. var internalTexture = rtt.getInternalTexture();
  73265. if (internalTexture) {
  73266. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  73267. engine.unBindFramebuffer(internalTexture);
  73268. rtt.disposeFramebufferObjects();
  73269. passPostProcess.dispose();
  73270. internalTexture.isReady = true;
  73271. }
  73272. });
  73273. return rtt;
  73274. };
  73275. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  73276. if (!scene._environmentBRDFTexture) {
  73277. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73278. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73279. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73280. scene._environmentBRDFTexture = texture;
  73281. }
  73282. return scene._environmentBRDFTexture;
  73283. };
  73284. 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=";
  73285. return TextureTools;
  73286. }());
  73287. BABYLON.TextureTools = TextureTools;
  73288. })(BABYLON || (BABYLON = {}));
  73289. //# sourceMappingURL=babylon.textureTools.js.map
  73290. var BABYLON;
  73291. (function (BABYLON) {
  73292. var FramingBehavior = /** @class */ (function () {
  73293. function FramingBehavior() {
  73294. this._mode = FramingBehavior.FitFrustumSidesMode;
  73295. this._radiusScale = 1.0;
  73296. this._positionScale = 0.5;
  73297. this._defaultElevation = 0.3;
  73298. this._elevationReturnTime = 1500;
  73299. this._elevationReturnWaitTime = 1000;
  73300. this._zoomStopsAnimation = false;
  73301. this._framingTime = 1500;
  73302. this._isPointerDown = false;
  73303. this._lastInteractionTime = -Infinity;
  73304. // Framing control
  73305. this._animatables = new Array();
  73306. this._betaIsAnimating = false;
  73307. }
  73308. Object.defineProperty(FramingBehavior.prototype, "name", {
  73309. get: function () {
  73310. return "Framing";
  73311. },
  73312. enumerable: true,
  73313. configurable: true
  73314. });
  73315. Object.defineProperty(FramingBehavior.prototype, "mode", {
  73316. /**
  73317. * Gets current mode used by the behavior.
  73318. */
  73319. get: function () {
  73320. return this._mode;
  73321. },
  73322. /**
  73323. * Sets the current mode used by the behavior
  73324. */
  73325. set: function (mode) {
  73326. this._mode = mode;
  73327. },
  73328. enumerable: true,
  73329. configurable: true
  73330. });
  73331. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  73332. /**
  73333. * Gets the scale applied to the radius
  73334. */
  73335. get: function () {
  73336. return this._radiusScale;
  73337. },
  73338. /**
  73339. * Sets the scale applied to the radius (1 by default)
  73340. */
  73341. set: function (radius) {
  73342. this._radiusScale = radius;
  73343. },
  73344. enumerable: true,
  73345. configurable: true
  73346. });
  73347. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  73348. /**
  73349. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73350. */
  73351. get: function () {
  73352. return this._positionScale;
  73353. },
  73354. /**
  73355. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73356. */
  73357. set: function (scale) {
  73358. this._positionScale = scale;
  73359. },
  73360. enumerable: true,
  73361. configurable: true
  73362. });
  73363. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  73364. /**
  73365. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73366. * behaviour is triggered, in radians.
  73367. */
  73368. get: function () {
  73369. return this._defaultElevation;
  73370. },
  73371. /**
  73372. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73373. * behaviour is triggered, in radians.
  73374. */
  73375. set: function (elevation) {
  73376. this._defaultElevation = elevation;
  73377. },
  73378. enumerable: true,
  73379. configurable: true
  73380. });
  73381. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  73382. /**
  73383. * Gets the time (in milliseconds) taken to return to the default beta position.
  73384. * Negative value indicates camera should not return to default.
  73385. */
  73386. get: function () {
  73387. return this._elevationReturnTime;
  73388. },
  73389. /**
  73390. * Sets the time (in milliseconds) taken to return to the default beta position.
  73391. * Negative value indicates camera should not return to default.
  73392. */
  73393. set: function (speed) {
  73394. this._elevationReturnTime = speed;
  73395. },
  73396. enumerable: true,
  73397. configurable: true
  73398. });
  73399. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  73400. /**
  73401. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73402. */
  73403. get: function () {
  73404. return this._elevationReturnWaitTime;
  73405. },
  73406. /**
  73407. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73408. */
  73409. set: function (time) {
  73410. this._elevationReturnWaitTime = time;
  73411. },
  73412. enumerable: true,
  73413. configurable: true
  73414. });
  73415. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  73416. /**
  73417. * Gets the flag that indicates if user zooming should stop animation.
  73418. */
  73419. get: function () {
  73420. return this._zoomStopsAnimation;
  73421. },
  73422. /**
  73423. * Sets the flag that indicates if user zooming should stop animation.
  73424. */
  73425. set: function (flag) {
  73426. this._zoomStopsAnimation = flag;
  73427. },
  73428. enumerable: true,
  73429. configurable: true
  73430. });
  73431. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  73432. /**
  73433. * Gets the transition time when framing the mesh, in milliseconds
  73434. */
  73435. get: function () {
  73436. return this._framingTime;
  73437. },
  73438. /**
  73439. * Sets the transition time when framing the mesh, in milliseconds
  73440. */
  73441. set: function (time) {
  73442. this._framingTime = time;
  73443. },
  73444. enumerable: true,
  73445. configurable: true
  73446. });
  73447. FramingBehavior.prototype.attach = function (camera) {
  73448. var _this = this;
  73449. this._attachedCamera = camera;
  73450. var scene = this._attachedCamera.getScene();
  73451. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  73452. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73453. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73454. _this._isPointerDown = true;
  73455. return;
  73456. }
  73457. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73458. _this._isPointerDown = false;
  73459. }
  73460. });
  73461. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73462. if (mesh) {
  73463. _this.zoomOnMesh(mesh);
  73464. }
  73465. });
  73466. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73467. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73468. _this._applyUserInteraction();
  73469. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  73470. // back to the default position after a given timeout
  73471. _this._maintainCameraAboveGround();
  73472. });
  73473. };
  73474. FramingBehavior.prototype.detach = function () {
  73475. if (!this._attachedCamera) {
  73476. return;
  73477. }
  73478. var scene = this._attachedCamera.getScene();
  73479. if (this._onPrePointerObservableObserver) {
  73480. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73481. }
  73482. if (this._onAfterCheckInputsObserver) {
  73483. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73484. }
  73485. if (this._onMeshTargetChangedObserver) {
  73486. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73487. }
  73488. this._attachedCamera = null;
  73489. };
  73490. /**
  73491. * Targets the given mesh and updates zoom level accordingly.
  73492. * @param mesh The mesh to target.
  73493. * @param radius Optional. If a cached radius position already exists, overrides default.
  73494. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73495. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73496. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73497. */
  73498. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  73499. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73500. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73501. mesh.computeWorldMatrix(true);
  73502. var boundingBox = mesh.getBoundingInfo().boundingBox;
  73503. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  73504. };
  73505. /**
  73506. * Targets the given mesh and updates zoom level accordingly.
  73507. * @param mesh The mesh to target.
  73508. * @param radius Optional. If a cached radius position already exists, overrides default.
  73509. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73510. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73511. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73512. */
  73513. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  73514. var _this = this;
  73515. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73516. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73517. var zoomTarget;
  73518. if (!this._attachedCamera) {
  73519. return;
  73520. }
  73521. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  73522. var bottom = minimumWorld.y;
  73523. var top = maximumWorld.y;
  73524. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  73525. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  73526. if (focusOnOriginXZ) {
  73527. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  73528. }
  73529. else {
  73530. var centerWorld = minimumWorld.add(radiusWorld);
  73531. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  73532. }
  73533. if (!this._vectorTransition) {
  73534. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  73535. }
  73536. this._betaIsAnimating = true;
  73537. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  73538. if (animatable) {
  73539. this._animatables.push(animatable);
  73540. }
  73541. // sets the radius and lower radius bounds
  73542. // Small delta ensures camera is not always at lower zoom limit.
  73543. var radius = 0;
  73544. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  73545. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73546. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  73547. radius = position;
  73548. }
  73549. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73550. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73551. if (this._attachedCamera.lowerRadiusLimit === null) {
  73552. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  73553. }
  73554. }
  73555. // Set sensibilities
  73556. var extend = maximumWorld.subtract(minimumWorld).length();
  73557. this._attachedCamera.panningSensibility = 5000 / extend;
  73558. this._attachedCamera.wheelPrecision = 100 / radius;
  73559. // transition to new radius
  73560. if (!this._radiusTransition) {
  73561. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73562. }
  73563. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  73564. if (onAnimationEnd) {
  73565. onAnimationEnd();
  73566. }
  73567. if (_this._attachedCamera) {
  73568. _this._attachedCamera.storeState();
  73569. }
  73570. });
  73571. if (animatable) {
  73572. this._animatables.push(animatable);
  73573. }
  73574. };
  73575. /**
  73576. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  73577. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  73578. * frustum width.
  73579. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  73580. * to fully enclose the mesh in the viewing frustum.
  73581. */
  73582. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  73583. var size = maximumWorld.subtract(minimumWorld);
  73584. var boxVectorGlobalDiagonal = size.length();
  73585. var frustumSlope = this._getFrustumSlope();
  73586. // Formula for setting distance
  73587. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  73588. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  73589. // Horizon distance
  73590. var radius = radiusWithoutFraming * this._radiusScale;
  73591. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  73592. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  73593. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  73594. var camera = this._attachedCamera;
  73595. if (!camera) {
  73596. return 0;
  73597. }
  73598. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73599. // Don't exceed the requested limit
  73600. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  73601. }
  73602. // Don't exceed the upper radius limit
  73603. if (camera.upperRadiusLimit) {
  73604. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  73605. }
  73606. return distance;
  73607. };
  73608. /**
  73609. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  73610. * is automatically returned to its default position (expected to be above ground plane).
  73611. */
  73612. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  73613. var _this = this;
  73614. if (this._elevationReturnTime < 0) {
  73615. return;
  73616. }
  73617. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  73618. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  73619. var limitBeta = Math.PI * 0.5;
  73620. // Bring the camera back up if below the ground plane
  73621. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  73622. this._betaIsAnimating = true;
  73623. //Transition to new position
  73624. this.stopAllAnimations();
  73625. if (!this._betaTransition) {
  73626. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73627. }
  73628. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  73629. _this._clearAnimationLocks();
  73630. _this.stopAllAnimations();
  73631. });
  73632. if (animatabe) {
  73633. this._animatables.push(animatabe);
  73634. }
  73635. }
  73636. };
  73637. /**
  73638. * Returns the frustum slope based on the canvas ratio and camera FOV
  73639. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  73640. */
  73641. FramingBehavior.prototype._getFrustumSlope = function () {
  73642. // Calculate the viewport ratio
  73643. // Aspect Ratio is Height/Width.
  73644. var camera = this._attachedCamera;
  73645. if (!camera) {
  73646. return BABYLON.Vector2.Zero();
  73647. }
  73648. var engine = camera.getScene().getEngine();
  73649. var aspectRatio = engine.getAspectRatio(camera);
  73650. // Camera FOV is the vertical field of view (top-bottom) in radians.
  73651. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  73652. var frustumSlopeY = Math.tan(camera.fov / 2);
  73653. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  73654. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  73655. // along the forward vector.
  73656. var frustumSlopeX = frustumSlopeY * aspectRatio;
  73657. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  73658. };
  73659. /**
  73660. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  73661. */
  73662. FramingBehavior.prototype._clearAnimationLocks = function () {
  73663. this._betaIsAnimating = false;
  73664. };
  73665. /**
  73666. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  73667. */
  73668. FramingBehavior.prototype._applyUserInteraction = function () {
  73669. if (this.isUserIsMoving) {
  73670. this._lastInteractionTime = BABYLON.Tools.Now;
  73671. this.stopAllAnimations();
  73672. this._clearAnimationLocks();
  73673. }
  73674. };
  73675. /**
  73676. * Stops and removes all animations that have been applied to the camera
  73677. */
  73678. FramingBehavior.prototype.stopAllAnimations = function () {
  73679. if (this._attachedCamera) {
  73680. this._attachedCamera.animations = [];
  73681. }
  73682. while (this._animatables.length) {
  73683. if (this._animatables[0]) {
  73684. this._animatables[0].onAnimationEnd = null;
  73685. this._animatables[0].stop();
  73686. }
  73687. this._animatables.shift();
  73688. }
  73689. };
  73690. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  73691. /**
  73692. * Gets a value indicating if the user is moving the camera
  73693. */
  73694. get: function () {
  73695. if (!this._attachedCamera) {
  73696. return false;
  73697. }
  73698. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  73699. this._attachedCamera.inertialBetaOffset !== 0 ||
  73700. this._attachedCamera.inertialRadiusOffset !== 0 ||
  73701. this._attachedCamera.inertialPanningX !== 0 ||
  73702. this._attachedCamera.inertialPanningY !== 0 ||
  73703. this._isPointerDown;
  73704. },
  73705. enumerable: true,
  73706. configurable: true
  73707. });
  73708. /**
  73709. * The easing function used by animations
  73710. */
  73711. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  73712. /**
  73713. * The easing mode used by animations
  73714. */
  73715. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  73716. // Statics
  73717. /**
  73718. * The camera can move all the way towards the mesh.
  73719. */
  73720. FramingBehavior.IgnoreBoundsSizeMode = 0;
  73721. /**
  73722. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  73723. */
  73724. FramingBehavior.FitFrustumSidesMode = 1;
  73725. return FramingBehavior;
  73726. }());
  73727. BABYLON.FramingBehavior = FramingBehavior;
  73728. })(BABYLON || (BABYLON = {}));
  73729. //# sourceMappingURL=babylon.framingBehavior.js.map
  73730. var BABYLON;
  73731. (function (BABYLON) {
  73732. /**
  73733. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  73734. */
  73735. var BouncingBehavior = /** @class */ (function () {
  73736. function BouncingBehavior() {
  73737. /**
  73738. * The duration of the animation, in milliseconds
  73739. */
  73740. this.transitionDuration = 450;
  73741. /**
  73742. * Length of the distance animated by the transition when lower radius is reached
  73743. */
  73744. this.lowerRadiusTransitionRange = 2;
  73745. /**
  73746. * Length of the distance animated by the transition when upper radius is reached
  73747. */
  73748. this.upperRadiusTransitionRange = -2;
  73749. this._autoTransitionRange = false;
  73750. // Animations
  73751. this._radiusIsAnimating = false;
  73752. this._radiusBounceTransition = null;
  73753. this._animatables = new Array();
  73754. }
  73755. Object.defineProperty(BouncingBehavior.prototype, "name", {
  73756. get: function () {
  73757. return "Bouncing";
  73758. },
  73759. enumerable: true,
  73760. configurable: true
  73761. });
  73762. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  73763. /**
  73764. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73765. */
  73766. get: function () {
  73767. return this._autoTransitionRange;
  73768. },
  73769. /**
  73770. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73771. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  73772. */
  73773. set: function (value) {
  73774. var _this = this;
  73775. if (this._autoTransitionRange === value) {
  73776. return;
  73777. }
  73778. this._autoTransitionRange = value;
  73779. var camera = this._attachedCamera;
  73780. if (!camera) {
  73781. return;
  73782. }
  73783. if (value) {
  73784. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73785. if (!mesh) {
  73786. return;
  73787. }
  73788. mesh.computeWorldMatrix(true);
  73789. var diagonal = mesh.getBoundingInfo().diagonalLength;
  73790. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  73791. _this.upperRadiusTransitionRange = diagonal * 0.05;
  73792. });
  73793. }
  73794. else if (this._onMeshTargetChangedObserver) {
  73795. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73796. }
  73797. },
  73798. enumerable: true,
  73799. configurable: true
  73800. });
  73801. BouncingBehavior.prototype.attach = function (camera) {
  73802. var _this = this;
  73803. this._attachedCamera = camera;
  73804. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73805. if (!_this._attachedCamera) {
  73806. return;
  73807. }
  73808. // Add the bounce animation to the lower radius limit
  73809. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  73810. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  73811. }
  73812. // Add the bounce animation to the upper radius limit
  73813. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  73814. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  73815. }
  73816. });
  73817. };
  73818. BouncingBehavior.prototype.detach = function () {
  73819. if (!this._attachedCamera) {
  73820. return;
  73821. }
  73822. if (this._onAfterCheckInputsObserver) {
  73823. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73824. }
  73825. if (this._onMeshTargetChangedObserver) {
  73826. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73827. }
  73828. this._attachedCamera = null;
  73829. };
  73830. /**
  73831. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  73832. * @param radiusLimit The limit to check against.
  73833. * @return Bool to indicate if at limit.
  73834. */
  73835. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  73836. if (!this._attachedCamera) {
  73837. return false;
  73838. }
  73839. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  73840. return true;
  73841. }
  73842. return false;
  73843. };
  73844. /**
  73845. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  73846. * @param radiusDelta The delta by which to animate to. Can be negative.
  73847. */
  73848. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  73849. var _this = this;
  73850. if (!this._attachedCamera) {
  73851. return;
  73852. }
  73853. if (!this._radiusBounceTransition) {
  73854. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  73855. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  73856. }
  73857. // Prevent zoom until bounce has completed
  73858. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  73859. this._attachedCamera.wheelPrecision = Infinity;
  73860. this._attachedCamera.inertialRadiusOffset = 0;
  73861. // Animate to the radius limit
  73862. this.stopAllAnimations();
  73863. this._radiusIsAnimating = true;
  73864. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  73865. if (animatable) {
  73866. this._animatables.push(animatable);
  73867. }
  73868. };
  73869. /**
  73870. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  73871. */
  73872. BouncingBehavior.prototype._clearAnimationLocks = function () {
  73873. this._radiusIsAnimating = false;
  73874. if (this._attachedCamera) {
  73875. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  73876. }
  73877. };
  73878. /**
  73879. * Stops and removes all animations that have been applied to the camera
  73880. */
  73881. BouncingBehavior.prototype.stopAllAnimations = function () {
  73882. if (this._attachedCamera) {
  73883. this._attachedCamera.animations = [];
  73884. }
  73885. while (this._animatables.length) {
  73886. this._animatables[0].onAnimationEnd = null;
  73887. this._animatables[0].stop();
  73888. this._animatables.shift();
  73889. }
  73890. };
  73891. /**
  73892. * The easing function used by animations
  73893. */
  73894. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  73895. /**
  73896. * The easing mode used by animations
  73897. */
  73898. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  73899. return BouncingBehavior;
  73900. }());
  73901. BABYLON.BouncingBehavior = BouncingBehavior;
  73902. })(BABYLON || (BABYLON = {}));
  73903. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  73904. var BABYLON;
  73905. (function (BABYLON) {
  73906. var AutoRotationBehavior = /** @class */ (function () {
  73907. function AutoRotationBehavior() {
  73908. this._zoomStopsAnimation = false;
  73909. this._idleRotationSpeed = 0.05;
  73910. this._idleRotationWaitTime = 2000;
  73911. this._idleRotationSpinupTime = 2000;
  73912. this._isPointerDown = false;
  73913. this._lastFrameTime = null;
  73914. this._lastInteractionTime = -Infinity;
  73915. this._cameraRotationSpeed = 0;
  73916. this._lastFrameRadius = 0;
  73917. }
  73918. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  73919. get: function () {
  73920. return "AutoRotation";
  73921. },
  73922. enumerable: true,
  73923. configurable: true
  73924. });
  73925. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  73926. /**
  73927. * Gets the flag that indicates if user zooming should stop animation.
  73928. */
  73929. get: function () {
  73930. return this._zoomStopsAnimation;
  73931. },
  73932. /**
  73933. * Sets the flag that indicates if user zooming should stop animation.
  73934. */
  73935. set: function (flag) {
  73936. this._zoomStopsAnimation = flag;
  73937. },
  73938. enumerable: true,
  73939. configurable: true
  73940. });
  73941. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  73942. /**
  73943. * Gets the default speed at which the camera rotates around the model.
  73944. */
  73945. get: function () {
  73946. return this._idleRotationSpeed;
  73947. },
  73948. /**
  73949. * Sets the default speed at which the camera rotates around the model.
  73950. */
  73951. set: function (speed) {
  73952. this._idleRotationSpeed = speed;
  73953. },
  73954. enumerable: true,
  73955. configurable: true
  73956. });
  73957. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  73958. /**
  73959. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  73960. */
  73961. get: function () {
  73962. return this._idleRotationWaitTime;
  73963. },
  73964. /**
  73965. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  73966. */
  73967. set: function (time) {
  73968. this._idleRotationWaitTime = time;
  73969. },
  73970. enumerable: true,
  73971. configurable: true
  73972. });
  73973. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  73974. /**
  73975. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  73976. */
  73977. get: function () {
  73978. return this._idleRotationSpinupTime;
  73979. },
  73980. /**
  73981. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  73982. */
  73983. set: function (time) {
  73984. this._idleRotationSpinupTime = time;
  73985. },
  73986. enumerable: true,
  73987. configurable: true
  73988. });
  73989. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  73990. /**
  73991. * Gets a value indicating if the camera is currently rotating because of this behavior
  73992. */
  73993. get: function () {
  73994. return Math.abs(this._cameraRotationSpeed) > 0;
  73995. },
  73996. enumerable: true,
  73997. configurable: true
  73998. });
  73999. AutoRotationBehavior.prototype.attach = function (camera) {
  74000. var _this = this;
  74001. this._attachedCamera = camera;
  74002. var scene = this._attachedCamera.getScene();
  74003. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74004. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74005. _this._isPointerDown = true;
  74006. return;
  74007. }
  74008. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74009. _this._isPointerDown = false;
  74010. }
  74011. });
  74012. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74013. var now = BABYLON.Tools.Now;
  74014. var dt = 0;
  74015. if (_this._lastFrameTime != null) {
  74016. dt = now - _this._lastFrameTime;
  74017. }
  74018. _this._lastFrameTime = now;
  74019. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74020. _this._applyUserInteraction();
  74021. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  74022. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  74023. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  74024. // Step camera rotation by rotation speed
  74025. if (_this._attachedCamera) {
  74026. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  74027. }
  74028. });
  74029. };
  74030. AutoRotationBehavior.prototype.detach = function () {
  74031. if (!this._attachedCamera) {
  74032. return;
  74033. }
  74034. var scene = this._attachedCamera.getScene();
  74035. if (this._onPrePointerObservableObserver) {
  74036. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74037. }
  74038. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74039. this._attachedCamera = null;
  74040. };
  74041. /**
  74042. * Returns true if user is scrolling.
  74043. * @return true if user is scrolling.
  74044. */
  74045. AutoRotationBehavior.prototype._userIsZooming = function () {
  74046. if (!this._attachedCamera) {
  74047. return false;
  74048. }
  74049. return this._attachedCamera.inertialRadiusOffset !== 0;
  74050. };
  74051. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  74052. if (!this._attachedCamera) {
  74053. return false;
  74054. }
  74055. var zoomHasHitLimit = false;
  74056. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  74057. zoomHasHitLimit = true;
  74058. }
  74059. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  74060. this._lastFrameRadius = this._attachedCamera.radius;
  74061. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  74062. };
  74063. /**
  74064. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74065. */
  74066. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  74067. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  74068. this._lastInteractionTime = BABYLON.Tools.Now;
  74069. }
  74070. };
  74071. // Tools
  74072. AutoRotationBehavior.prototype._userIsMoving = function () {
  74073. if (!this._attachedCamera) {
  74074. return false;
  74075. }
  74076. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74077. this._attachedCamera.inertialBetaOffset !== 0 ||
  74078. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74079. this._attachedCamera.inertialPanningX !== 0 ||
  74080. this._attachedCamera.inertialPanningY !== 0 ||
  74081. this._isPointerDown;
  74082. };
  74083. return AutoRotationBehavior;
  74084. }());
  74085. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  74086. })(BABYLON || (BABYLON = {}));
  74087. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  74088. var BABYLON;
  74089. (function (BABYLON) {
  74090. /**
  74091. * This class can be used to get instrumentation data from a Babylon engine
  74092. */
  74093. var EngineInstrumentation = /** @class */ (function () {
  74094. function EngineInstrumentation(engine) {
  74095. this.engine = engine;
  74096. this._captureGPUFrameTime = false;
  74097. this._gpuFrameTime = new BABYLON.PerfCounter();
  74098. this._captureShaderCompilationTime = false;
  74099. this._shaderCompilationTime = new BABYLON.PerfCounter();
  74100. // Observers
  74101. this._onBeginFrameObserver = null;
  74102. this._onEndFrameObserver = null;
  74103. this._onBeforeShaderCompilationObserver = null;
  74104. this._onAfterShaderCompilationObserver = null;
  74105. }
  74106. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  74107. // Properties
  74108. /**
  74109. * Gets the perf counter used for GPU frame time
  74110. */
  74111. get: function () {
  74112. return this._gpuFrameTime;
  74113. },
  74114. enumerable: true,
  74115. configurable: true
  74116. });
  74117. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  74118. /**
  74119. * Gets the GPU frame time capture status
  74120. */
  74121. get: function () {
  74122. return this._captureGPUFrameTime;
  74123. },
  74124. /**
  74125. * Enable or disable the GPU frame time capture
  74126. */
  74127. set: function (value) {
  74128. var _this = this;
  74129. if (value === this._captureGPUFrameTime) {
  74130. return;
  74131. }
  74132. if (value) {
  74133. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  74134. if (!_this._gpuFrameTimeToken) {
  74135. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  74136. }
  74137. });
  74138. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  74139. if (!_this._gpuFrameTimeToken) {
  74140. return;
  74141. }
  74142. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  74143. if (time > -1) {
  74144. _this._gpuFrameTimeToken = null;
  74145. _this._gpuFrameTime.fetchNewFrame();
  74146. _this._gpuFrameTime.addCount(time, true);
  74147. }
  74148. });
  74149. }
  74150. else {
  74151. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74152. this._onBeginFrameObserver = null;
  74153. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74154. this._onEndFrameObserver = null;
  74155. }
  74156. },
  74157. enumerable: true,
  74158. configurable: true
  74159. });
  74160. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  74161. /**
  74162. * Gets the perf counter used for shader compilation time
  74163. */
  74164. get: function () {
  74165. return this._shaderCompilationTime;
  74166. },
  74167. enumerable: true,
  74168. configurable: true
  74169. });
  74170. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  74171. /**
  74172. * Gets the shader compilation time capture status
  74173. */
  74174. get: function () {
  74175. return this._captureShaderCompilationTime;
  74176. },
  74177. /**
  74178. * Enable or disable the shader compilation time capture
  74179. */
  74180. set: function (value) {
  74181. var _this = this;
  74182. if (value === this._captureShaderCompilationTime) {
  74183. return;
  74184. }
  74185. if (value) {
  74186. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  74187. _this._shaderCompilationTime.fetchNewFrame();
  74188. _this._shaderCompilationTime.beginMonitoring();
  74189. });
  74190. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  74191. _this._shaderCompilationTime.endMonitoring();
  74192. });
  74193. }
  74194. else {
  74195. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74196. this._onBeforeShaderCompilationObserver = null;
  74197. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74198. this._onAfterShaderCompilationObserver = null;
  74199. }
  74200. },
  74201. enumerable: true,
  74202. configurable: true
  74203. });
  74204. EngineInstrumentation.prototype.dispose = function () {
  74205. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74206. this._onBeginFrameObserver = null;
  74207. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74208. this._onEndFrameObserver = null;
  74209. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74210. this._onBeforeShaderCompilationObserver = null;
  74211. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74212. this._onAfterShaderCompilationObserver = null;
  74213. this.engine = null;
  74214. };
  74215. return EngineInstrumentation;
  74216. }());
  74217. BABYLON.EngineInstrumentation = EngineInstrumentation;
  74218. })(BABYLON || (BABYLON = {}));
  74219. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  74220. var BABYLON;
  74221. (function (BABYLON) {
  74222. /**
  74223. * This class can be used to get instrumentation data from a Babylon engine
  74224. */
  74225. var SceneInstrumentation = /** @class */ (function () {
  74226. function SceneInstrumentation(scene) {
  74227. var _this = this;
  74228. this.scene = scene;
  74229. this._captureActiveMeshesEvaluationTime = false;
  74230. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  74231. this._captureRenderTargetsRenderTime = false;
  74232. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  74233. this._captureFrameTime = false;
  74234. this._frameTime = new BABYLON.PerfCounter();
  74235. // Observers
  74236. this._onBeforeActiveMeshesEvaluationObserver = null;
  74237. this._onAfterActiveMeshesEvaluationObserver = null;
  74238. this._onBeforeRenderTargetsRenderObserver = null;
  74239. this._onAfterRenderTargetsRenderObserver = null;
  74240. this._onBeforeRenderObserver = null;
  74241. this._onAfterRenderObserver = null;
  74242. this._onBeforeRenderObserver = scene.onBeforeRenderObservable.add(function () {
  74243. if (_this._captureActiveMeshesEvaluationTime) {
  74244. _this._activeMeshesEvaluationTime.fetchNewFrame();
  74245. }
  74246. if (_this._captureRenderTargetsRenderTime) {
  74247. _this._renderTargetsRenderTime.fetchNewFrame();
  74248. }
  74249. if (_this._captureFrameTime) {
  74250. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  74251. _this._frameTime.beginMonitoring();
  74252. }
  74253. });
  74254. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  74255. if (_this._captureFrameTime) {
  74256. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  74257. _this._frameTime.endMonitoring();
  74258. }
  74259. });
  74260. }
  74261. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTime", {
  74262. // Properties
  74263. /**
  74264. * Gets the perf counter used for active meshes evaluation time
  74265. */
  74266. get: function () {
  74267. return this._activeMeshesEvaluationTime;
  74268. },
  74269. enumerable: true,
  74270. configurable: true
  74271. });
  74272. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  74273. /**
  74274. * Gets the active meshes evaluation time capture status
  74275. */
  74276. get: function () {
  74277. return this._captureActiveMeshesEvaluationTime;
  74278. },
  74279. /**
  74280. * Enable or disable the active meshes evaluation time capture
  74281. */
  74282. set: function (value) {
  74283. var _this = this;
  74284. if (value === this._captureActiveMeshesEvaluationTime) {
  74285. return;
  74286. }
  74287. if (value) {
  74288. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  74289. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  74290. _this._activeMeshesEvaluationTime.beginMonitoring();
  74291. });
  74292. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  74293. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  74294. _this._activeMeshesEvaluationTime.endMonitoring();
  74295. });
  74296. }
  74297. else {
  74298. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74299. this._onBeforeActiveMeshesEvaluationObserver = null;
  74300. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74301. this._onAfterActiveMeshesEvaluationObserver = null;
  74302. }
  74303. },
  74304. enumerable: true,
  74305. configurable: true
  74306. });
  74307. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  74308. /**
  74309. * Gets the perf counter used for render targets render time
  74310. */
  74311. get: function () {
  74312. return this._renderTargetsRenderTime;
  74313. },
  74314. enumerable: true,
  74315. configurable: true
  74316. });
  74317. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  74318. /**
  74319. * Gets the render targets render time capture status
  74320. */
  74321. get: function () {
  74322. return this._captureRenderTargetsRenderTime;
  74323. },
  74324. /**
  74325. * Enable or disable the render targets render time capture
  74326. */
  74327. set: function (value) {
  74328. var _this = this;
  74329. if (value === this._captureRenderTargetsRenderTime) {
  74330. return;
  74331. }
  74332. if (value) {
  74333. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  74334. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  74335. _this._renderTargetsRenderTime.beginMonitoring();
  74336. });
  74337. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  74338. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  74339. _this._renderTargetsRenderTime.endMonitoring(false);
  74340. });
  74341. }
  74342. else {
  74343. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74344. this._onBeforeRenderTargetsRenderObserver = null;
  74345. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74346. this._onAfterRenderTargetsRenderObserver = null;
  74347. }
  74348. },
  74349. enumerable: true,
  74350. configurable: true
  74351. });
  74352. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  74353. /**
  74354. * Gets the perf counter used for frame time capture
  74355. */
  74356. get: function () {
  74357. return this._frameTime;
  74358. },
  74359. enumerable: true,
  74360. configurable: true
  74361. });
  74362. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  74363. /**
  74364. * Gets the frame time capture status
  74365. */
  74366. get: function () {
  74367. return this._captureFrameTime;
  74368. },
  74369. /**
  74370. * Enable or disable the frame time capture
  74371. */
  74372. set: function (value) {
  74373. this._captureFrameTime = value;
  74374. },
  74375. enumerable: true,
  74376. configurable: true
  74377. });
  74378. SceneInstrumentation.prototype.dispose = function () {
  74379. this.scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74380. this._onBeforeRenderObserver = null;
  74381. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74382. this._onAfterRenderObserver = null;
  74383. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74384. this._onBeforeActiveMeshesEvaluationObserver = null;
  74385. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74386. this._onAfterActiveMeshesEvaluationObserver = null;
  74387. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74388. this._onBeforeRenderTargetsRenderObserver = null;
  74389. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74390. this._onAfterRenderTargetsRenderObserver = null;
  74391. this.scene = null;
  74392. };
  74393. return SceneInstrumentation;
  74394. }());
  74395. BABYLON.SceneInstrumentation = SceneInstrumentation;
  74396. })(BABYLON || (BABYLON = {}));
  74397. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  74398. var BABYLON;
  74399. (function (BABYLON) {
  74400. var _TimeToken = /** @class */ (function () {
  74401. function _TimeToken() {
  74402. this._timeElapsedQueryEnded = false;
  74403. }
  74404. return _TimeToken;
  74405. }());
  74406. BABYLON._TimeToken = _TimeToken;
  74407. })(BABYLON || (BABYLON = {}));
  74408. //# sourceMappingURL=babylon.timeToken.js.map
  74409. 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}"};
  74410. 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};"};
  74411. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74412. var BABYLON;
  74413. (function (BABYLON) {
  74414. var GridMaterialDefines = /** @class */ (function (_super) {
  74415. __extends(GridMaterialDefines, _super);
  74416. function GridMaterialDefines() {
  74417. var _this = _super.call(this) || this;
  74418. _this.TRANSPARENT = false;
  74419. _this.FOG = false;
  74420. _this.PREMULTIPLYALPHA = false;
  74421. _this.rebuild();
  74422. return _this;
  74423. }
  74424. return GridMaterialDefines;
  74425. }(BABYLON.MaterialDefines));
  74426. /**
  74427. * The grid materials allows you to wrap any shape with a grid.
  74428. * Colors are customizable.
  74429. */
  74430. var GridMaterial = /** @class */ (function (_super) {
  74431. __extends(GridMaterial, _super);
  74432. /**
  74433. * constructor
  74434. * @param name The name given to the material in order to identify it afterwards.
  74435. * @param scene The scene the material is used in.
  74436. */
  74437. function GridMaterial(name, scene) {
  74438. var _this = _super.call(this, name, scene) || this;
  74439. /**
  74440. * Main color of the grid (e.g. between lines)
  74441. */
  74442. _this.mainColor = BABYLON.Color3.Black();
  74443. /**
  74444. * Color of the grid lines.
  74445. */
  74446. _this.lineColor = BABYLON.Color3.Teal();
  74447. /**
  74448. * The scale of the grid compared to unit.
  74449. */
  74450. _this.gridRatio = 1.0;
  74451. /**
  74452. * Allows setting an offset for the grid lines.
  74453. */
  74454. _this.gridOffset = BABYLON.Vector3.Zero();
  74455. /**
  74456. * The frequency of thicker lines.
  74457. */
  74458. _this.majorUnitFrequency = 10;
  74459. /**
  74460. * The visibility of minor units in the grid.
  74461. */
  74462. _this.minorUnitVisibility = 0.33;
  74463. /**
  74464. * The grid opacity outside of the lines.
  74465. */
  74466. _this.opacity = 1.0;
  74467. /**
  74468. * Determine RBG output is premultiplied by alpha value.
  74469. */
  74470. _this.preMultiplyAlpha = false;
  74471. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  74472. return _this;
  74473. }
  74474. /**
  74475. * Returns wehter or not the grid requires alpha blending.
  74476. */
  74477. GridMaterial.prototype.needAlphaBlending = function () {
  74478. return this.opacity < 1.0;
  74479. };
  74480. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74481. if (this.isFrozen) {
  74482. if (this._wasPreviouslyReady && subMesh.effect) {
  74483. return true;
  74484. }
  74485. }
  74486. if (!subMesh._materialDefines) {
  74487. subMesh._materialDefines = new GridMaterialDefines();
  74488. }
  74489. var defines = subMesh._materialDefines;
  74490. var scene = this.getScene();
  74491. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  74492. if (this._renderId === scene.getRenderId()) {
  74493. return true;
  74494. }
  74495. }
  74496. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  74497. defines.TRANSPARENT = !defines.TRANSPARENT;
  74498. defines.markAsUnprocessed();
  74499. }
  74500. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  74501. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  74502. defines.markAsUnprocessed();
  74503. }
  74504. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  74505. // Get correct effect
  74506. if (defines.isDirty) {
  74507. defines.markAsProcessed();
  74508. scene.resetCachedMaterial();
  74509. // Attributes
  74510. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74511. // Defines
  74512. var join = defines.toString();
  74513. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  74514. }
  74515. if (!subMesh.effect || !subMesh.effect.isReady()) {
  74516. return false;
  74517. }
  74518. this._renderId = scene.getRenderId();
  74519. this._wasPreviouslyReady = true;
  74520. return true;
  74521. };
  74522. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  74523. var scene = this.getScene();
  74524. var defines = subMesh._materialDefines;
  74525. if (!defines) {
  74526. return;
  74527. }
  74528. var effect = subMesh.effect;
  74529. if (!effect) {
  74530. return;
  74531. }
  74532. this._activeEffect = effect;
  74533. // Matrices
  74534. this.bindOnlyWorldMatrix(world);
  74535. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  74536. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  74537. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  74538. // Uniforms
  74539. if (this._mustRebind(scene, effect)) {
  74540. this._activeEffect.setColor3("mainColor", this.mainColor);
  74541. this._activeEffect.setColor3("lineColor", this.lineColor);
  74542. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  74543. this._gridControl.x = this.gridRatio;
  74544. this._gridControl.y = Math.round(this.majorUnitFrequency);
  74545. this._gridControl.z = this.minorUnitVisibility;
  74546. this._gridControl.w = this.opacity;
  74547. this._activeEffect.setVector4("gridControl", this._gridControl);
  74548. }
  74549. // Fog
  74550. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  74551. this._afterBind(mesh, this._activeEffect);
  74552. };
  74553. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  74554. _super.prototype.dispose.call(this, forceDisposeEffect);
  74555. };
  74556. GridMaterial.prototype.clone = function (name) {
  74557. var _this = this;
  74558. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  74559. };
  74560. GridMaterial.prototype.serialize = function () {
  74561. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74562. serializationObject.customType = "BABYLON.GridMaterial";
  74563. return serializationObject;
  74564. };
  74565. GridMaterial.prototype.getClassName = function () {
  74566. return "GridMaterial";
  74567. };
  74568. GridMaterial.Parse = function (source, scene, rootUrl) {
  74569. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  74570. };
  74571. __decorate([
  74572. BABYLON.serializeAsColor3()
  74573. ], GridMaterial.prototype, "mainColor", void 0);
  74574. __decorate([
  74575. BABYLON.serializeAsColor3()
  74576. ], GridMaterial.prototype, "lineColor", void 0);
  74577. __decorate([
  74578. BABYLON.serialize()
  74579. ], GridMaterial.prototype, "gridRatio", void 0);
  74580. __decorate([
  74581. BABYLON.serializeAsColor3()
  74582. ], GridMaterial.prototype, "gridOffset", void 0);
  74583. __decorate([
  74584. BABYLON.serialize()
  74585. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  74586. __decorate([
  74587. BABYLON.serialize()
  74588. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  74589. __decorate([
  74590. BABYLON.serialize()
  74591. ], GridMaterial.prototype, "opacity", void 0);
  74592. __decorate([
  74593. BABYLON.serialize()
  74594. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  74595. return GridMaterial;
  74596. }(BABYLON.PushMaterial));
  74597. BABYLON.GridMaterial = GridMaterial;
  74598. })(BABYLON || (BABYLON = {}));
  74599. //# sourceMappingURL=babylon.gridmaterial.js.map
  74600. 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}";
  74601. 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}";
  74602. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74603. var BABYLON;
  74604. (function (BABYLON) {
  74605. /**
  74606. * Background material defines definition.
  74607. */
  74608. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  74609. __extends(BackgroundMaterialDefines, _super);
  74610. /**
  74611. * Constructor of the defines.
  74612. */
  74613. function BackgroundMaterialDefines() {
  74614. var _this = _super.call(this) || this;
  74615. /**
  74616. * True if the diffuse texture is in use.
  74617. */
  74618. _this.DIFFUSE = false;
  74619. /**
  74620. * The direct UV channel to use.
  74621. */
  74622. _this.DIFFUSEDIRECTUV = 0;
  74623. /**
  74624. * True if the diffuse texture is in gamma space.
  74625. */
  74626. _this.GAMMADIFFUSE = false;
  74627. /**
  74628. * True if the diffuse texture has opacity in the alpha channel.
  74629. */
  74630. _this.DIFFUSEHASALPHA = false;
  74631. /**
  74632. * True if you want the material to fade to transparent at grazing angle.
  74633. */
  74634. _this.OPACITYFRESNEL = false;
  74635. /**
  74636. * True if an extra blur needs to be added in the reflection.
  74637. */
  74638. _this.REFLECTIONBLUR = false;
  74639. /**
  74640. * False if the current Webgl implementation does not support the texture lod extension.
  74641. */
  74642. _this.TEXTURELODSUPPORT = false;
  74643. /**
  74644. * True to ensure the data are premultiplied.
  74645. */
  74646. _this.PREMULTIPLYALPHA = false;
  74647. /**
  74648. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  74649. */
  74650. _this.USERGBCOLOR = false;
  74651. // Image Processing Configuration.
  74652. _this.IMAGEPROCESSING = false;
  74653. _this.VIGNETTE = false;
  74654. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  74655. _this.VIGNETTEBLENDMODEOPAQUE = false;
  74656. _this.TONEMAPPING = false;
  74657. _this.CONTRAST = false;
  74658. _this.COLORCURVES = false;
  74659. _this.COLORGRADING = false;
  74660. _this.COLORGRADING3D = false;
  74661. _this.SAMPLER3DGREENDEPTH = false;
  74662. _this.SAMPLER3DBGRMAP = false;
  74663. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  74664. _this.EXPOSURE = false;
  74665. // Reflection.
  74666. _this.REFLECTION = false;
  74667. _this.REFLECTIONMAP_3D = false;
  74668. _this.REFLECTIONMAP_SPHERICAL = false;
  74669. _this.REFLECTIONMAP_PLANAR = false;
  74670. _this.REFLECTIONMAP_CUBIC = false;
  74671. _this.REFLECTIONMAP_PROJECTION = false;
  74672. _this.REFLECTIONMAP_SKYBOX = false;
  74673. _this.REFLECTIONMAP_EXPLICIT = false;
  74674. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  74675. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  74676. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  74677. _this.INVERTCUBICMAP = false;
  74678. _this.REFLECTIONMAP_OPPOSITEZ = false;
  74679. _this.LODINREFLECTIONALPHA = false;
  74680. _this.GAMMAREFLECTION = false;
  74681. // Default BJS.
  74682. _this.MAINUV1 = false;
  74683. _this.MAINUV2 = false;
  74684. _this.UV1 = false;
  74685. _this.UV2 = false;
  74686. _this.CLIPPLANE = false;
  74687. _this.POINTSIZE = false;
  74688. _this.FOG = false;
  74689. _this.NORMAL = false;
  74690. _this.NUM_BONE_INFLUENCERS = 0;
  74691. _this.BonesPerMesh = 0;
  74692. _this.INSTANCES = false;
  74693. _this.SHADOWFLOAT = false;
  74694. _this.rebuild();
  74695. return _this;
  74696. }
  74697. return BackgroundMaterialDefines;
  74698. }(BABYLON.MaterialDefines));
  74699. /**
  74700. * Background material
  74701. */
  74702. var BackgroundMaterial = /** @class */ (function (_super) {
  74703. __extends(BackgroundMaterial, _super);
  74704. /**
  74705. * constructor
  74706. * @param name The name of the material
  74707. * @param scene The scene to add the material to
  74708. */
  74709. function BackgroundMaterial(name, scene) {
  74710. var _this = _super.call(this, name, scene) || this;
  74711. _this.primaryColor = BABYLON.Color3.White();
  74712. _this.primaryLevel = 1;
  74713. _this.secondaryColor = BABYLON.Color3.Gray();
  74714. _this.secondaryLevel = 1;
  74715. _this.tertiaryColor = BABYLON.Color3.Black();
  74716. _this.tertiaryLevel = 1;
  74717. _this.reflectionTexture = null;
  74718. _this.reflectionBlur = 0;
  74719. _this.diffuseTexture = null;
  74720. /**
  74721. * Specify the list of lights casting shadow on the material.
  74722. * All scene shadow lights will be included if null.
  74723. */
  74724. _this._shadowLights = null;
  74725. _this.shadowLights = null;
  74726. _this.shadowBlurScale = 1;
  74727. _this.shadowLevel = 0;
  74728. _this.opacityFresnel = true;
  74729. _this.useRGBColor = true;
  74730. /**
  74731. * Number of Simultaneous lights allowed on the material.
  74732. */
  74733. _this._maxSimultaneousLights = 4;
  74734. _this.maxSimultaneousLights = 4;
  74735. /**
  74736. * Keep track of the image processing observer to allow dispose and replace.
  74737. */
  74738. _this._imageProcessingObserver = null;
  74739. // Temp values kept as cache in the material.
  74740. _this._renderTargets = new BABYLON.SmartArray(16);
  74741. // Setup the default processing configuration to the scene.
  74742. _this._attachImageProcessingConfiguration(null);
  74743. _this.getRenderTargetTextures = function () {
  74744. _this._renderTargets.reset();
  74745. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  74746. _this._renderTargets.push(_this._diffuseTexture);
  74747. }
  74748. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  74749. _this._renderTargets.push(_this._reflectionTexture);
  74750. }
  74751. return _this._renderTargets;
  74752. };
  74753. return _this;
  74754. }
  74755. /**
  74756. * Attaches a new image processing configuration to the PBR Material.
  74757. * @param configuration (if null the scene configuration will be use)
  74758. */
  74759. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  74760. var _this = this;
  74761. if (configuration === this._imageProcessingConfiguration) {
  74762. return;
  74763. }
  74764. // Detaches observer.
  74765. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  74766. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  74767. }
  74768. // Pick the scene configuration if needed.
  74769. if (!configuration) {
  74770. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  74771. }
  74772. else {
  74773. this._imageProcessingConfiguration = configuration;
  74774. }
  74775. // Attaches observer.
  74776. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  74777. _this._markAllSubMeshesAsImageProcessingDirty();
  74778. });
  74779. };
  74780. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  74781. /**
  74782. * Gets the image processing configuration used either in this material.
  74783. */
  74784. get: function () {
  74785. return this._imageProcessingConfiguration;
  74786. },
  74787. /**
  74788. * Sets the Default image processing configuration used either in the this material.
  74789. *
  74790. * If sets to null, the scene one is in use.
  74791. */
  74792. set: function (value) {
  74793. this._attachImageProcessingConfiguration(value);
  74794. // Ensure the effect will be rebuilt.
  74795. this._markAllSubMeshesAsTexturesDirty();
  74796. },
  74797. enumerable: true,
  74798. configurable: true
  74799. });
  74800. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  74801. /**
  74802. * Gets wether the color curves effect is enabled.
  74803. */
  74804. get: function () {
  74805. return this.imageProcessingConfiguration.colorCurvesEnabled;
  74806. },
  74807. /**
  74808. * Sets wether the color curves effect is enabled.
  74809. */
  74810. set: function (value) {
  74811. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  74812. },
  74813. enumerable: true,
  74814. configurable: true
  74815. });
  74816. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  74817. /**
  74818. * Gets wether the color grading effect is enabled.
  74819. */
  74820. get: function () {
  74821. return this.imageProcessingConfiguration.colorGradingEnabled;
  74822. },
  74823. /**
  74824. * Gets wether the color grading effect is enabled.
  74825. */
  74826. set: function (value) {
  74827. this.imageProcessingConfiguration.colorGradingEnabled = value;
  74828. },
  74829. enumerable: true,
  74830. configurable: true
  74831. });
  74832. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  74833. /**
  74834. * Gets wether tonemapping is enabled or not.
  74835. */
  74836. get: function () {
  74837. return this._imageProcessingConfiguration.toneMappingEnabled;
  74838. },
  74839. /**
  74840. * Sets wether tonemapping is enabled or not
  74841. */
  74842. set: function (value) {
  74843. this._imageProcessingConfiguration.toneMappingEnabled = value;
  74844. },
  74845. enumerable: true,
  74846. configurable: true
  74847. });
  74848. ;
  74849. ;
  74850. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  74851. /**
  74852. * The camera exposure used on this material.
  74853. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  74854. * This corresponds to a photographic exposure.
  74855. */
  74856. get: function () {
  74857. return this._imageProcessingConfiguration.exposure;
  74858. },
  74859. /**
  74860. * The camera exposure used on this material.
  74861. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  74862. * This corresponds to a photographic exposure.
  74863. */
  74864. set: function (value) {
  74865. this._imageProcessingConfiguration.exposure = value;
  74866. },
  74867. enumerable: true,
  74868. configurable: true
  74869. });
  74870. ;
  74871. ;
  74872. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  74873. /**
  74874. * Gets The camera contrast used on this material.
  74875. */
  74876. get: function () {
  74877. return this._imageProcessingConfiguration.contrast;
  74878. },
  74879. /**
  74880. * Sets The camera contrast used on this material.
  74881. */
  74882. set: function (value) {
  74883. this._imageProcessingConfiguration.contrast = value;
  74884. },
  74885. enumerable: true,
  74886. configurable: true
  74887. });
  74888. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  74889. /**
  74890. * Gets the Color Grading 2D Lookup Texture.
  74891. */
  74892. get: function () {
  74893. return this._imageProcessingConfiguration.colorGradingTexture;
  74894. },
  74895. /**
  74896. * Sets the Color Grading 2D Lookup Texture.
  74897. */
  74898. set: function (value) {
  74899. this.imageProcessingConfiguration.colorGradingTexture = value;
  74900. },
  74901. enumerable: true,
  74902. configurable: true
  74903. });
  74904. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  74905. /**
  74906. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  74907. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  74908. * 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;
  74909. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  74910. */
  74911. get: function () {
  74912. return this.imageProcessingConfiguration.colorCurves;
  74913. },
  74914. /**
  74915. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  74916. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  74917. * 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;
  74918. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  74919. */
  74920. set: function (value) {
  74921. this.imageProcessingConfiguration.colorCurves = value;
  74922. },
  74923. enumerable: true,
  74924. configurable: true
  74925. });
  74926. /**
  74927. * The entire material has been created in order to prevent overdraw.
  74928. * @returns false
  74929. */
  74930. BackgroundMaterial.prototype.needAlphaTesting = function () {
  74931. return false;
  74932. };
  74933. /**
  74934. * The entire material has been created in order to prevent overdraw.
  74935. * @returns true if blending is enable
  74936. */
  74937. BackgroundMaterial.prototype.needAlphaBlending = function () {
  74938. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  74939. };
  74940. /**
  74941. * Checks wether the material is ready to be rendered for a given mesh.
  74942. * @param mesh The mesh to render
  74943. * @param subMesh The submesh to check against
  74944. * @param useInstances Specify wether or not the material is used with instances
  74945. */
  74946. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74947. var _this = this;
  74948. if (useInstances === void 0) { useInstances = false; }
  74949. if (subMesh.effect && this.isFrozen) {
  74950. if (this._wasPreviouslyReady) {
  74951. return true;
  74952. }
  74953. }
  74954. if (!subMesh._materialDefines) {
  74955. subMesh._materialDefines = new BackgroundMaterialDefines();
  74956. }
  74957. var scene = this.getScene();
  74958. var defines = subMesh._materialDefines;
  74959. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  74960. if (defines._renderId === scene.getRenderId()) {
  74961. return true;
  74962. }
  74963. }
  74964. var engine = scene.getEngine();
  74965. // Lights
  74966. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  74967. defines._needNormals = true;
  74968. // Textures
  74969. if (defines._areTexturesDirty) {
  74970. defines._needUVs = false;
  74971. if (scene.texturesEnabled) {
  74972. if (scene.getEngine().getCaps().textureLOD) {
  74973. defines.TEXTURELODSUPPORT = true;
  74974. }
  74975. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  74976. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  74977. return false;
  74978. }
  74979. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  74980. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  74981. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  74982. defines.OPACITYFRESNEL = this._opacityFresnel;
  74983. }
  74984. else {
  74985. defines.DIFFUSE = false;
  74986. defines.DIFFUSEHASALPHA = false;
  74987. defines.GAMMADIFFUSE = false;
  74988. defines.OPACITYFRESNEL = false;
  74989. }
  74990. var reflectionTexture = this._reflectionTexture;
  74991. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  74992. if (!reflectionTexture.isReadyOrNotBlocking()) {
  74993. return false;
  74994. }
  74995. defines.REFLECTION = true;
  74996. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  74997. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  74998. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  74999. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  75000. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  75001. defines.INVERTCUBICMAP = true;
  75002. }
  75003. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  75004. switch (reflectionTexture.coordinatesMode) {
  75005. case BABYLON.Texture.CUBIC_MODE:
  75006. case BABYLON.Texture.INVCUBIC_MODE:
  75007. defines.REFLECTIONMAP_CUBIC = true;
  75008. break;
  75009. case BABYLON.Texture.EXPLICIT_MODE:
  75010. defines.REFLECTIONMAP_EXPLICIT = true;
  75011. break;
  75012. case BABYLON.Texture.PLANAR_MODE:
  75013. defines.REFLECTIONMAP_PLANAR = true;
  75014. break;
  75015. case BABYLON.Texture.PROJECTION_MODE:
  75016. defines.REFLECTIONMAP_PROJECTION = true;
  75017. break;
  75018. case BABYLON.Texture.SKYBOX_MODE:
  75019. defines.REFLECTIONMAP_SKYBOX = true;
  75020. break;
  75021. case BABYLON.Texture.SPHERICAL_MODE:
  75022. defines.REFLECTIONMAP_SPHERICAL = true;
  75023. break;
  75024. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  75025. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  75026. break;
  75027. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  75028. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  75029. break;
  75030. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  75031. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  75032. break;
  75033. }
  75034. }
  75035. else {
  75036. defines.REFLECTION = false;
  75037. defines.REFLECTIONBLUR = false;
  75038. defines.REFLECTIONMAP_3D = false;
  75039. defines.REFLECTIONMAP_SPHERICAL = false;
  75040. defines.REFLECTIONMAP_PLANAR = false;
  75041. defines.REFLECTIONMAP_CUBIC = false;
  75042. defines.REFLECTIONMAP_PROJECTION = false;
  75043. defines.REFLECTIONMAP_SKYBOX = false;
  75044. defines.REFLECTIONMAP_EXPLICIT = false;
  75045. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75046. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75047. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75048. defines.INVERTCUBICMAP = false;
  75049. defines.REFLECTIONMAP_OPPOSITEZ = false;
  75050. defines.LODINREFLECTIONALPHA = false;
  75051. defines.GAMMAREFLECTION = false;
  75052. }
  75053. }
  75054. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  75055. defines.USERGBCOLOR = this._useRGBColor;
  75056. }
  75057. if (defines._areImageProcessingDirty) {
  75058. if (!this._imageProcessingConfiguration.isReady()) {
  75059. return false;
  75060. }
  75061. this._imageProcessingConfiguration.prepareDefines(defines);
  75062. }
  75063. // Misc.
  75064. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  75065. // Values that need to be evaluated on every frame
  75066. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  75067. // Attribs
  75068. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  75069. if (mesh) {
  75070. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75071. mesh.createNormals(true);
  75072. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  75073. }
  75074. }
  75075. }
  75076. // Get correct effect
  75077. if (defines.isDirty) {
  75078. defines.markAsProcessed();
  75079. scene.resetCachedMaterial();
  75080. // Fallbacks
  75081. var fallbacks = new BABYLON.EffectFallbacks();
  75082. if (defines.FOG) {
  75083. fallbacks.addFallback(0, "FOG");
  75084. }
  75085. if (defines.POINTSIZE) {
  75086. fallbacks.addFallback(1, "POINTSIZE");
  75087. }
  75088. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  75089. if (defines.NUM_BONE_INFLUENCERS > 0) {
  75090. fallbacks.addCPUSkinningFallback(0, mesh);
  75091. }
  75092. //Attributes
  75093. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75094. if (defines.NORMAL) {
  75095. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75096. }
  75097. if (defines.UV1) {
  75098. attribs.push(BABYLON.VertexBuffer.UVKind);
  75099. }
  75100. if (defines.UV2) {
  75101. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75102. }
  75103. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  75104. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  75105. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  75106. "vFogInfos", "vFogColor", "pointSize",
  75107. "vClipPlane", "mBones",
  75108. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  75109. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  75110. "shadowLevel", "alpha",
  75111. "vDiffuseInfos", "diffuseMatrix",
  75112. ];
  75113. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  75114. var uniformBuffers = ["Material", "Scene"];
  75115. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  75116. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  75117. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  75118. uniformsNames: uniforms,
  75119. uniformBuffersNames: uniformBuffers,
  75120. samplers: samplers,
  75121. defines: defines,
  75122. maxSimultaneousLights: this._maxSimultaneousLights
  75123. });
  75124. var onCompiled = function (effect) {
  75125. if (_this.onCompiled) {
  75126. _this.onCompiled(effect);
  75127. }
  75128. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  75129. };
  75130. var join = defines.toString();
  75131. subMesh.setEffect(scene.getEngine().createEffect("background", {
  75132. attributes: attribs,
  75133. uniformsNames: uniforms,
  75134. uniformBuffersNames: uniformBuffers,
  75135. samplers: samplers,
  75136. defines: join,
  75137. fallbacks: fallbacks,
  75138. onCompiled: onCompiled,
  75139. onError: this.onError,
  75140. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  75141. }, engine), defines);
  75142. this.buildUniformLayout();
  75143. }
  75144. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75145. return false;
  75146. }
  75147. defines._renderId = scene.getRenderId();
  75148. this._wasPreviouslyReady = true;
  75149. return true;
  75150. };
  75151. /**
  75152. * Build the uniform buffer used in the material.
  75153. */
  75154. BackgroundMaterial.prototype.buildUniformLayout = function () {
  75155. // Order is important !
  75156. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  75157. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  75158. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  75159. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  75160. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  75161. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  75162. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  75163. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  75164. this._uniformBuffer.addUniform("pointSize", 1);
  75165. this._uniformBuffer.addUniform("shadowLevel", 1);
  75166. this._uniformBuffer.addUniform("alpha", 1);
  75167. this._uniformBuffer.create();
  75168. };
  75169. /**
  75170. * Unbind the material.
  75171. */
  75172. BackgroundMaterial.prototype.unbind = function () {
  75173. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  75174. this._uniformBuffer.setTexture("diffuseSampler", null);
  75175. }
  75176. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  75177. this._uniformBuffer.setTexture("reflectionSampler", null);
  75178. }
  75179. _super.prototype.unbind.call(this);
  75180. };
  75181. /**
  75182. * Bind only the world matrix to the material.
  75183. * @param world The world matrix to bind.
  75184. */
  75185. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  75186. this._activeEffect.setMatrix("world", world);
  75187. };
  75188. /**
  75189. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  75190. * @param world The world matrix to bind.
  75191. * @param subMesh The submesh to bind for.
  75192. */
  75193. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75194. var scene = this.getScene();
  75195. var defines = subMesh._materialDefines;
  75196. if (!defines) {
  75197. return;
  75198. }
  75199. var effect = subMesh.effect;
  75200. if (!effect) {
  75201. return;
  75202. }
  75203. this._activeEffect = effect;
  75204. // Matrices
  75205. this.bindOnlyWorldMatrix(world);
  75206. // Bones
  75207. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  75208. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  75209. if (mustRebind) {
  75210. this._uniformBuffer.bindToEffect(effect, "Material");
  75211. this.bindViewProjection(effect);
  75212. var reflectionTexture = this._reflectionTexture;
  75213. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  75214. // Texture uniforms
  75215. if (scene.texturesEnabled) {
  75216. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75217. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  75218. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  75219. }
  75220. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75221. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  75222. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  75223. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  75224. }
  75225. }
  75226. if (this.shadowLevel > 0) {
  75227. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  75228. }
  75229. this._uniformBuffer.updateFloat("alpha", this.alpha);
  75230. // Point size
  75231. if (this.pointsCloud) {
  75232. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  75233. }
  75234. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  75235. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  75236. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  75237. }
  75238. // Textures
  75239. if (scene.texturesEnabled) {
  75240. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75241. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  75242. }
  75243. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75244. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  75245. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75246. }
  75247. else if (!defines.REFLECTIONBLUR) {
  75248. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75249. }
  75250. else {
  75251. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  75252. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  75253. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  75254. }
  75255. }
  75256. }
  75257. // Clip plane
  75258. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  75259. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  75260. }
  75261. if (mustRebind || !this.isFrozen) {
  75262. if (scene.lightsEnabled) {
  75263. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  75264. }
  75265. // View
  75266. this.bindView(effect);
  75267. // Fog
  75268. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75269. // image processing
  75270. this._imageProcessingConfiguration.bind(this._activeEffect);
  75271. }
  75272. this._uniformBuffer.update();
  75273. this._afterBind(mesh);
  75274. };
  75275. /**
  75276. * Dispose the material.
  75277. * @forceDisposeEffect Force disposal of the associated effect.
  75278. * @forceDisposeTextures Force disposal of the associated textures.
  75279. */
  75280. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75281. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  75282. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  75283. if (forceDisposeTextures) {
  75284. if (this.diffuseTexture) {
  75285. this.diffuseTexture.dispose();
  75286. }
  75287. if (this.reflectionTexture) {
  75288. this.reflectionTexture.dispose();
  75289. }
  75290. }
  75291. this._renderTargets.dispose();
  75292. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75293. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75294. }
  75295. _super.prototype.dispose.call(this, forceDisposeEffect);
  75296. };
  75297. /**
  75298. * Clones the material.
  75299. * @name The cloned name.
  75300. * @returns The cloned material.
  75301. */
  75302. BackgroundMaterial.prototype.clone = function (name) {
  75303. var _this = this;
  75304. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  75305. };
  75306. /**
  75307. * Serializes the current material to its JSON representation.
  75308. * @returns The JSON representation.
  75309. */
  75310. BackgroundMaterial.prototype.serialize = function () {
  75311. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75312. serializationObject.customType = "BABYLON.BackgroundMaterial";
  75313. return serializationObject;
  75314. };
  75315. /**
  75316. * Gets the class name of the material
  75317. * @returns "BackgroundMaterial"
  75318. */
  75319. BackgroundMaterial.prototype.getClassName = function () {
  75320. return "BackgroundMaterial";
  75321. };
  75322. /**
  75323. * Parse a JSON input to create back a background material.
  75324. * @param source
  75325. * @param scene
  75326. * @param rootUrl
  75327. * @returns the instantiated BackgroundMaterial.
  75328. */
  75329. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  75330. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  75331. };
  75332. __decorate([
  75333. BABYLON.serializeAsColor3()
  75334. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  75335. __decorate([
  75336. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75337. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  75338. __decorate([
  75339. BABYLON.serialize()
  75340. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  75341. __decorate([
  75342. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75343. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  75344. __decorate([
  75345. BABYLON.serializeAsColor3()
  75346. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  75347. __decorate([
  75348. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75349. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  75350. __decorate([
  75351. BABYLON.serialize()
  75352. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  75353. __decorate([
  75354. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75355. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  75356. __decorate([
  75357. BABYLON.serializeAsColor3()
  75358. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  75359. __decorate([
  75360. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75361. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  75362. __decorate([
  75363. BABYLON.serialize()
  75364. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  75365. __decorate([
  75366. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75367. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  75368. __decorate([
  75369. BABYLON.serializeAsTexture()
  75370. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  75371. __decorate([
  75372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75373. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  75374. __decorate([
  75375. BABYLON.serialize()
  75376. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  75377. __decorate([
  75378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75379. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  75380. __decorate([
  75381. BABYLON.serializeAsTexture()
  75382. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  75383. __decorate([
  75384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75385. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  75386. __decorate([
  75387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75388. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  75389. __decorate([
  75390. BABYLON.serialize()
  75391. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  75392. __decorate([
  75393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75394. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  75395. __decorate([
  75396. BABYLON.serialize()
  75397. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  75398. __decorate([
  75399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75400. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  75401. __decorate([
  75402. BABYLON.serialize()
  75403. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  75404. __decorate([
  75405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75406. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  75407. __decorate([
  75408. BABYLON.serialize()
  75409. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  75410. __decorate([
  75411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75412. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  75413. __decorate([
  75414. BABYLON.serialize()
  75415. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  75416. __decorate([
  75417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75418. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  75419. __decorate([
  75420. BABYLON.serializeAsImageProcessingConfiguration()
  75421. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  75422. return BackgroundMaterial;
  75423. }(BABYLON.PushMaterial));
  75424. BABYLON.BackgroundMaterial = BackgroundMaterial;
  75425. })(BABYLON || (BABYLON = {}));
  75426. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  75427. 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";
  75428. 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}";
  75429. 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";
  75430. 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};";
  75431. 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";
  75432. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  75433. var BABYLON;
  75434. (function (BABYLON) {
  75435. var GLTFLoaderCoordinateSystemMode;
  75436. (function (GLTFLoaderCoordinateSystemMode) {
  75437. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  75438. // 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.
  75439. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  75440. // The glTF right-handed data is not transformed in any form and is loaded directly.
  75441. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  75442. // Sets the useRightHandedSystem flag on the scene.
  75443. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  75444. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  75445. var GLTFFileLoader = /** @class */ (function () {
  75446. function GLTFFileLoader() {
  75447. // V2 options
  75448. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  75449. this.name = "gltf";
  75450. this.extensions = {
  75451. ".gltf": { isBinary: false },
  75452. ".glb": { isBinary: true }
  75453. };
  75454. }
  75455. GLTFFileLoader.prototype.dispose = function () {
  75456. if (this._loader) {
  75457. this._loader.dispose();
  75458. this._loader = null;
  75459. }
  75460. };
  75461. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75462. var loaderData = GLTFFileLoader._parse(data, onError);
  75463. if (!loaderData) {
  75464. return;
  75465. }
  75466. if (this.onParsed) {
  75467. this.onParsed(loaderData);
  75468. }
  75469. this._loader = this._getLoader(loaderData, onError);
  75470. if (!this._loader) {
  75471. return;
  75472. }
  75473. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  75474. };
  75475. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  75476. var loaderData = GLTFFileLoader._parse(data, onError);
  75477. if (!loaderData) {
  75478. return;
  75479. }
  75480. if (this.onParsed) {
  75481. this.onParsed(loaderData);
  75482. }
  75483. this._loader = this._getLoader(loaderData, onError);
  75484. if (!this._loader) {
  75485. return;
  75486. }
  75487. return this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  75488. };
  75489. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  75490. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  75491. };
  75492. GLTFFileLoader._parse = function (data, onError) {
  75493. try {
  75494. if (data instanceof ArrayBuffer) {
  75495. return GLTFFileLoader._parseBinary(data, onError);
  75496. }
  75497. return {
  75498. json: JSON.parse(data),
  75499. bin: null
  75500. };
  75501. }
  75502. catch (e) {
  75503. onError(e.message);
  75504. return null;
  75505. }
  75506. };
  75507. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  75508. var loaderVersion = { major: 2, minor: 0 };
  75509. var asset = loaderData.json.asset || {};
  75510. var version = GLTFFileLoader._parseVersion(asset.version);
  75511. if (!version) {
  75512. onError("Invalid version: " + asset.version);
  75513. return null;
  75514. }
  75515. if (asset.minVersion !== undefined) {
  75516. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  75517. if (!minVersion) {
  75518. onError("Invalid minimum version: " + asset.minVersion);
  75519. return null;
  75520. }
  75521. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  75522. onError("Incompatible minimum version: " + asset.minVersion);
  75523. return null;
  75524. }
  75525. }
  75526. var createLoaders = {
  75527. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  75528. 2: GLTFFileLoader.CreateGLTFLoaderV2
  75529. };
  75530. var createLoader = createLoaders[version.major];
  75531. if (!createLoader) {
  75532. onError("Unsupported version: " + asset.version);
  75533. return null;
  75534. }
  75535. return createLoader(this);
  75536. };
  75537. GLTFFileLoader._parseBinary = function (data, onError) {
  75538. var Binary = {
  75539. Magic: 0x46546C67
  75540. };
  75541. var binaryReader = new BinaryReader(data);
  75542. var magic = binaryReader.readUint32();
  75543. if (magic !== Binary.Magic) {
  75544. onError("Unexpected magic: " + magic);
  75545. return null;
  75546. }
  75547. var version = binaryReader.readUint32();
  75548. switch (version) {
  75549. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  75550. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  75551. }
  75552. onError("Unsupported version: " + version);
  75553. return null;
  75554. };
  75555. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  75556. var ContentFormat = {
  75557. JSON: 0
  75558. };
  75559. var length = binaryReader.readUint32();
  75560. if (length != binaryReader.getLength()) {
  75561. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  75562. return null;
  75563. }
  75564. var contentLength = binaryReader.readUint32();
  75565. var contentFormat = binaryReader.readUint32();
  75566. var content;
  75567. switch (contentFormat) {
  75568. case ContentFormat.JSON:
  75569. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  75570. break;
  75571. default:
  75572. onError("Unexpected content format: " + contentFormat);
  75573. return null;
  75574. }
  75575. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  75576. var body = binaryReader.readUint8Array(bytesRemaining);
  75577. return {
  75578. json: content,
  75579. bin: body
  75580. };
  75581. };
  75582. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  75583. var ChunkFormat = {
  75584. JSON: 0x4E4F534A,
  75585. BIN: 0x004E4942
  75586. };
  75587. var length = binaryReader.readUint32();
  75588. if (length !== binaryReader.getLength()) {
  75589. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  75590. return null;
  75591. }
  75592. // JSON chunk
  75593. var chunkLength = binaryReader.readUint32();
  75594. var chunkFormat = binaryReader.readUint32();
  75595. if (chunkFormat !== ChunkFormat.JSON) {
  75596. onError("First chunk format is not JSON");
  75597. return null;
  75598. }
  75599. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  75600. // Look for BIN chunk
  75601. var bin = null;
  75602. while (binaryReader.getPosition() < binaryReader.getLength()) {
  75603. var chunkLength_1 = binaryReader.readUint32();
  75604. var chunkFormat_1 = binaryReader.readUint32();
  75605. switch (chunkFormat_1) {
  75606. case ChunkFormat.JSON:
  75607. onError("Unexpected JSON chunk");
  75608. return null;
  75609. case ChunkFormat.BIN:
  75610. bin = binaryReader.readUint8Array(chunkLength_1);
  75611. break;
  75612. default:
  75613. // ignore unrecognized chunkFormat
  75614. binaryReader.skipBytes(chunkLength_1);
  75615. break;
  75616. }
  75617. }
  75618. return {
  75619. json: json,
  75620. bin: bin
  75621. };
  75622. };
  75623. GLTFFileLoader._parseVersion = function (version) {
  75624. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  75625. if (!match) {
  75626. return null;
  75627. }
  75628. return {
  75629. major: parseInt(match[1]),
  75630. minor: parseInt(match[2])
  75631. };
  75632. };
  75633. GLTFFileLoader._compareVersion = function (a, b) {
  75634. if (a.major > b.major)
  75635. return 1;
  75636. if (a.major < b.major)
  75637. return -1;
  75638. if (a.minor > b.minor)
  75639. return 1;
  75640. if (a.minor < b.minor)
  75641. return -1;
  75642. return 0;
  75643. };
  75644. GLTFFileLoader._decodeBufferToText = function (buffer) {
  75645. var result = "";
  75646. var length = buffer.byteLength;
  75647. for (var i = 0; i < length; i++) {
  75648. result += String.fromCharCode(buffer[i]);
  75649. }
  75650. return result;
  75651. };
  75652. // V1 options
  75653. GLTFFileLoader.HomogeneousCoordinates = false;
  75654. GLTFFileLoader.IncrementalLoading = true;
  75655. return GLTFFileLoader;
  75656. }());
  75657. BABYLON.GLTFFileLoader = GLTFFileLoader;
  75658. var BinaryReader = /** @class */ (function () {
  75659. function BinaryReader(arrayBuffer) {
  75660. this._arrayBuffer = arrayBuffer;
  75661. this._dataView = new DataView(arrayBuffer);
  75662. this._byteOffset = 0;
  75663. }
  75664. BinaryReader.prototype.getPosition = function () {
  75665. return this._byteOffset;
  75666. };
  75667. BinaryReader.prototype.getLength = function () {
  75668. return this._arrayBuffer.byteLength;
  75669. };
  75670. BinaryReader.prototype.readUint32 = function () {
  75671. var value = this._dataView.getUint32(this._byteOffset, true);
  75672. this._byteOffset += 4;
  75673. return value;
  75674. };
  75675. BinaryReader.prototype.readUint8Array = function (length) {
  75676. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  75677. this._byteOffset += length;
  75678. return value;
  75679. };
  75680. BinaryReader.prototype.skipBytes = function (length) {
  75681. this._byteOffset += length;
  75682. };
  75683. return BinaryReader;
  75684. }());
  75685. if (BABYLON.SceneLoader) {
  75686. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  75687. }
  75688. })(BABYLON || (BABYLON = {}));
  75689. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  75690. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75691. var BABYLON;
  75692. (function (BABYLON) {
  75693. var GLTF1;
  75694. (function (GLTF1) {
  75695. /**
  75696. * Enums
  75697. */
  75698. var EComponentType;
  75699. (function (EComponentType) {
  75700. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  75701. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  75702. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  75703. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  75704. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  75705. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  75706. var EShaderType;
  75707. (function (EShaderType) {
  75708. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  75709. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  75710. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  75711. var EParameterType;
  75712. (function (EParameterType) {
  75713. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  75714. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  75715. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  75716. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  75717. EParameterType[EParameterType["INT"] = 5124] = "INT";
  75718. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  75719. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  75720. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  75721. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  75722. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  75723. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  75724. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  75725. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  75726. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  75727. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  75728. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  75729. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  75730. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  75731. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  75732. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  75733. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  75734. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  75735. var ETextureWrapMode;
  75736. (function (ETextureWrapMode) {
  75737. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  75738. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  75739. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  75740. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  75741. var ETextureFilterType;
  75742. (function (ETextureFilterType) {
  75743. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  75744. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  75745. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  75746. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  75747. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  75748. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  75749. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  75750. var ETextureFormat;
  75751. (function (ETextureFormat) {
  75752. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  75753. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  75754. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  75755. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  75756. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  75757. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  75758. var ECullingType;
  75759. (function (ECullingType) {
  75760. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  75761. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  75762. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  75763. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  75764. var EBlendingFunction;
  75765. (function (EBlendingFunction) {
  75766. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  75767. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  75768. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  75769. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  75770. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  75771. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  75772. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  75773. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  75774. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  75775. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  75776. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  75777. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  75778. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  75779. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  75780. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  75781. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  75782. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  75783. })(BABYLON || (BABYLON = {}));
  75784. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  75785. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75786. var BABYLON;
  75787. (function (BABYLON) {
  75788. var GLTF1;
  75789. (function (GLTF1) {
  75790. /**
  75791. * Tokenizer. Used for shaders compatibility
  75792. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  75793. */
  75794. var ETokenType;
  75795. (function (ETokenType) {
  75796. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  75797. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  75798. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  75799. })(ETokenType || (ETokenType = {}));
  75800. var Tokenizer = /** @class */ (function () {
  75801. function Tokenizer(toParse) {
  75802. this._pos = 0;
  75803. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  75804. this._toParse = toParse;
  75805. this._maxPos = toParse.length;
  75806. }
  75807. Tokenizer.prototype.getNextToken = function () {
  75808. if (this.isEnd())
  75809. return ETokenType.END_OF_INPUT;
  75810. this.currentString = this.read();
  75811. this.currentToken = ETokenType.UNKNOWN;
  75812. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  75813. this.currentToken = ETokenType.IDENTIFIER;
  75814. this.currentIdentifier = this.currentString;
  75815. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  75816. this.currentIdentifier += this.currentString;
  75817. this.forward();
  75818. }
  75819. }
  75820. return this.currentToken;
  75821. };
  75822. Tokenizer.prototype.peek = function () {
  75823. return this._toParse[this._pos];
  75824. };
  75825. Tokenizer.prototype.read = function () {
  75826. return this._toParse[this._pos++];
  75827. };
  75828. Tokenizer.prototype.forward = function () {
  75829. this._pos++;
  75830. };
  75831. Tokenizer.prototype.isEnd = function () {
  75832. return this._pos >= this._maxPos;
  75833. };
  75834. return Tokenizer;
  75835. }());
  75836. /**
  75837. * Values
  75838. */
  75839. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  75840. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  75841. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  75842. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  75843. /**
  75844. * Parse
  75845. */
  75846. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  75847. for (var buf in parsedBuffers) {
  75848. var parsedBuffer = parsedBuffers[buf];
  75849. gltfRuntime.buffers[buf] = parsedBuffer;
  75850. gltfRuntime.buffersCount++;
  75851. }
  75852. };
  75853. var parseShaders = function (parsedShaders, gltfRuntime) {
  75854. for (var sha in parsedShaders) {
  75855. var parsedShader = parsedShaders[sha];
  75856. gltfRuntime.shaders[sha] = parsedShader;
  75857. gltfRuntime.shaderscount++;
  75858. }
  75859. };
  75860. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  75861. for (var object in parsedObjects) {
  75862. var parsedObject = parsedObjects[object];
  75863. gltfRuntime[runtimeProperty][object] = parsedObject;
  75864. }
  75865. };
  75866. /**
  75867. * Utils
  75868. */
  75869. var normalizeUVs = function (buffer) {
  75870. if (!buffer) {
  75871. return;
  75872. }
  75873. for (var i = 0; i < buffer.length / 2; i++) {
  75874. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  75875. }
  75876. };
  75877. var getAttribute = function (attributeParameter) {
  75878. if (attributeParameter.semantic === "NORMAL") {
  75879. return "normal";
  75880. }
  75881. else if (attributeParameter.semantic === "POSITION") {
  75882. return "position";
  75883. }
  75884. else if (attributeParameter.semantic === "JOINT") {
  75885. return "matricesIndices";
  75886. }
  75887. else if (attributeParameter.semantic === "WEIGHT") {
  75888. return "matricesWeights";
  75889. }
  75890. else if (attributeParameter.semantic === "COLOR") {
  75891. return "color";
  75892. }
  75893. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  75894. var channel = Number(attributeParameter.semantic.split("_")[1]);
  75895. return "uv" + (channel === 0 ? "" : channel + 1);
  75896. }
  75897. return null;
  75898. };
  75899. /**
  75900. * Loads and creates animations
  75901. */
  75902. var loadAnimations = function (gltfRuntime) {
  75903. for (var anim in gltfRuntime.animations) {
  75904. var animation = gltfRuntime.animations[anim];
  75905. if (!animation.channels || !animation.samplers) {
  75906. continue;
  75907. }
  75908. var lastAnimation = null;
  75909. for (var i = 0; i < animation.channels.length; i++) {
  75910. // Get parameters and load buffers
  75911. var channel = animation.channels[i];
  75912. var sampler = animation.samplers[channel.sampler];
  75913. if (!sampler) {
  75914. continue;
  75915. }
  75916. var inputData = null;
  75917. var outputData = null;
  75918. if (animation.parameters) {
  75919. inputData = animation.parameters[sampler.input];
  75920. outputData = animation.parameters[sampler.output];
  75921. }
  75922. else {
  75923. inputData = sampler.input;
  75924. outputData = sampler.output;
  75925. }
  75926. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  75927. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  75928. var targetID = channel.target.id;
  75929. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  75930. if (targetNode === null) {
  75931. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  75932. }
  75933. if (targetNode === null) {
  75934. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  75935. continue;
  75936. }
  75937. var isBone = targetNode instanceof BABYLON.Bone;
  75938. // Get target path (position, rotation or scaling)
  75939. var targetPath = channel.target.path;
  75940. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  75941. if (targetPathIndex !== -1) {
  75942. targetPath = babylonAnimationPaths[targetPathIndex];
  75943. }
  75944. // Determine animation type
  75945. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  75946. if (!isBone) {
  75947. if (targetPath === "rotationQuaternion") {
  75948. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  75949. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  75950. }
  75951. else {
  75952. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  75953. }
  75954. }
  75955. // Create animation and key frames
  75956. var babylonAnimation = null;
  75957. var keys = [];
  75958. var arrayOffset = 0;
  75959. var modifyKey = false;
  75960. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  75961. babylonAnimation = lastAnimation;
  75962. modifyKey = true;
  75963. }
  75964. if (!modifyKey) {
  75965. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  75966. }
  75967. // For each frame
  75968. for (var j = 0; j < bufferInput.length; j++) {
  75969. var value = null;
  75970. if (targetPath === "rotationQuaternion") {
  75971. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  75972. arrayOffset += 4;
  75973. }
  75974. else {
  75975. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  75976. arrayOffset += 3;
  75977. }
  75978. if (isBone) {
  75979. var bone = targetNode;
  75980. var translation = BABYLON.Vector3.Zero();
  75981. var rotationQuaternion = new BABYLON.Quaternion();
  75982. var scaling = BABYLON.Vector3.Zero();
  75983. // Warning on decompose
  75984. var mat = bone.getBaseMatrix();
  75985. if (modifyKey && lastAnimation) {
  75986. mat = lastAnimation.getKeys()[j].value;
  75987. }
  75988. mat.decompose(scaling, rotationQuaternion, translation);
  75989. if (targetPath === "position") {
  75990. translation = value;
  75991. }
  75992. else if (targetPath === "rotationQuaternion") {
  75993. rotationQuaternion = value;
  75994. }
  75995. else {
  75996. scaling = value;
  75997. }
  75998. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  75999. }
  76000. if (!modifyKey) {
  76001. keys.push({
  76002. frame: bufferInput[j],
  76003. value: value
  76004. });
  76005. }
  76006. else if (lastAnimation) {
  76007. lastAnimation.getKeys()[j].value = value;
  76008. }
  76009. }
  76010. // Finish
  76011. if (!modifyKey && babylonAnimation) {
  76012. babylonAnimation.setKeys(keys);
  76013. targetNode.animations.push(babylonAnimation);
  76014. }
  76015. lastAnimation = babylonAnimation;
  76016. gltfRuntime.scene.stopAnimation(targetNode);
  76017. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  76018. }
  76019. }
  76020. };
  76021. /**
  76022. * Returns the bones transformation matrix
  76023. */
  76024. var configureBoneTransformation = function (node) {
  76025. var mat = null;
  76026. if (node.translation || node.rotation || node.scale) {
  76027. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  76028. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  76029. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  76030. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  76031. }
  76032. else {
  76033. mat = BABYLON.Matrix.FromArray(node.matrix);
  76034. }
  76035. return mat;
  76036. };
  76037. /**
  76038. * Returns the parent bone
  76039. */
  76040. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  76041. // Try to find
  76042. for (var i = 0; i < newSkeleton.bones.length; i++) {
  76043. if (newSkeleton.bones[i].name === jointName) {
  76044. return newSkeleton.bones[i];
  76045. }
  76046. }
  76047. // Not found, search in gltf nodes
  76048. var nodes = gltfRuntime.nodes;
  76049. for (var nde in nodes) {
  76050. var node = nodes[nde];
  76051. if (!node.jointName) {
  76052. continue;
  76053. }
  76054. var children = node.children;
  76055. for (var i = 0; i < children.length; i++) {
  76056. var child = gltfRuntime.nodes[children[i]];
  76057. if (!child.jointName) {
  76058. continue;
  76059. }
  76060. if (child.jointName === jointName) {
  76061. var mat = configureBoneTransformation(node);
  76062. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  76063. bone.id = nde;
  76064. return bone;
  76065. }
  76066. }
  76067. }
  76068. return null;
  76069. };
  76070. /**
  76071. * Returns the appropriate root node
  76072. */
  76073. var getNodeToRoot = function (nodesToRoot, id) {
  76074. for (var i = 0; i < nodesToRoot.length; i++) {
  76075. var nodeToRoot = nodesToRoot[i];
  76076. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  76077. var child = nodeToRoot.node.children[j];
  76078. if (child === id) {
  76079. return nodeToRoot.bone;
  76080. }
  76081. }
  76082. }
  76083. return null;
  76084. };
  76085. /**
  76086. * Returns the node with the joint name
  76087. */
  76088. var getJointNode = function (gltfRuntime, jointName) {
  76089. var nodes = gltfRuntime.nodes;
  76090. var node = nodes[jointName];
  76091. if (node) {
  76092. return {
  76093. node: node,
  76094. id: jointName
  76095. };
  76096. }
  76097. for (var nde in nodes) {
  76098. node = nodes[nde];
  76099. if (node.jointName === jointName) {
  76100. return {
  76101. node: node,
  76102. id: nde
  76103. };
  76104. }
  76105. }
  76106. return null;
  76107. };
  76108. /**
  76109. * Checks if a nodes is in joints
  76110. */
  76111. var nodeIsInJoints = function (skins, id) {
  76112. for (var i = 0; i < skins.jointNames.length; i++) {
  76113. if (skins.jointNames[i] === id) {
  76114. return true;
  76115. }
  76116. }
  76117. return false;
  76118. };
  76119. /**
  76120. * Fills the nodes to root for bones and builds hierarchy
  76121. */
  76122. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  76123. // Creates nodes for root
  76124. for (var nde in gltfRuntime.nodes) {
  76125. var node = gltfRuntime.nodes[nde];
  76126. var id = nde;
  76127. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  76128. continue;
  76129. }
  76130. // Create node to root bone
  76131. var mat = configureBoneTransformation(node);
  76132. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  76133. bone.id = id;
  76134. nodesToRoot.push({ bone: bone, node: node, id: id });
  76135. }
  76136. // Parenting
  76137. for (var i = 0; i < nodesToRoot.length; i++) {
  76138. var nodeToRoot = nodesToRoot[i];
  76139. var children = nodeToRoot.node.children;
  76140. for (var j = 0; j < children.length; j++) {
  76141. var child = null;
  76142. for (var k = 0; k < nodesToRoot.length; k++) {
  76143. if (nodesToRoot[k].id === children[j]) {
  76144. child = nodesToRoot[k];
  76145. break;
  76146. }
  76147. }
  76148. if (child) {
  76149. child.bone._parent = nodeToRoot.bone;
  76150. nodeToRoot.bone.children.push(child.bone);
  76151. }
  76152. }
  76153. }
  76154. };
  76155. /**
  76156. * Imports a skeleton
  76157. */
  76158. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  76159. if (!newSkeleton) {
  76160. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  76161. }
  76162. if (!skins.babylonSkeleton) {
  76163. return newSkeleton;
  76164. }
  76165. // Find the root bones
  76166. var nodesToRoot = [];
  76167. var nodesToRootToAdd = [];
  76168. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  76169. newSkeleton.bones = [];
  76170. // Joints
  76171. for (var i = 0; i < skins.jointNames.length; i++) {
  76172. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76173. if (!jointNode) {
  76174. continue;
  76175. }
  76176. var node = jointNode.node;
  76177. if (!node) {
  76178. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  76179. continue;
  76180. }
  76181. var id = jointNode.id;
  76182. // Optimize, if the bone already exists...
  76183. var existingBone = gltfRuntime.scene.getBoneByID(id);
  76184. if (existingBone) {
  76185. newSkeleton.bones.push(existingBone);
  76186. continue;
  76187. }
  76188. // Search for parent bone
  76189. var foundBone = false;
  76190. var parentBone = null;
  76191. for (var j = 0; j < i; j++) {
  76192. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  76193. if (!jointNode_1) {
  76194. continue;
  76195. }
  76196. var joint = jointNode_1.node;
  76197. if (!joint) {
  76198. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  76199. continue;
  76200. }
  76201. var children = joint.children;
  76202. if (!children) {
  76203. continue;
  76204. }
  76205. foundBone = false;
  76206. for (var k = 0; k < children.length; k++) {
  76207. if (children[k] === id) {
  76208. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  76209. foundBone = true;
  76210. break;
  76211. }
  76212. }
  76213. if (foundBone) {
  76214. break;
  76215. }
  76216. }
  76217. // Create bone
  76218. var mat = configureBoneTransformation(node);
  76219. if (!parentBone && nodesToRoot.length > 0) {
  76220. parentBone = getNodeToRoot(nodesToRoot, id);
  76221. if (parentBone) {
  76222. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  76223. nodesToRootToAdd.push(parentBone);
  76224. }
  76225. }
  76226. }
  76227. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  76228. bone.id = id;
  76229. }
  76230. // Polish
  76231. var bones = newSkeleton.bones;
  76232. newSkeleton.bones = [];
  76233. for (var i = 0; i < skins.jointNames.length; i++) {
  76234. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76235. if (!jointNode) {
  76236. continue;
  76237. }
  76238. for (var j = 0; j < bones.length; j++) {
  76239. if (bones[j].id === jointNode.id) {
  76240. newSkeleton.bones.push(bones[j]);
  76241. break;
  76242. }
  76243. }
  76244. }
  76245. newSkeleton.prepare();
  76246. // Finish
  76247. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  76248. newSkeleton.bones.push(nodesToRootToAdd[i]);
  76249. }
  76250. return newSkeleton;
  76251. };
  76252. /**
  76253. * Imports a mesh and its geometries
  76254. */
  76255. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  76256. if (!newMesh) {
  76257. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  76258. newMesh.id = id;
  76259. }
  76260. if (!node.babylonNode) {
  76261. return newMesh;
  76262. }
  76263. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  76264. if (!newMesh.material) {
  76265. newMesh.material = multiMat;
  76266. }
  76267. var vertexData = new BABYLON.VertexData();
  76268. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  76269. var verticesStarts = new Array();
  76270. var verticesCounts = new Array();
  76271. var indexStarts = new Array();
  76272. var indexCounts = new Array();
  76273. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76274. var meshID = meshes[meshIndex];
  76275. var mesh = gltfRuntime.meshes[meshID];
  76276. if (!mesh) {
  76277. continue;
  76278. }
  76279. // Positions, normals and UVs
  76280. for (var i = 0; i < mesh.primitives.length; i++) {
  76281. // Temporary vertex data
  76282. var tempVertexData = new BABYLON.VertexData();
  76283. var primitive = mesh.primitives[i];
  76284. if (primitive.mode !== 4) {
  76285. // continue;
  76286. }
  76287. var attributes = primitive.attributes;
  76288. var accessor = null;
  76289. var buffer = null;
  76290. // Set positions, normal and uvs
  76291. for (var semantic in attributes) {
  76292. // Link accessor and buffer view
  76293. accessor = gltfRuntime.accessors[attributes[semantic]];
  76294. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76295. if (semantic === "NORMAL") {
  76296. tempVertexData.normals = new Float32Array(buffer.length);
  76297. tempVertexData.normals.set(buffer);
  76298. }
  76299. else if (semantic === "POSITION") {
  76300. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  76301. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  76302. for (var j = 0; j < buffer.length; j += 4) {
  76303. tempVertexData.positions[j] = buffer[j];
  76304. tempVertexData.positions[j + 1] = buffer[j + 1];
  76305. tempVertexData.positions[j + 2] = buffer[j + 2];
  76306. }
  76307. }
  76308. else {
  76309. tempVertexData.positions = new Float32Array(buffer.length);
  76310. tempVertexData.positions.set(buffer);
  76311. }
  76312. verticesCounts.push(tempVertexData.positions.length);
  76313. }
  76314. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  76315. var channel = Number(semantic.split("_")[1]);
  76316. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  76317. var uvs = new Float32Array(buffer.length);
  76318. uvs.set(buffer);
  76319. normalizeUVs(uvs);
  76320. tempVertexData.set(uvs, uvKind);
  76321. }
  76322. else if (semantic === "JOINT") {
  76323. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  76324. tempVertexData.matricesIndices.set(buffer);
  76325. }
  76326. else if (semantic === "WEIGHT") {
  76327. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  76328. tempVertexData.matricesWeights.set(buffer);
  76329. }
  76330. else if (semantic === "COLOR") {
  76331. tempVertexData.colors = new Float32Array(buffer.length);
  76332. tempVertexData.colors.set(buffer);
  76333. }
  76334. }
  76335. // Indices
  76336. accessor = gltfRuntime.accessors[primitive.indices];
  76337. if (accessor) {
  76338. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76339. tempVertexData.indices = new Int32Array(buffer.length);
  76340. tempVertexData.indices.set(buffer);
  76341. indexCounts.push(tempVertexData.indices.length);
  76342. }
  76343. else {
  76344. // Set indices on the fly
  76345. var indices = [];
  76346. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  76347. indices.push(j);
  76348. }
  76349. tempVertexData.indices = new Int32Array(indices);
  76350. indexCounts.push(tempVertexData.indices.length);
  76351. }
  76352. vertexData.merge(tempVertexData);
  76353. // Sub material
  76354. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  76355. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  76356. // Update vertices start and index start
  76357. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  76358. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  76359. }
  76360. }
  76361. // Apply geometry
  76362. geometry.setAllVerticesData(vertexData, false);
  76363. newMesh.computeWorldMatrix(true);
  76364. // Apply submeshes
  76365. newMesh.subMeshes = [];
  76366. var index = 0;
  76367. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76368. var meshID = meshes[meshIndex];
  76369. var mesh = gltfRuntime.meshes[meshID];
  76370. if (!mesh) {
  76371. continue;
  76372. }
  76373. for (var i = 0; i < mesh.primitives.length; i++) {
  76374. if (mesh.primitives[i].mode !== 4) {
  76375. //continue;
  76376. }
  76377. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  76378. index++;
  76379. }
  76380. }
  76381. // Finish
  76382. return newMesh;
  76383. };
  76384. /**
  76385. * Configure node transformation from position, rotation and scaling
  76386. */
  76387. var configureNode = function (newNode, position, rotation, scaling) {
  76388. if (newNode.position) {
  76389. newNode.position = position;
  76390. }
  76391. if (newNode.rotationQuaternion || newNode.rotation) {
  76392. newNode.rotationQuaternion = rotation;
  76393. }
  76394. if (newNode.scaling) {
  76395. newNode.scaling = scaling;
  76396. }
  76397. };
  76398. /**
  76399. * Configures node from transformation matrix
  76400. */
  76401. var configureNodeFromMatrix = function (newNode, node, parent) {
  76402. if (node.matrix) {
  76403. var position = new BABYLON.Vector3(0, 0, 0);
  76404. var rotation = new BABYLON.Quaternion();
  76405. var scaling = new BABYLON.Vector3(0, 0, 0);
  76406. var mat = BABYLON.Matrix.FromArray(node.matrix);
  76407. mat.decompose(scaling, rotation, position);
  76408. configureNode(newNode, position, rotation, scaling);
  76409. }
  76410. else if (node.translation && node.rotation && node.scale) {
  76411. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  76412. }
  76413. newNode.computeWorldMatrix(true);
  76414. };
  76415. /**
  76416. * Imports a node
  76417. */
  76418. var importNode = function (gltfRuntime, node, id, parent) {
  76419. var lastNode = null;
  76420. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  76421. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  76422. return null;
  76423. }
  76424. }
  76425. // Meshes
  76426. if (node.skin) {
  76427. if (node.meshes) {
  76428. var skin = gltfRuntime.skins[node.skin];
  76429. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  76430. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  76431. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  76432. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  76433. if (!skin.babylonSkeleton) {
  76434. skin.babylonSkeleton = newMesh.skeleton;
  76435. }
  76436. }
  76437. lastNode = newMesh;
  76438. }
  76439. }
  76440. else if (node.meshes) {
  76441. /**
  76442. * Improve meshes property
  76443. */
  76444. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  76445. lastNode = newMesh;
  76446. }
  76447. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  76448. var light = gltfRuntime.lights[node.light];
  76449. if (light) {
  76450. if (light.type === "ambient") {
  76451. var ambienLight = light[light.type];
  76452. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76453. hemiLight.name = node.name || "";
  76454. if (ambienLight.color) {
  76455. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  76456. }
  76457. lastNode = hemiLight;
  76458. }
  76459. else if (light.type === "directional") {
  76460. var directionalLight = light[light.type];
  76461. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76462. dirLight.name = node.name || "";
  76463. if (directionalLight.color) {
  76464. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  76465. }
  76466. lastNode = dirLight;
  76467. }
  76468. else if (light.type === "point") {
  76469. var pointLight = light[light.type];
  76470. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76471. ptLight.name = node.name || "";
  76472. if (pointLight.color) {
  76473. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  76474. }
  76475. lastNode = ptLight;
  76476. }
  76477. else if (light.type === "spot") {
  76478. var spotLight = light[light.type];
  76479. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  76480. spLight.name = node.name || "";
  76481. if (spotLight.color) {
  76482. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  76483. }
  76484. if (spotLight.fallOfAngle) {
  76485. spLight.angle = spotLight.fallOfAngle;
  76486. }
  76487. if (spotLight.fallOffExponent) {
  76488. spLight.exponent = spotLight.fallOffExponent;
  76489. }
  76490. lastNode = spLight;
  76491. }
  76492. }
  76493. }
  76494. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  76495. var camera = gltfRuntime.cameras[node.camera];
  76496. if (camera) {
  76497. if (camera.type === "orthographic") {
  76498. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76499. orthoCamera.name = node.name || "";
  76500. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  76501. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  76502. lastNode = orthoCamera;
  76503. }
  76504. else if (camera.type === "perspective") {
  76505. var perspectiveCamera = camera[camera.type];
  76506. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76507. persCamera.name = node.name || "";
  76508. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  76509. if (!perspectiveCamera.aspectRatio) {
  76510. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  76511. }
  76512. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  76513. persCamera.maxZ = perspectiveCamera.zfar;
  76514. persCamera.minZ = perspectiveCamera.znear;
  76515. }
  76516. lastNode = persCamera;
  76517. }
  76518. }
  76519. }
  76520. // Empty node
  76521. if (!node.jointName) {
  76522. if (node.babylonNode) {
  76523. return node.babylonNode;
  76524. }
  76525. else if (lastNode === null) {
  76526. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  76527. node.babylonNode = dummy;
  76528. lastNode = dummy;
  76529. }
  76530. }
  76531. if (lastNode !== null) {
  76532. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  76533. configureNodeFromMatrix(lastNode, node, parent);
  76534. }
  76535. else {
  76536. var translation = node.translation || [0, 0, 0];
  76537. var rotation = node.rotation || [0, 0, 0, 1];
  76538. var scale = node.scale || [1, 1, 1];
  76539. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  76540. }
  76541. lastNode.updateCache(true);
  76542. node.babylonNode = lastNode;
  76543. }
  76544. return lastNode;
  76545. };
  76546. /**
  76547. * Traverses nodes and creates them
  76548. */
  76549. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  76550. if (meshIncluded === void 0) { meshIncluded = false; }
  76551. var node = gltfRuntime.nodes[id];
  76552. var newNode = null;
  76553. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  76554. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  76555. meshIncluded = true;
  76556. }
  76557. else {
  76558. meshIncluded = false;
  76559. }
  76560. }
  76561. else {
  76562. meshIncluded = true;
  76563. }
  76564. if (!node.jointName && meshIncluded) {
  76565. newNode = importNode(gltfRuntime, node, id, parent);
  76566. if (newNode !== null) {
  76567. newNode.id = id;
  76568. newNode.parent = parent;
  76569. }
  76570. }
  76571. if (node.children) {
  76572. for (var i = 0; i < node.children.length; i++) {
  76573. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  76574. }
  76575. }
  76576. };
  76577. /**
  76578. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  76579. */
  76580. var postLoad = function (gltfRuntime) {
  76581. // Nodes
  76582. var currentScene = gltfRuntime.currentScene;
  76583. if (currentScene) {
  76584. for (var i = 0; i < currentScene.nodes.length; i++) {
  76585. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  76586. }
  76587. }
  76588. else {
  76589. for (var thing in gltfRuntime.scenes) {
  76590. currentScene = gltfRuntime.scenes[thing];
  76591. for (var i = 0; i < currentScene.nodes.length; i++) {
  76592. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  76593. }
  76594. }
  76595. }
  76596. // Set animations
  76597. loadAnimations(gltfRuntime);
  76598. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  76599. var skeleton = gltfRuntime.scene.skeletons[i];
  76600. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  76601. }
  76602. };
  76603. /**
  76604. * onBind shaderrs callback to set uniforms and matrices
  76605. */
  76606. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  76607. var materialValues = material.values || technique.parameters;
  76608. for (var unif in unTreatedUniforms) {
  76609. var uniform = unTreatedUniforms[unif];
  76610. var type = uniform.type;
  76611. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  76612. if (uniform.semantic && !uniform.source && !uniform.node) {
  76613. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  76614. }
  76615. else if (uniform.semantic && (uniform.source || uniform.node)) {
  76616. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  76617. if (source === null) {
  76618. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  76619. }
  76620. if (source === null) {
  76621. continue;
  76622. }
  76623. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  76624. }
  76625. }
  76626. else {
  76627. var value = materialValues[technique.uniforms[unif]];
  76628. if (!value) {
  76629. continue;
  76630. }
  76631. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  76632. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  76633. if (texture === null || texture === undefined) {
  76634. continue;
  76635. }
  76636. shaderMaterial.getEffect().setTexture(unif, texture);
  76637. }
  76638. else {
  76639. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  76640. }
  76641. }
  76642. }
  76643. onSuccess(shaderMaterial);
  76644. };
  76645. /**
  76646. * Prepare uniforms to send the only one time
  76647. * Loads the appropriate textures
  76648. */
  76649. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  76650. var materialValues = material.values || technique.parameters;
  76651. var techniqueUniforms = technique.uniforms;
  76652. /**
  76653. * Prepare values here (not matrices)
  76654. */
  76655. for (var unif in unTreatedUniforms) {
  76656. var uniform = unTreatedUniforms[unif];
  76657. var type = uniform.type;
  76658. var value = materialValues[techniqueUniforms[unif]];
  76659. if (value === undefined) {
  76660. // In case the value is the same for all materials
  76661. value = uniform.value;
  76662. }
  76663. if (!value) {
  76664. continue;
  76665. }
  76666. var onLoadTexture = function (uniformName) {
  76667. return function (texture) {
  76668. if (uniform.value && uniformName) {
  76669. // Static uniform
  76670. shaderMaterial.setTexture(uniformName, texture);
  76671. delete unTreatedUniforms[uniformName];
  76672. }
  76673. };
  76674. };
  76675. // Texture (sampler2D)
  76676. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  76677. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  76678. }
  76679. else {
  76680. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  76681. // Static uniform
  76682. delete unTreatedUniforms[unif];
  76683. }
  76684. }
  76685. }
  76686. };
  76687. /**
  76688. * Shader compilation failed
  76689. */
  76690. var onShaderCompileError = function (program, shaderMaterial, onError) {
  76691. return function (effect, error) {
  76692. shaderMaterial.dispose(true);
  76693. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  76694. };
  76695. };
  76696. /**
  76697. * Shader compilation success
  76698. */
  76699. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  76700. return function (_) {
  76701. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  76702. shaderMaterial.onBind = function (mesh) {
  76703. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  76704. };
  76705. };
  76706. };
  76707. /**
  76708. * Returns the appropriate uniform if already handled by babylon
  76709. */
  76710. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  76711. for (var unif in technique.uniforms) {
  76712. var uniform = technique.uniforms[unif];
  76713. var uniformParameter = technique.parameters[uniform];
  76714. if (tokenizer.currentIdentifier === unif) {
  76715. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  76716. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  76717. if (transformIndex !== -1) {
  76718. delete unTreatedUniforms[unif];
  76719. return babylonTransforms[transformIndex];
  76720. }
  76721. }
  76722. }
  76723. }
  76724. return tokenizer.currentIdentifier;
  76725. };
  76726. /**
  76727. * All shaders loaded. Create materials one by one
  76728. */
  76729. var importMaterials = function (gltfRuntime) {
  76730. // Create materials
  76731. for (var mat in gltfRuntime.materials) {
  76732. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  76733. }
  76734. };
  76735. /**
  76736. * Implementation of the base glTF spec
  76737. */
  76738. var GLTFLoaderBase = /** @class */ (function () {
  76739. function GLTFLoaderBase() {
  76740. }
  76741. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  76742. var gltfRuntime = {
  76743. extensions: {},
  76744. accessors: {},
  76745. buffers: {},
  76746. bufferViews: {},
  76747. meshes: {},
  76748. lights: {},
  76749. cameras: {},
  76750. nodes: {},
  76751. images: {},
  76752. textures: {},
  76753. shaders: {},
  76754. programs: {},
  76755. samplers: {},
  76756. techniques: {},
  76757. materials: {},
  76758. animations: {},
  76759. skins: {},
  76760. extensionsUsed: [],
  76761. scenes: {},
  76762. buffersCount: 0,
  76763. shaderscount: 0,
  76764. scene: scene,
  76765. rootUrl: rootUrl,
  76766. loadedBufferCount: 0,
  76767. loadedBufferViews: {},
  76768. loadedShaderCount: 0,
  76769. importOnlyMeshes: false,
  76770. dummyNodes: []
  76771. };
  76772. // Parse
  76773. if (parsedData.extensions) {
  76774. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  76775. }
  76776. if (parsedData.extensionsUsed) {
  76777. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  76778. }
  76779. if (parsedData.buffers) {
  76780. parseBuffers(parsedData.buffers, gltfRuntime);
  76781. }
  76782. if (parsedData.bufferViews) {
  76783. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  76784. }
  76785. if (parsedData.accessors) {
  76786. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  76787. }
  76788. if (parsedData.meshes) {
  76789. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  76790. }
  76791. if (parsedData.lights) {
  76792. parseObject(parsedData.lights, "lights", gltfRuntime);
  76793. }
  76794. if (parsedData.cameras) {
  76795. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  76796. }
  76797. if (parsedData.nodes) {
  76798. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  76799. }
  76800. if (parsedData.images) {
  76801. parseObject(parsedData.images, "images", gltfRuntime);
  76802. }
  76803. if (parsedData.textures) {
  76804. parseObject(parsedData.textures, "textures", gltfRuntime);
  76805. }
  76806. if (parsedData.shaders) {
  76807. parseShaders(parsedData.shaders, gltfRuntime);
  76808. }
  76809. if (parsedData.programs) {
  76810. parseObject(parsedData.programs, "programs", gltfRuntime);
  76811. }
  76812. if (parsedData.samplers) {
  76813. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  76814. }
  76815. if (parsedData.techniques) {
  76816. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  76817. }
  76818. if (parsedData.materials) {
  76819. parseObject(parsedData.materials, "materials", gltfRuntime);
  76820. }
  76821. if (parsedData.animations) {
  76822. parseObject(parsedData.animations, "animations", gltfRuntime);
  76823. }
  76824. if (parsedData.skins) {
  76825. parseObject(parsedData.skins, "skins", gltfRuntime);
  76826. }
  76827. if (parsedData.scenes) {
  76828. gltfRuntime.scenes = parsedData.scenes;
  76829. }
  76830. if (parsedData.scene && parsedData.scenes) {
  76831. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  76832. }
  76833. return gltfRuntime;
  76834. };
  76835. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  76836. var buffer = gltfRuntime.buffers[id];
  76837. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  76838. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  76839. }
  76840. else {
  76841. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  76842. if (request) {
  76843. onError(request.status + " " + request.statusText);
  76844. }
  76845. });
  76846. }
  76847. };
  76848. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  76849. var texture = gltfRuntime.textures[id];
  76850. if (!texture || !texture.source) {
  76851. onError("");
  76852. return;
  76853. }
  76854. if (texture.babylonTexture) {
  76855. onSuccess(null);
  76856. return;
  76857. }
  76858. var source = gltfRuntime.images[texture.source];
  76859. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  76860. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  76861. }
  76862. else {
  76863. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  76864. if (request) {
  76865. onError(request.status + " " + request.statusText);
  76866. }
  76867. });
  76868. }
  76869. };
  76870. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  76871. var texture = gltfRuntime.textures[id];
  76872. if (texture.babylonTexture) {
  76873. onSuccess(texture.babylonTexture);
  76874. return;
  76875. }
  76876. var sampler = gltfRuntime.samplers[texture.sampler];
  76877. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  76878. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  76879. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  76880. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  76881. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  76882. var blob = new Blob([buffer]);
  76883. var blobURL = URL.createObjectURL(blob);
  76884. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  76885. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  76886. if (sampler.wrapS !== undefined) {
  76887. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  76888. }
  76889. if (sampler.wrapT !== undefined) {
  76890. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  76891. }
  76892. newTexture.name = id;
  76893. texture.babylonTexture = newTexture;
  76894. onSuccess(newTexture);
  76895. };
  76896. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  76897. var shader = gltfRuntime.shaders[id];
  76898. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  76899. var shaderString = atob(shader.uri.split(",")[1]);
  76900. onSuccess(shaderString);
  76901. }
  76902. else {
  76903. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  76904. if (request) {
  76905. onError(request.status + " " + request.statusText);
  76906. }
  76907. });
  76908. }
  76909. };
  76910. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  76911. var material = gltfRuntime.materials[id];
  76912. if (!material.technique) {
  76913. if (onError) {
  76914. onError("No technique found.");
  76915. }
  76916. return;
  76917. }
  76918. var technique = gltfRuntime.techniques[material.technique];
  76919. if (!technique) {
  76920. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  76921. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  76922. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  76923. onSuccess(defaultMaterial);
  76924. return;
  76925. }
  76926. var program = gltfRuntime.programs[technique.program];
  76927. var states = technique.states;
  76928. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  76929. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  76930. var newVertexShader = "";
  76931. var newPixelShader = "";
  76932. var vertexTokenizer = new Tokenizer(vertexShader);
  76933. var pixelTokenizer = new Tokenizer(pixelShader);
  76934. var unTreatedUniforms = {};
  76935. var uniforms = [];
  76936. var attributes = [];
  76937. var samplers = [];
  76938. // Fill uniform, sampler2D and attributes
  76939. for (var unif in technique.uniforms) {
  76940. var uniform = technique.uniforms[unif];
  76941. var uniformParameter = technique.parameters[uniform];
  76942. unTreatedUniforms[unif] = uniformParameter;
  76943. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  76944. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  76945. if (transformIndex !== -1) {
  76946. uniforms.push(babylonTransforms[transformIndex]);
  76947. delete unTreatedUniforms[unif];
  76948. }
  76949. else {
  76950. uniforms.push(unif);
  76951. }
  76952. }
  76953. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  76954. samplers.push(unif);
  76955. }
  76956. else {
  76957. uniforms.push(unif);
  76958. }
  76959. }
  76960. for (var attr in technique.attributes) {
  76961. var attribute = technique.attributes[attr];
  76962. var attributeParameter = technique.parameters[attribute];
  76963. if (attributeParameter.semantic) {
  76964. attributes.push(getAttribute(attributeParameter));
  76965. }
  76966. }
  76967. // Configure vertex shader
  76968. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  76969. var tokenType = vertexTokenizer.currentToken;
  76970. if (tokenType !== ETokenType.IDENTIFIER) {
  76971. newVertexShader += vertexTokenizer.currentString;
  76972. continue;
  76973. }
  76974. var foundAttribute = false;
  76975. for (var attr in technique.attributes) {
  76976. var attribute = technique.attributes[attr];
  76977. var attributeParameter = technique.parameters[attribute];
  76978. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  76979. newVertexShader += getAttribute(attributeParameter);
  76980. foundAttribute = true;
  76981. break;
  76982. }
  76983. }
  76984. if (foundAttribute) {
  76985. continue;
  76986. }
  76987. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  76988. }
  76989. // Configure pixel shader
  76990. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  76991. var tokenType = pixelTokenizer.currentToken;
  76992. if (tokenType !== ETokenType.IDENTIFIER) {
  76993. newPixelShader += pixelTokenizer.currentString;
  76994. continue;
  76995. }
  76996. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  76997. }
  76998. // Create shader material
  76999. var shaderPath = {
  77000. vertex: program.vertexShader + id,
  77001. fragment: program.fragmentShader + id
  77002. };
  77003. var options = {
  77004. attributes: attributes,
  77005. uniforms: uniforms,
  77006. samplers: samplers,
  77007. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  77008. };
  77009. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  77010. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  77011. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  77012. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  77013. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  77014. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77015. if (states && states.functions) {
  77016. var functions = states.functions;
  77017. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  77018. shaderMaterial.backFaceCulling = false;
  77019. }
  77020. var blendFunc = functions.blendFuncSeparate;
  77021. if (blendFunc) {
  77022. 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) {
  77023. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  77024. }
  77025. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77026. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  77027. }
  77028. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77029. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  77030. }
  77031. 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) {
  77032. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  77033. }
  77034. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77035. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  77036. }
  77037. 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) {
  77038. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  77039. }
  77040. }
  77041. }
  77042. };
  77043. return GLTFLoaderBase;
  77044. }());
  77045. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  77046. /**
  77047. * glTF V1 Loader
  77048. */
  77049. var GLTFLoader = /** @class */ (function () {
  77050. function GLTFLoader() {
  77051. }
  77052. GLTFLoader.RegisterExtension = function (extension) {
  77053. if (GLTFLoader.Extensions[extension.name]) {
  77054. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  77055. return;
  77056. }
  77057. GLTFLoader.Extensions[extension.name] = extension;
  77058. };
  77059. GLTFLoader.prototype.dispose = function () {
  77060. // do nothing
  77061. };
  77062. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77063. var _this = this;
  77064. scene.useRightHandedSystem = true;
  77065. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77066. gltfRuntime.importOnlyMeshes = true;
  77067. if (meshesNames === "") {
  77068. gltfRuntime.importMeshesNames = [];
  77069. }
  77070. else if (typeof meshesNames === "string") {
  77071. gltfRuntime.importMeshesNames = [meshesNames];
  77072. }
  77073. else if (meshesNames && !(meshesNames instanceof Array)) {
  77074. gltfRuntime.importMeshesNames = [meshesNames];
  77075. }
  77076. else {
  77077. gltfRuntime.importMeshesNames = [];
  77078. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  77079. }
  77080. // Create nodes
  77081. _this._createNodes(gltfRuntime);
  77082. var meshes = new Array();
  77083. var skeletons = new Array();
  77084. // Fill arrays of meshes and skeletons
  77085. for (var nde in gltfRuntime.nodes) {
  77086. var node = gltfRuntime.nodes[nde];
  77087. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  77088. meshes.push(node.babylonNode);
  77089. }
  77090. }
  77091. for (var skl in gltfRuntime.skins) {
  77092. var skin = gltfRuntime.skins[skl];
  77093. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  77094. skeletons.push(skin.babylonSkeleton);
  77095. }
  77096. }
  77097. // Load buffers, shaders, materials, etc.
  77098. _this._loadBuffersAsync(gltfRuntime, function () {
  77099. _this._loadShadersAsync(gltfRuntime, function () {
  77100. importMaterials(gltfRuntime);
  77101. postLoad(gltfRuntime);
  77102. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77103. onSuccess(meshes, null, skeletons);
  77104. }
  77105. });
  77106. }, onProgress);
  77107. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77108. onSuccess(meshes, null, skeletons);
  77109. }
  77110. }, onError);
  77111. return true;
  77112. };
  77113. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77114. var _this = this;
  77115. scene.useRightHandedSystem = true;
  77116. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77117. // Load runtime extensios
  77118. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  77119. // Create nodes
  77120. _this._createNodes(gltfRuntime);
  77121. // Load buffers, shaders, materials, etc.
  77122. _this._loadBuffersAsync(gltfRuntime, function () {
  77123. _this._loadShadersAsync(gltfRuntime, function () {
  77124. importMaterials(gltfRuntime);
  77125. postLoad(gltfRuntime);
  77126. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  77127. onSuccess();
  77128. }
  77129. });
  77130. });
  77131. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  77132. onSuccess();
  77133. }
  77134. }, onError);
  77135. }, onError);
  77136. };
  77137. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  77138. var hasShaders = false;
  77139. var processShader = function (sha, shader) {
  77140. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  77141. gltfRuntime.loadedShaderCount++;
  77142. if (shaderString) {
  77143. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  77144. }
  77145. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  77146. onload();
  77147. }
  77148. }, function () {
  77149. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  77150. });
  77151. };
  77152. for (var sha in gltfRuntime.shaders) {
  77153. hasShaders = true;
  77154. var shader = gltfRuntime.shaders[sha];
  77155. if (shader) {
  77156. processShader.bind(this, sha, shader)();
  77157. }
  77158. else {
  77159. BABYLON.Tools.Error("No shader named: " + sha);
  77160. }
  77161. }
  77162. if (!hasShaders) {
  77163. onload();
  77164. }
  77165. };
  77166. ;
  77167. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  77168. var hasBuffers = false;
  77169. var processBuffer = function (buf, buffer) {
  77170. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  77171. gltfRuntime.loadedBufferCount++;
  77172. if (bufferView) {
  77173. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  77174. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  77175. }
  77176. gltfRuntime.loadedBufferViews[buf] = bufferView;
  77177. }
  77178. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  77179. onLoad();
  77180. }
  77181. }, function () {
  77182. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  77183. });
  77184. };
  77185. for (var buf in gltfRuntime.buffers) {
  77186. hasBuffers = true;
  77187. var buffer = gltfRuntime.buffers[buf];
  77188. if (buffer) {
  77189. processBuffer.bind(this, buf, buffer)();
  77190. }
  77191. else {
  77192. BABYLON.Tools.Error("No buffer named: " + buf);
  77193. }
  77194. }
  77195. if (!hasBuffers) {
  77196. onLoad();
  77197. }
  77198. };
  77199. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  77200. var currentScene = gltfRuntime.currentScene;
  77201. if (currentScene) {
  77202. // Only one scene even if multiple scenes are defined
  77203. for (var i = 0; i < currentScene.nodes.length; i++) {
  77204. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77205. }
  77206. }
  77207. else {
  77208. // Load all scenes
  77209. for (var thing in gltfRuntime.scenes) {
  77210. currentScene = gltfRuntime.scenes[thing];
  77211. for (var i = 0; i < currentScene.nodes.length; i++) {
  77212. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77213. }
  77214. }
  77215. }
  77216. };
  77217. GLTFLoader.Extensions = {};
  77218. return GLTFLoader;
  77219. }());
  77220. GLTF1.GLTFLoader = GLTFLoader;
  77221. ;
  77222. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  77223. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77224. })(BABYLON || (BABYLON = {}));
  77225. //# sourceMappingURL=babylon.glTFLoader.js.map
  77226. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77227. var BABYLON;
  77228. (function (BABYLON) {
  77229. var GLTF1;
  77230. (function (GLTF1) {
  77231. /**
  77232. * Utils functions for GLTF
  77233. */
  77234. var GLTFUtils = /** @class */ (function () {
  77235. function GLTFUtils() {
  77236. }
  77237. /**
  77238. * Sets the given "parameter" matrix
  77239. * @param scene: the {BABYLON.Scene} object
  77240. * @param source: the source node where to pick the matrix
  77241. * @param parameter: the GLTF technique parameter
  77242. * @param uniformName: the name of the shader's uniform
  77243. * @param shaderMaterial: the shader material
  77244. */
  77245. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  77246. var mat = null;
  77247. if (parameter.semantic === "MODEL") {
  77248. mat = source.getWorldMatrix();
  77249. }
  77250. else if (parameter.semantic === "PROJECTION") {
  77251. mat = scene.getProjectionMatrix();
  77252. }
  77253. else if (parameter.semantic === "VIEW") {
  77254. mat = scene.getViewMatrix();
  77255. }
  77256. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  77257. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  77258. }
  77259. else if (parameter.semantic === "MODELVIEW") {
  77260. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  77261. }
  77262. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  77263. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  77264. }
  77265. else if (parameter.semantic === "MODELINVERSE") {
  77266. mat = source.getWorldMatrix().invert();
  77267. }
  77268. else if (parameter.semantic === "VIEWINVERSE") {
  77269. mat = scene.getViewMatrix().invert();
  77270. }
  77271. else if (parameter.semantic === "PROJECTIONINVERSE") {
  77272. mat = scene.getProjectionMatrix().invert();
  77273. }
  77274. else if (parameter.semantic === "MODELVIEWINVERSE") {
  77275. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  77276. }
  77277. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  77278. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  77279. }
  77280. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  77281. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  77282. }
  77283. else {
  77284. debugger;
  77285. }
  77286. if (mat) {
  77287. switch (parameter.type) {
  77288. case GLTF1.EParameterType.FLOAT_MAT2:
  77289. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  77290. break;
  77291. case GLTF1.EParameterType.FLOAT_MAT3:
  77292. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  77293. break;
  77294. case GLTF1.EParameterType.FLOAT_MAT4:
  77295. shaderMaterial.setMatrix(uniformName, mat);
  77296. break;
  77297. default: break;
  77298. }
  77299. }
  77300. };
  77301. /**
  77302. * Sets the given "parameter" matrix
  77303. * @param shaderMaterial: the shader material
  77304. * @param uniform: the name of the shader's uniform
  77305. * @param value: the value of the uniform
  77306. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  77307. */
  77308. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  77309. switch (type) {
  77310. case GLTF1.EParameterType.FLOAT:
  77311. shaderMaterial.setFloat(uniform, value);
  77312. return true;
  77313. case GLTF1.EParameterType.FLOAT_VEC2:
  77314. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  77315. return true;
  77316. case GLTF1.EParameterType.FLOAT_VEC3:
  77317. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  77318. return true;
  77319. case GLTF1.EParameterType.FLOAT_VEC4:
  77320. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  77321. return true;
  77322. default: return false;
  77323. }
  77324. };
  77325. /**
  77326. * If the uri is a base64 string
  77327. * @param uri: the uri to test
  77328. */
  77329. GLTFUtils.IsBase64 = function (uri) {
  77330. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  77331. };
  77332. /**
  77333. * Decode the base64 uri
  77334. * @param uri: the uri to decode
  77335. */
  77336. GLTFUtils.DecodeBase64 = function (uri) {
  77337. var decodedString = atob(uri.split(",")[1]);
  77338. var bufferLength = decodedString.length;
  77339. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  77340. for (var i = 0; i < bufferLength; i++) {
  77341. bufferView[i] = decodedString.charCodeAt(i);
  77342. }
  77343. return bufferView.buffer;
  77344. };
  77345. /**
  77346. * Returns the wrap mode of the texture
  77347. * @param mode: the mode value
  77348. */
  77349. GLTFUtils.GetWrapMode = function (mode) {
  77350. switch (mode) {
  77351. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  77352. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  77353. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77354. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77355. }
  77356. };
  77357. /**
  77358. * Returns the byte stride giving an accessor
  77359. * @param accessor: the GLTF accessor objet
  77360. */
  77361. GLTFUtils.GetByteStrideFromType = function (accessor) {
  77362. // Needs this function since "byteStride" isn't requiered in glTF format
  77363. var type = accessor.type;
  77364. switch (type) {
  77365. case "VEC2": return 2;
  77366. case "VEC3": return 3;
  77367. case "VEC4": return 4;
  77368. case "MAT2": return 4;
  77369. case "MAT3": return 9;
  77370. case "MAT4": return 16;
  77371. default: return 1;
  77372. }
  77373. };
  77374. /**
  77375. * Returns the texture filter mode giving a mode value
  77376. * @param mode: the filter mode value
  77377. */
  77378. GLTFUtils.GetTextureFilterMode = function (mode) {
  77379. switch (mode) {
  77380. case GLTF1.ETextureFilterType.LINEAR:
  77381. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  77382. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  77383. case GLTF1.ETextureFilterType.NEAREST:
  77384. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  77385. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  77386. }
  77387. };
  77388. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  77389. var byteOffset = bufferView.byteOffset + byteOffset;
  77390. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  77391. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  77392. throw new Error("Buffer access is out of range");
  77393. }
  77394. var buffer = loadedBufferView.buffer;
  77395. byteOffset += loadedBufferView.byteOffset;
  77396. switch (componentType) {
  77397. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  77398. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  77399. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  77400. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  77401. default: return new Float32Array(buffer, byteOffset, byteLength);
  77402. }
  77403. };
  77404. /**
  77405. * Returns a buffer from its accessor
  77406. * @param gltfRuntime: the GLTF runtime
  77407. * @param accessor: the GLTF accessor
  77408. */
  77409. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  77410. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  77411. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  77412. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  77413. };
  77414. /**
  77415. * Decodes a buffer view into a string
  77416. * @param view: the buffer view
  77417. */
  77418. GLTFUtils.DecodeBufferToText = function (view) {
  77419. var result = "";
  77420. var length = view.byteLength;
  77421. for (var i = 0; i < length; ++i) {
  77422. result += String.fromCharCode(view[i]);
  77423. }
  77424. return result;
  77425. };
  77426. /**
  77427. * Returns the default material of gltf. Related to
  77428. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  77429. * @param scene: the Babylon.js scene
  77430. */
  77431. GLTFUtils.GetDefaultMaterial = function (scene) {
  77432. if (!GLTFUtils._DefaultMaterial) {
  77433. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  77434. "precision highp float;",
  77435. "",
  77436. "uniform mat4 worldView;",
  77437. "uniform mat4 projection;",
  77438. "",
  77439. "attribute vec3 position;",
  77440. "",
  77441. "void main(void)",
  77442. "{",
  77443. " gl_Position = projection * worldView * vec4(position, 1.0);",
  77444. "}"
  77445. ].join("\n");
  77446. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  77447. "precision highp float;",
  77448. "",
  77449. "uniform vec4 u_emission;",
  77450. "",
  77451. "void main(void)",
  77452. "{",
  77453. " gl_FragColor = u_emission;",
  77454. "}"
  77455. ].join("\n");
  77456. var shaderPath = {
  77457. vertex: "GLTFDefaultMaterial",
  77458. fragment: "GLTFDefaultMaterial"
  77459. };
  77460. var options = {
  77461. attributes: ["position"],
  77462. uniforms: ["worldView", "projection", "u_emission"],
  77463. samplers: new Array(),
  77464. needAlphaBlending: false
  77465. };
  77466. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  77467. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  77468. }
  77469. return GLTFUtils._DefaultMaterial;
  77470. };
  77471. // The GLTF default material
  77472. GLTFUtils._DefaultMaterial = null;
  77473. return GLTFUtils;
  77474. }());
  77475. GLTF1.GLTFUtils = GLTFUtils;
  77476. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77477. })(BABYLON || (BABYLON = {}));
  77478. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  77479. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77480. var BABYLON;
  77481. (function (BABYLON) {
  77482. var GLTF1;
  77483. (function (GLTF1) {
  77484. var GLTFLoaderExtension = /** @class */ (function () {
  77485. function GLTFLoaderExtension(name) {
  77486. this._name = name;
  77487. }
  77488. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  77489. get: function () {
  77490. return this._name;
  77491. },
  77492. enumerable: true,
  77493. configurable: true
  77494. });
  77495. /**
  77496. * Defines an override for loading the runtime
  77497. * Return true to stop further extensions from loading the runtime
  77498. */
  77499. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77500. return false;
  77501. };
  77502. /**
  77503. * Defines an onverride for creating gltf runtime
  77504. * Return true to stop further extensions from creating the runtime
  77505. */
  77506. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77507. return false;
  77508. };
  77509. /**
  77510. * Defines an override for loading buffers
  77511. * Return true to stop further extensions from loading this buffer
  77512. */
  77513. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77514. return false;
  77515. };
  77516. /**
  77517. * Defines an override for loading texture buffers
  77518. * Return true to stop further extensions from loading this texture data
  77519. */
  77520. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77521. return false;
  77522. };
  77523. /**
  77524. * Defines an override for creating textures
  77525. * Return true to stop further extensions from loading this texture
  77526. */
  77527. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77528. return false;
  77529. };
  77530. /**
  77531. * Defines an override for loading shader strings
  77532. * Return true to stop further extensions from loading this shader data
  77533. */
  77534. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77535. return false;
  77536. };
  77537. /**
  77538. * Defines an override for loading materials
  77539. * Return true to stop further extensions from loading this material
  77540. */
  77541. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77542. return false;
  77543. };
  77544. // ---------
  77545. // Utilities
  77546. // ---------
  77547. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77548. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77549. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  77550. }, function () {
  77551. setTimeout(function () {
  77552. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  77553. });
  77554. });
  77555. };
  77556. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77557. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77558. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  77559. }, function () {
  77560. setTimeout(function () {
  77561. onSuccess();
  77562. });
  77563. });
  77564. };
  77565. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77566. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77567. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  77568. }, function () {
  77569. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  77570. });
  77571. };
  77572. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  77573. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  77574. };
  77575. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77576. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77577. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  77578. }, function () {
  77579. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  77580. });
  77581. };
  77582. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77583. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77584. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  77585. }, function () {
  77586. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  77587. });
  77588. };
  77589. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77590. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77591. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  77592. }, function () {
  77593. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  77594. });
  77595. };
  77596. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77597. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77598. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  77599. }, function () {
  77600. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  77601. });
  77602. };
  77603. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  77604. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  77605. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  77606. if (func(loaderExtension)) {
  77607. return;
  77608. }
  77609. }
  77610. defaultFunc();
  77611. };
  77612. return GLTFLoaderExtension;
  77613. }());
  77614. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  77615. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77616. })(BABYLON || (BABYLON = {}));
  77617. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  77618. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77619. var BABYLON;
  77620. (function (BABYLON) {
  77621. var GLTF1;
  77622. (function (GLTF1) {
  77623. var BinaryExtensionBufferName = "binary_glTF";
  77624. ;
  77625. ;
  77626. var GLTFBinaryExtension = /** @class */ (function (_super) {
  77627. __extends(GLTFBinaryExtension, _super);
  77628. function GLTFBinaryExtension() {
  77629. return _super.call(this, "KHR_binary_glTF") || this;
  77630. }
  77631. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77632. var extensionsUsed = data.json.extensionsUsed;
  77633. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  77634. return false;
  77635. }
  77636. this._bin = data.bin;
  77637. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  77638. return true;
  77639. };
  77640. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77641. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  77642. return false;
  77643. }
  77644. if (id !== BinaryExtensionBufferName) {
  77645. return false;
  77646. }
  77647. onSuccess(this._bin);
  77648. return true;
  77649. };
  77650. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77651. var texture = gltfRuntime.textures[id];
  77652. var source = gltfRuntime.images[texture.source];
  77653. if (!source.extensions || !(this.name in source.extensions)) {
  77654. return false;
  77655. }
  77656. var sourceExt = source.extensions[this.name];
  77657. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  77658. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  77659. onSuccess(buffer);
  77660. return true;
  77661. };
  77662. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77663. var shader = gltfRuntime.shaders[id];
  77664. if (!shader.extensions || !(this.name in shader.extensions)) {
  77665. return false;
  77666. }
  77667. var binaryExtensionShader = shader.extensions[this.name];
  77668. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  77669. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  77670. setTimeout(function () {
  77671. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  77672. onSuccess(shaderString);
  77673. });
  77674. return true;
  77675. };
  77676. return GLTFBinaryExtension;
  77677. }(GLTF1.GLTFLoaderExtension));
  77678. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  77679. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  77680. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77681. })(BABYLON || (BABYLON = {}));
  77682. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  77683. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77684. var BABYLON;
  77685. (function (BABYLON) {
  77686. var GLTF1;
  77687. (function (GLTF1) {
  77688. ;
  77689. ;
  77690. ;
  77691. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  77692. __extends(GLTFMaterialsCommonExtension, _super);
  77693. function GLTFMaterialsCommonExtension() {
  77694. return _super.call(this, "KHR_materials_common") || this;
  77695. }
  77696. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77697. if (!gltfRuntime.extensions)
  77698. return false;
  77699. var extension = gltfRuntime.extensions[this.name];
  77700. if (!extension)
  77701. return false;
  77702. // Create lights
  77703. var lights = extension.lights;
  77704. if (lights) {
  77705. for (var thing in lights) {
  77706. var light = lights[thing];
  77707. switch (light.type) {
  77708. case "ambient":
  77709. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  77710. var ambient = light.ambient;
  77711. if (ambient) {
  77712. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  77713. }
  77714. break;
  77715. case "point":
  77716. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  77717. var point = light.point;
  77718. if (point) {
  77719. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  77720. }
  77721. break;
  77722. case "directional":
  77723. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  77724. var directional = light.directional;
  77725. if (directional) {
  77726. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  77727. }
  77728. break;
  77729. case "spot":
  77730. var spot = light.spot;
  77731. if (spot) {
  77732. 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);
  77733. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  77734. }
  77735. break;
  77736. default:
  77737. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  77738. break;
  77739. }
  77740. }
  77741. }
  77742. return false;
  77743. };
  77744. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77745. var material = gltfRuntime.materials[id];
  77746. if (!material || !material.extensions)
  77747. return false;
  77748. var extension = material.extensions[this.name];
  77749. if (!extension)
  77750. return false;
  77751. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  77752. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77753. if (extension.technique === "CONSTANT") {
  77754. standardMaterial.disableLighting = true;
  77755. }
  77756. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  77757. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  77758. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  77759. // Ambient
  77760. if (typeof extension.values.ambient === "string") {
  77761. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  77762. }
  77763. else {
  77764. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  77765. }
  77766. // Diffuse
  77767. if (typeof extension.values.diffuse === "string") {
  77768. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  77769. }
  77770. else {
  77771. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  77772. }
  77773. // Emission
  77774. if (typeof extension.values.emission === "string") {
  77775. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  77776. }
  77777. else {
  77778. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  77779. }
  77780. // Specular
  77781. if (typeof extension.values.specular === "string") {
  77782. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  77783. }
  77784. else {
  77785. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  77786. }
  77787. return true;
  77788. };
  77789. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  77790. // Create buffer from texture url
  77791. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  77792. // Create texture from buffer
  77793. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  77794. }, onError);
  77795. };
  77796. return GLTFMaterialsCommonExtension;
  77797. }(GLTF1.GLTFLoaderExtension));
  77798. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  77799. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  77800. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77801. })(BABYLON || (BABYLON = {}));
  77802. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  77803. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77804. var BABYLON;
  77805. (function (BABYLON) {
  77806. var GLTF2;
  77807. (function (GLTF2) {
  77808. /**
  77809. * Enums
  77810. */
  77811. var EComponentType;
  77812. (function (EComponentType) {
  77813. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  77814. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  77815. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  77816. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  77817. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  77818. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  77819. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  77820. var EMeshPrimitiveMode;
  77821. (function (EMeshPrimitiveMode) {
  77822. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  77823. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  77824. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  77825. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  77826. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  77827. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  77828. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  77829. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  77830. var ETextureMagFilter;
  77831. (function (ETextureMagFilter) {
  77832. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  77833. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  77834. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  77835. var ETextureMinFilter;
  77836. (function (ETextureMinFilter) {
  77837. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  77838. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  77839. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  77840. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  77841. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  77842. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  77843. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  77844. var ETextureWrapMode;
  77845. (function (ETextureWrapMode) {
  77846. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  77847. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  77848. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  77849. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  77850. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  77851. })(BABYLON || (BABYLON = {}));
  77852. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  77853. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77854. var BABYLON;
  77855. (function (BABYLON) {
  77856. var GLTF2;
  77857. (function (GLTF2) {
  77858. var GLTFLoaderTracker = /** @class */ (function () {
  77859. function GLTFLoaderTracker(onComplete) {
  77860. this._pendingCount = 0;
  77861. this._callback = onComplete;
  77862. }
  77863. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  77864. this._pendingCount++;
  77865. };
  77866. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  77867. if (--this._pendingCount === 0) {
  77868. this._callback();
  77869. }
  77870. };
  77871. return GLTFLoaderTracker;
  77872. }());
  77873. var GLTFLoader = /** @class */ (function () {
  77874. function GLTFLoader(parent) {
  77875. this._disposed = false;
  77876. this._renderReady = false;
  77877. this._requests = new Array();
  77878. this._renderReadyObservable = new BABYLON.Observable();
  77879. // Count of pending work that needs to complete before the asset is rendered.
  77880. this._renderPendingCount = 0;
  77881. // Count of pending work that needs to complete before the loader is disposed.
  77882. this._loaderPendingCount = 0;
  77883. this._loaderTrackers = new Array();
  77884. this._parent = parent;
  77885. }
  77886. GLTFLoader.RegisterExtension = function (extension) {
  77887. if (GLTFLoader.Extensions[extension.name]) {
  77888. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  77889. return;
  77890. }
  77891. GLTFLoader.Extensions[extension.name] = extension;
  77892. // Keep the order of registration so that extensions registered first are called first.
  77893. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  77894. };
  77895. GLTFLoader.prototype.dispose = function () {
  77896. if (this._disposed) {
  77897. return;
  77898. }
  77899. this._disposed = true;
  77900. // Abort requests that are not complete
  77901. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  77902. var request = _a[_i];
  77903. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  77904. request.abort();
  77905. }
  77906. }
  77907. // Revoke object urls created during load
  77908. if (this._gltf.textures) {
  77909. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  77910. var texture = _c[_b];
  77911. if (texture.url) {
  77912. URL.revokeObjectURL(texture.url);
  77913. }
  77914. }
  77915. }
  77916. this._gltf = undefined;
  77917. this._babylonScene = undefined;
  77918. this._parent = undefined;
  77919. this._rootUrl = undefined;
  77920. this._defaultMaterial = undefined;
  77921. this._rootNode = undefined;
  77922. this._successCallback = undefined;
  77923. this._progressCallback = undefined;
  77924. this._errorCallback = undefined;
  77925. this._renderReady = false;
  77926. this._requests = undefined;
  77927. this._renderReadyObservable = undefined;
  77928. this._renderPendingCount = 0;
  77929. this._loaderPendingCount = 0;
  77930. this._loaderTrackers = undefined;
  77931. };
  77932. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77933. var _this = this;
  77934. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  77935. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  77936. }, onProgress, onError);
  77937. };
  77938. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77939. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  77940. };
  77941. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77942. var _this = this;
  77943. this._tryCatchOnError(function () {
  77944. _this._loadData(data);
  77945. _this._babylonScene = scene;
  77946. _this._rootUrl = rootUrl;
  77947. _this._successCallback = onSuccess;
  77948. _this._progressCallback = onProgress;
  77949. _this._errorCallback = onError;
  77950. GLTF2.GLTFUtils.AssignIndices(_this._gltf.accessors);
  77951. GLTF2.GLTFUtils.AssignIndices(_this._gltf.animations);
  77952. GLTF2.GLTFUtils.AssignIndices(_this._gltf.buffers);
  77953. GLTF2.GLTFUtils.AssignIndices(_this._gltf.bufferViews);
  77954. GLTF2.GLTFUtils.AssignIndices(_this._gltf.images);
  77955. GLTF2.GLTFUtils.AssignIndices(_this._gltf.materials);
  77956. GLTF2.GLTFUtils.AssignIndices(_this._gltf.meshes);
  77957. GLTF2.GLTFUtils.AssignIndices(_this._gltf.nodes);
  77958. GLTF2.GLTFUtils.AssignIndices(_this._gltf.scenes);
  77959. GLTF2.GLTFUtils.AssignIndices(_this._gltf.skins);
  77960. GLTF2.GLTFUtils.AssignIndices(_this._gltf.textures);
  77961. _this._addPendingData(_this);
  77962. _this._loadDefaultScene(nodeNames);
  77963. _this._loadAnimations();
  77964. _this._removePendingData(_this);
  77965. });
  77966. };
  77967. GLTFLoader.prototype._onError = function (message) {
  77968. if (this._disposed) {
  77969. return;
  77970. }
  77971. BABYLON.Tools.Error("glTF Loader: " + message);
  77972. if (this._errorCallback) {
  77973. this._errorCallback(message);
  77974. }
  77975. this.dispose();
  77976. };
  77977. GLTFLoader.prototype._onProgress = function (event) {
  77978. if (this._disposed) {
  77979. return;
  77980. }
  77981. if (this._progressCallback) {
  77982. this._progressCallback(event);
  77983. }
  77984. };
  77985. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  77986. if (this._renderReady) {
  77987. func();
  77988. }
  77989. else {
  77990. this._renderReadyObservable.add(func);
  77991. }
  77992. };
  77993. GLTFLoader.prototype._onRenderReady = function () {
  77994. if (this._rootNode.babylonMesh) {
  77995. this._rootNode.babylonMesh.setEnabled(true);
  77996. }
  77997. this._startAnimations();
  77998. this._successCallback();
  77999. this._renderReadyObservable.notifyObservers(this);
  78000. };
  78001. GLTFLoader.prototype._onComplete = function () {
  78002. if (this._parent.onComplete) {
  78003. this._parent.onComplete();
  78004. }
  78005. this.dispose();
  78006. };
  78007. GLTFLoader.prototype._loadData = function (data) {
  78008. this._gltf = data.json;
  78009. if (data.bin) {
  78010. var buffers = this._gltf.buffers;
  78011. if (buffers && buffers[0] && !buffers[0].uri) {
  78012. var binaryBuffer = buffers[0];
  78013. if (binaryBuffer.byteLength != data.bin.byteLength) {
  78014. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  78015. }
  78016. binaryBuffer.loadedData = data.bin;
  78017. }
  78018. else {
  78019. BABYLON.Tools.Warn("Unexpected BIN chunk");
  78020. }
  78021. }
  78022. };
  78023. GLTFLoader.prototype._getMeshes = function () {
  78024. var meshes = [this._rootNode.babylonMesh];
  78025. var nodes = this._gltf.nodes;
  78026. if (nodes) {
  78027. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  78028. var node = nodes_1[_i];
  78029. if (node.babylonMesh) {
  78030. meshes.push(node.babylonMesh);
  78031. }
  78032. }
  78033. }
  78034. return meshes;
  78035. };
  78036. GLTFLoader.prototype._getSkeletons = function () {
  78037. var skeletons = new Array();
  78038. var skins = this._gltf.skins;
  78039. if (skins) {
  78040. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  78041. var skin = skins_1[_i];
  78042. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  78043. skeletons.push(skin.babylonSkeleton);
  78044. }
  78045. }
  78046. }
  78047. return skeletons;
  78048. };
  78049. GLTFLoader.prototype._getAnimationTargets = function () {
  78050. var targets = new Array();
  78051. var animations = this._gltf.animations;
  78052. if (animations) {
  78053. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  78054. var animation = animations_1[_i];
  78055. targets.push.apply(targets, animation.targets);
  78056. }
  78057. }
  78058. return targets;
  78059. };
  78060. GLTFLoader.prototype._startAnimations = function () {
  78061. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  78062. var target = _a[_i];
  78063. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  78064. }
  78065. };
  78066. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  78067. var scene = GLTF2.GLTFUtils.GetArrayItem(this._gltf.scenes, this._gltf.scene || 0);
  78068. if (!scene) {
  78069. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  78070. }
  78071. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  78072. };
  78073. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  78074. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  78075. switch (this._parent.coordinateSystemMode) {
  78076. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  78077. if (!this._babylonScene.useRightHandedSystem && this._rootNode.babylonMesh) {
  78078. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  78079. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  78080. }
  78081. break;
  78082. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  78083. // do nothing
  78084. break;
  78085. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  78086. this._babylonScene.useRightHandedSystem = true;
  78087. break;
  78088. default:
  78089. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  78090. return;
  78091. }
  78092. var nodeIndices = scene.nodes;
  78093. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  78094. node.parent = parentNode;
  78095. return true;
  78096. }, this._rootNode);
  78097. if (nodeNames) {
  78098. if (!(nodeNames instanceof Array)) {
  78099. nodeNames = [nodeNames];
  78100. }
  78101. var filteredNodeIndices_1 = new Array();
  78102. this._traverseNodes(context, nodeIndices, function (node) {
  78103. if (nodeNames.indexOf(node.name) !== -1) {
  78104. filteredNodeIndices_1.push(node.index);
  78105. return false;
  78106. }
  78107. return true;
  78108. }, this._rootNode);
  78109. nodeIndices = filteredNodeIndices_1;
  78110. }
  78111. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  78112. var index = nodeIndices_1[_i];
  78113. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  78114. if (!node) {
  78115. throw new Error(context + ": Failed to find node " + index);
  78116. }
  78117. this._loadNode("#/nodes/" + index, node);
  78118. }
  78119. // Disable the root mesh until the asset is ready to render.
  78120. if (this._rootNode.babylonMesh) {
  78121. this._rootNode.babylonMesh.setEnabled(false);
  78122. }
  78123. };
  78124. GLTFLoader.prototype._loadNode = function (context, node) {
  78125. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  78126. return;
  78127. }
  78128. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  78129. this._loadTransform(node);
  78130. if (node.mesh != null) {
  78131. var mesh = GLTF2.GLTFUtils.GetArrayItem(this._gltf.meshes, node.mesh);
  78132. if (!mesh) {
  78133. throw new Error(context + ": Failed to find mesh " + node.mesh);
  78134. }
  78135. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  78136. }
  78137. node.babylonMesh.parent = (node.parent ? node.parent.babylonMesh : null);
  78138. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  78139. node.babylonAnimationTargets.push(node.babylonMesh);
  78140. if (node.skin != null) {
  78141. var skin = GLTF2.GLTFUtils.GetArrayItem(this._gltf.skins, node.skin);
  78142. if (!skin) {
  78143. throw new Error(context + ": Failed to find skin " + node.skin);
  78144. }
  78145. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  78146. }
  78147. if (node.camera != null) {
  78148. // TODO: handle cameras
  78149. }
  78150. if (node.children) {
  78151. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  78152. var index = _a[_i];
  78153. var childNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  78154. if (!childNode) {
  78155. throw new Error(context + ": Failed to find child node " + index);
  78156. }
  78157. this._loadNode("#/nodes/" + index, childNode);
  78158. }
  78159. }
  78160. };
  78161. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  78162. var _this = this;
  78163. if (!node.babylonMesh) {
  78164. return;
  78165. }
  78166. node.babylonMesh.name = node.babylonMesh.name || mesh.name || "";
  78167. var primitives = mesh.primitives;
  78168. if (!primitives || primitives.length === 0) {
  78169. throw new Error(context + ": Primitives are missing");
  78170. }
  78171. this._createMorphTargets(context, node, mesh);
  78172. this._loadAllVertexDataAsync(context, mesh, function () {
  78173. if (!node.babylonMesh) {
  78174. return;
  78175. }
  78176. _this._loadMorphTargets(context, node, mesh);
  78177. var vertexData = new BABYLON.VertexData();
  78178. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  78179. var primitive = primitives_1[_i];
  78180. vertexData.merge(primitive.vertexData);
  78181. }
  78182. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  78183. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  78184. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  78185. node.babylonMesh.subMeshes = [];
  78186. var verticesStart = 0;
  78187. var indicesStart = 0;
  78188. for (var index = 0; index < primitives.length; index++) {
  78189. var vertexData_1 = primitives[index].vertexData;
  78190. var verticesCount = vertexData_1.positions.length;
  78191. var indicesCount = vertexData_1.indices.length;
  78192. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  78193. verticesStart += verticesCount;
  78194. indicesStart += indicesCount;
  78195. }
  78196. ;
  78197. });
  78198. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  78199. node.babylonMesh.material = multiMaterial;
  78200. var subMaterials = multiMaterial.subMaterials;
  78201. var _loop_1 = function (index) {
  78202. var primitive = primitives[index];
  78203. if (primitive.material == null) {
  78204. subMaterials[index] = this_1._getDefaultMaterial();
  78205. }
  78206. else {
  78207. var material_1 = GLTF2.GLTFUtils.GetArrayItem(this_1._gltf.materials, primitive.material);
  78208. if (!material_1) {
  78209. throw new Error(context + ": Failed to find material " + primitive.material);
  78210. }
  78211. this_1._loadMaterial("#/materials/" + material_1.index, material_1, function (babylonMaterial, isNew) {
  78212. if (isNew && _this._parent.onMaterialLoaded) {
  78213. _this._parent.onMaterialLoaded(babylonMaterial);
  78214. }
  78215. if (_this._parent.onBeforeMaterialReadyAsync) {
  78216. _this._addLoaderPendingData(material_1);
  78217. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  78218. _this._tryCatchOnError(function () {
  78219. subMaterials[index] = babylonMaterial;
  78220. _this._removeLoaderPendingData(material_1);
  78221. });
  78222. });
  78223. }
  78224. else {
  78225. subMaterials[index] = babylonMaterial;
  78226. }
  78227. });
  78228. }
  78229. };
  78230. var this_1 = this;
  78231. for (var index = 0; index < primitives.length; index++) {
  78232. _loop_1(index);
  78233. }
  78234. ;
  78235. };
  78236. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  78237. var primitives = mesh.primitives;
  78238. var numRemainingPrimitives = primitives.length;
  78239. var _loop_2 = function (index) {
  78240. var primitive = primitives[index];
  78241. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  78242. primitive.vertexData = vertexData;
  78243. if (--numRemainingPrimitives === 0) {
  78244. onSuccess();
  78245. }
  78246. });
  78247. };
  78248. var this_2 = this;
  78249. for (var index = 0; index < primitives.length; index++) {
  78250. _loop_2(index);
  78251. }
  78252. };
  78253. /**
  78254. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  78255. * @param {ArrayBufferView} data
  78256. * @param {IGLTFAccessor} accessor
  78257. */
  78258. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  78259. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  78260. return data;
  78261. }
  78262. var buffer = data;
  78263. var factor = 1;
  78264. switch (accessor.componentType) {
  78265. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78266. factor = 1 / 255;
  78267. break;
  78268. }
  78269. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78270. factor = 1 / 65535;
  78271. break;
  78272. }
  78273. default: {
  78274. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78275. }
  78276. }
  78277. var result = new Float32Array(accessor.count * 2);
  78278. for (var i = 0; i < result.length; ++i) {
  78279. result[i] = buffer[i] * factor;
  78280. }
  78281. return result;
  78282. };
  78283. /**
  78284. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  78285. * @param {ArrayBufferView} data
  78286. * @param {IGLTFAccessor} accessor
  78287. */
  78288. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  78289. var colorComponentCount = this._getNumComponentsOfType(accessor.type);
  78290. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  78291. return data;
  78292. }
  78293. var buffer = data;
  78294. var factor = 1;
  78295. switch (accessor.componentType) {
  78296. case GLTF2.EComponentType.FLOAT: {
  78297. factor = 1;
  78298. break;
  78299. }
  78300. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78301. factor = 1 / 255;
  78302. break;
  78303. }
  78304. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78305. factor = 1 / 65535;
  78306. break;
  78307. }
  78308. default: {
  78309. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78310. }
  78311. }
  78312. var result = new Float32Array(accessor.count * 4);
  78313. if (colorComponentCount === 4) {
  78314. for (var i = 0; i < result.length; ++i) {
  78315. result[i] = buffer[i] * factor;
  78316. }
  78317. }
  78318. else {
  78319. var offset = 0;
  78320. for (var i = 0; i < result.length; ++i) {
  78321. if ((i + 1) % 4 === 0) {
  78322. result[i] = 1;
  78323. }
  78324. else {
  78325. result[i] = buffer[offset++] * factor;
  78326. }
  78327. }
  78328. }
  78329. return result;
  78330. };
  78331. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  78332. var _this = this;
  78333. var attributes = primitive.attributes;
  78334. if (!attributes) {
  78335. throw new Error(context + ": Attributes are missing");
  78336. }
  78337. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  78338. // TODO: handle other primitive modes
  78339. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  78340. }
  78341. var vertexData = new BABYLON.VertexData();
  78342. var numRemainingAttributes = Object.keys(attributes).length;
  78343. var _loop_3 = function (attribute) {
  78344. var accessor = GLTF2.GLTFUtils.GetArrayItem(this_3._gltf.accessors, attributes[attribute]);
  78345. if (!accessor) {
  78346. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78347. }
  78348. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78349. switch (attribute) {
  78350. case "NORMAL":
  78351. vertexData.normals = data;
  78352. break;
  78353. case "POSITION":
  78354. vertexData.positions = data;
  78355. break;
  78356. case "TANGENT":
  78357. vertexData.tangents = data;
  78358. break;
  78359. case "TEXCOORD_0":
  78360. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  78361. break;
  78362. case "TEXCOORD_1":
  78363. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  78364. break;
  78365. case "JOINTS_0":
  78366. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  78367. break;
  78368. case "WEIGHTS_0":
  78369. //TODO: need to add support for normalized weights.
  78370. vertexData.matricesWeights = data;
  78371. break;
  78372. case "COLOR_0":
  78373. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  78374. break;
  78375. default:
  78376. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78377. break;
  78378. }
  78379. if (--numRemainingAttributes === 0) {
  78380. if (primitive.indices == null) {
  78381. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  78382. for (var i = 0; i < vertexData.indices.length; i++) {
  78383. vertexData.indices[i] = i;
  78384. }
  78385. onSuccess(vertexData);
  78386. }
  78387. else {
  78388. var indicesAccessor = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.accessors, primitive.indices);
  78389. if (!indicesAccessor) {
  78390. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  78391. }
  78392. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  78393. vertexData.indices = data;
  78394. onSuccess(vertexData);
  78395. });
  78396. }
  78397. }
  78398. });
  78399. };
  78400. var this_3 = this;
  78401. for (var attribute in attributes) {
  78402. _loop_3(attribute);
  78403. }
  78404. };
  78405. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  78406. var primitives = mesh.primitives;
  78407. var targets = primitives[0].targets;
  78408. if (!targets || !node.babylonMesh) {
  78409. return;
  78410. }
  78411. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  78412. var primitive = primitives_2[_i];
  78413. if (!primitive.targets || primitive.targets.length != targets.length) {
  78414. throw new Error(context + ": All primitives are required to list the same number of targets");
  78415. }
  78416. }
  78417. var morphTargetManager = new BABYLON.MorphTargetManager();
  78418. node.babylonMesh.morphTargetManager = morphTargetManager;
  78419. for (var index = 0; index < targets.length; index++) {
  78420. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  78421. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  78422. }
  78423. };
  78424. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  78425. if (!node.babylonMesh) {
  78426. return;
  78427. }
  78428. var morphTargetManager = node.babylonMesh.morphTargetManager;
  78429. if (!morphTargetManager) {
  78430. return;
  78431. }
  78432. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  78433. var numTargets = morphTargetManager.numTargets;
  78434. for (var index = 0; index < numTargets; index++) {
  78435. var vertexData = new BABYLON.VertexData();
  78436. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78437. var primitive = _a[_i];
  78438. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  78439. }
  78440. var target = morphTargetManager.getTarget(index);
  78441. target.setNormals(vertexData.normals);
  78442. target.setPositions(vertexData.positions);
  78443. target.setTangents(vertexData.tangents);
  78444. }
  78445. });
  78446. };
  78447. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  78448. if (!node.babylonMesh || !node.babylonMesh.morphTargetManager) {
  78449. return;
  78450. }
  78451. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  78452. var _loop_4 = function (primitive) {
  78453. var targets = primitive.targets;
  78454. if (!targets) {
  78455. return "continue";
  78456. }
  78457. primitive.targetsVertexData = new Array(targets.length);
  78458. var _loop_5 = function (index) {
  78459. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  78460. primitive.targetsVertexData[index] = vertexData;
  78461. if (--numRemainingTargets === 0) {
  78462. onSuccess();
  78463. }
  78464. });
  78465. };
  78466. for (var index = 0; index < targets.length; index++) {
  78467. _loop_5(index);
  78468. }
  78469. };
  78470. var this_4 = this;
  78471. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78472. var primitive = _a[_i];
  78473. _loop_4(primitive);
  78474. }
  78475. };
  78476. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  78477. var targetVertexData = new BABYLON.VertexData();
  78478. var numRemainingAttributes = Object.keys(attributes).length;
  78479. var _loop_6 = function (attribute) {
  78480. var accessor = GLTF2.GLTFUtils.GetArrayItem(this_5._gltf.accessors, attributes[attribute]);
  78481. if (!accessor) {
  78482. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78483. }
  78484. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78485. // glTF stores morph target information as deltas while babylon.js expects the final data.
  78486. // As a result we have to add the original data to the delta to calculate the final data.
  78487. var values = data;
  78488. switch (attribute) {
  78489. case "NORMAL":
  78490. for (var i = 0; i < values.length; i++) {
  78491. values[i] += vertexData.normals[i];
  78492. }
  78493. targetVertexData.normals = values;
  78494. break;
  78495. case "POSITION":
  78496. for (var i = 0; i < values.length; i++) {
  78497. values[i] += vertexData.positions[i];
  78498. }
  78499. targetVertexData.positions = values;
  78500. break;
  78501. case "TANGENT":
  78502. // Tangent data for morph targets is stored as xyz delta.
  78503. // The vertexData.tangent is stored as xyzw.
  78504. // So we need to skip every fourth vertexData.tangent.
  78505. for (var i = 0, j = 0; i < values.length; i++, j++) {
  78506. values[i] += vertexData.tangents[j];
  78507. if ((i + 1) % 3 == 0) {
  78508. j++;
  78509. }
  78510. }
  78511. targetVertexData.tangents = values;
  78512. break;
  78513. default:
  78514. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78515. break;
  78516. }
  78517. if (--numRemainingAttributes === 0) {
  78518. onSuccess(targetVertexData);
  78519. }
  78520. });
  78521. };
  78522. var this_5 = this;
  78523. for (var attribute in attributes) {
  78524. _loop_6(attribute);
  78525. }
  78526. };
  78527. GLTFLoader.prototype._loadTransform = function (node) {
  78528. if (!node.babylonMesh) {
  78529. return;
  78530. }
  78531. var position = BABYLON.Vector3.Zero();
  78532. var rotation = BABYLON.Quaternion.Identity();
  78533. var scaling = BABYLON.Vector3.One();
  78534. if (node.matrix) {
  78535. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  78536. matrix.decompose(scaling, rotation, position);
  78537. }
  78538. else {
  78539. if (node.translation)
  78540. position = BABYLON.Vector3.FromArray(node.translation);
  78541. if (node.rotation)
  78542. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  78543. if (node.scale)
  78544. scaling = BABYLON.Vector3.FromArray(node.scale);
  78545. }
  78546. node.babylonMesh.position = position;
  78547. node.babylonMesh.rotationQuaternion = rotation;
  78548. node.babylonMesh.scaling = scaling;
  78549. };
  78550. GLTFLoader.prototype._loadSkin = function (context, skin) {
  78551. var _this = this;
  78552. var skeletonId = "skeleton" + skin.index;
  78553. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  78554. if (skin.inverseBindMatrices == null) {
  78555. this._loadBones(context, skin, null);
  78556. }
  78557. else {
  78558. var accessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices);
  78559. if (!accessor) {
  78560. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  78561. }
  78562. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78563. _this._loadBones(context, skin, data);
  78564. });
  78565. }
  78566. return skin.babylonSkeleton;
  78567. };
  78568. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  78569. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  78570. node.babylonBones = node.babylonBones || {};
  78571. node.babylonBones[skin.index] = babylonBone;
  78572. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  78573. node.babylonAnimationTargets.push(babylonBone);
  78574. return babylonBone;
  78575. };
  78576. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  78577. var babylonBones = {};
  78578. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  78579. var index = _a[_i];
  78580. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  78581. if (!node) {
  78582. throw new Error(context + ": Failed to find joint " + index);
  78583. }
  78584. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  78585. }
  78586. };
  78587. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  78588. var babylonBone = babylonBones[node.index];
  78589. if (babylonBone) {
  78590. return babylonBone;
  78591. }
  78592. var boneIndex = skin.joints.indexOf(node.index);
  78593. var baseMatrix = BABYLON.Matrix.Identity();
  78594. if (inverseBindMatrixData && boneIndex !== -1) {
  78595. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  78596. baseMatrix.invertToRef(baseMatrix);
  78597. }
  78598. var babylonParentBone = null;
  78599. if (node.index !== skin.skeleton && node.parent !== this._rootNode) {
  78600. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  78601. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  78602. }
  78603. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  78604. babylonBones[node.index] = babylonBone;
  78605. return babylonBone;
  78606. };
  78607. GLTFLoader.prototype._getNodeMatrix = function (node) {
  78608. return node.matrix ?
  78609. BABYLON.Matrix.FromArray(node.matrix) :
  78610. 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());
  78611. };
  78612. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  78613. if (parentNode === void 0) { parentNode = null; }
  78614. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  78615. var index = indices_1[_i];
  78616. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  78617. if (!node) {
  78618. throw new Error(context + ": Failed to find node " + index);
  78619. }
  78620. this._traverseNode(context, node, action, parentNode);
  78621. }
  78622. };
  78623. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  78624. if (parentNode === void 0) { parentNode = null; }
  78625. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  78626. return;
  78627. }
  78628. if (!action(node, parentNode)) {
  78629. return;
  78630. }
  78631. if (node.children) {
  78632. this._traverseNodes(context, node.children, action, node);
  78633. }
  78634. };
  78635. GLTFLoader.prototype._loadAnimations = function () {
  78636. var animations = this._gltf.animations;
  78637. if (!animations) {
  78638. return;
  78639. }
  78640. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  78641. var animation = animations[animationIndex];
  78642. var context = "#/animations/" + animationIndex;
  78643. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  78644. var channel = GLTF2.GLTFUtils.GetArrayItem(animation.channels, channelIndex);
  78645. if (!channel) {
  78646. throw new Error(context + ": Failed to find channel " + channelIndex);
  78647. }
  78648. var sampler = GLTF2.GLTFUtils.GetArrayItem(animation.samplers, channel.sampler);
  78649. if (!sampler) {
  78650. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  78651. }
  78652. this._loadAnimationChannel(animation, context + "/channels/" + channelIndex, channel, context + "/samplers/" + channel.sampler, sampler);
  78653. }
  78654. }
  78655. };
  78656. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  78657. var targetNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node);
  78658. if (!targetNode) {
  78659. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  78660. }
  78661. var targetPath;
  78662. var animationType;
  78663. switch (channel.target.path) {
  78664. case "translation":
  78665. targetPath = "position";
  78666. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  78667. break;
  78668. case "rotation":
  78669. targetPath = "rotationQuaternion";
  78670. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  78671. break;
  78672. case "scale":
  78673. targetPath = "scaling";
  78674. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  78675. break;
  78676. case "weights":
  78677. targetPath = "influence";
  78678. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  78679. break;
  78680. default:
  78681. throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'");
  78682. }
  78683. var inputData;
  78684. var outputData;
  78685. var checkSuccess = function () {
  78686. if (!inputData || !outputData) {
  78687. return;
  78688. }
  78689. var outputBufferOffset = 0;
  78690. var getNextOutputValue;
  78691. switch (targetPath) {
  78692. case "position":
  78693. getNextOutputValue = function () {
  78694. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  78695. outputBufferOffset += 3;
  78696. return value;
  78697. };
  78698. break;
  78699. case "rotationQuaternion":
  78700. getNextOutputValue = function () {
  78701. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  78702. outputBufferOffset += 4;
  78703. return value;
  78704. };
  78705. break;
  78706. case "scaling":
  78707. getNextOutputValue = function () {
  78708. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  78709. outputBufferOffset += 3;
  78710. return value;
  78711. };
  78712. break;
  78713. case "influence":
  78714. getNextOutputValue = function () {
  78715. if (!targetNode.babylonMesh || !targetNode.babylonMesh.morphTargetManager) {
  78716. return BABYLON.Vector3.Zero();
  78717. }
  78718. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  78719. var value = new Array(numTargets);
  78720. for (var i = 0; i < numTargets; i++) {
  78721. value[i] = outputData[outputBufferOffset++];
  78722. }
  78723. return value;
  78724. };
  78725. break;
  78726. }
  78727. var getNextKey;
  78728. switch (sampler.interpolation) {
  78729. case "LINEAR":
  78730. getNextKey = function (frameIndex) { return ({
  78731. frame: inputData[frameIndex],
  78732. value: getNextOutputValue()
  78733. }); };
  78734. break;
  78735. case "CUBICSPLINE":
  78736. getNextKey = function (frameIndex) { return ({
  78737. frame: inputData[frameIndex],
  78738. inTangent: getNextOutputValue(),
  78739. value: getNextOutputValue(),
  78740. outTangent: getNextOutputValue()
  78741. }); };
  78742. break;
  78743. default:
  78744. throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'");
  78745. }
  78746. ;
  78747. var keys = new Array(inputData.length);
  78748. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  78749. keys[frameIndex] = getNextKey(frameIndex);
  78750. }
  78751. animation.targets = animation.targets || [];
  78752. if (targetPath === "influence" && targetNode.babylonMesh && targetNode.babylonMesh.morphTargetManager) {
  78753. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  78754. var _loop_7 = function (targetIndex) {
  78755. var morphTarget = morphTargetManager.getTarget(targetIndex);
  78756. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  78757. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  78758. babylonAnimation.setKeys(keys.map(function (key) { return ({
  78759. frame: key.frame,
  78760. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  78761. value: key.value[targetIndex],
  78762. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  78763. }); }));
  78764. morphTarget.animations.push(babylonAnimation);
  78765. animation.targets.push(morphTarget);
  78766. };
  78767. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  78768. _loop_7(targetIndex);
  78769. }
  78770. }
  78771. else if (targetNode.babylonAnimationTargets) {
  78772. var animationName = animation.name || "anim" + animation.index;
  78773. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  78774. babylonAnimation.setKeys(keys);
  78775. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  78776. var target = _a[_i];
  78777. target.animations.push(babylonAnimation.clone());
  78778. animation.targets.push(target);
  78779. }
  78780. }
  78781. };
  78782. var inputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input);
  78783. if (!inputAccessor) {
  78784. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  78785. }
  78786. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  78787. inputData = data;
  78788. checkSuccess();
  78789. });
  78790. var outputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output);
  78791. if (!outputAccessor) {
  78792. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  78793. }
  78794. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  78795. outputData = data;
  78796. checkSuccess();
  78797. });
  78798. };
  78799. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  78800. var _this = this;
  78801. this._addPendingData(buffer);
  78802. if (buffer.loadedData) {
  78803. onSuccess(buffer.loadedData);
  78804. this._removePendingData(buffer);
  78805. }
  78806. else if (buffer.loadedObservable) {
  78807. buffer.loadedObservable.add(function (buffer) {
  78808. onSuccess(buffer.loadedData);
  78809. _this._removePendingData(buffer);
  78810. });
  78811. }
  78812. else {
  78813. if (!buffer.uri) {
  78814. throw new Error(context + ": Uri is missing");
  78815. }
  78816. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  78817. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  78818. buffer.loadedData = new Uint8Array(data);
  78819. onSuccess(buffer.loadedData);
  78820. this._removePendingData(buffer);
  78821. }
  78822. else {
  78823. buffer.loadedObservable = new BABYLON.Observable();
  78824. buffer.loadedObservable.add(function (buffer) {
  78825. onSuccess(buffer.loadedData);
  78826. _this._removePendingData(buffer);
  78827. });
  78828. this._loadUri(context, buffer.uri, function (data) {
  78829. buffer.loadedData = data;
  78830. if (buffer.loadedObservable) {
  78831. buffer.loadedObservable.notifyObservers(buffer);
  78832. buffer.loadedObservable = undefined;
  78833. }
  78834. });
  78835. }
  78836. }
  78837. };
  78838. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  78839. var _this = this;
  78840. var buffer = GLTF2.GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer);
  78841. if (!buffer) {
  78842. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  78843. }
  78844. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  78845. if (_this._disposed || !bufferData) {
  78846. return;
  78847. }
  78848. var data;
  78849. try {
  78850. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  78851. }
  78852. catch (e) {
  78853. throw new Error(context + ": " + e.message);
  78854. }
  78855. onSuccess(data);
  78856. });
  78857. };
  78858. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  78859. var _this = this;
  78860. if (accessor.sparse) {
  78861. throw new Error(context + ": Sparse accessors are not currently supported");
  78862. }
  78863. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView);
  78864. if (!bufferView) {
  78865. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  78866. }
  78867. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  78868. var numComponents = _this._getNumComponentsOfType(accessor.type);
  78869. if (numComponents === 0) {
  78870. throw new Error(context + ": Invalid type (" + accessor.type + ")");
  78871. }
  78872. var data;
  78873. var byteOffset = accessor.byteOffset;
  78874. var byteStride = bufferView.byteStride;
  78875. try {
  78876. switch (accessor.componentType) {
  78877. case GLTF2.EComponentType.BYTE:
  78878. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78879. break;
  78880. case GLTF2.EComponentType.UNSIGNED_BYTE:
  78881. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78882. break;
  78883. case GLTF2.EComponentType.SHORT:
  78884. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78885. break;
  78886. case GLTF2.EComponentType.UNSIGNED_SHORT:
  78887. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78888. break;
  78889. case GLTF2.EComponentType.UNSIGNED_INT:
  78890. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78891. break;
  78892. case GLTF2.EComponentType.FLOAT:
  78893. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78894. break;
  78895. default:
  78896. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78897. }
  78898. }
  78899. catch (e) {
  78900. throw new Error(context + ": " + e);
  78901. }
  78902. onSuccess(data);
  78903. });
  78904. };
  78905. GLTFLoader.prototype._getNumComponentsOfType = function (type) {
  78906. switch (type) {
  78907. case "SCALAR": return 1;
  78908. case "VEC2": return 2;
  78909. case "VEC3": return 3;
  78910. case "VEC4": return 4;
  78911. case "MAT2": return 4;
  78912. case "MAT3": return 9;
  78913. case "MAT4": return 16;
  78914. }
  78915. return 0;
  78916. };
  78917. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  78918. byteOffset = data.byteOffset + (byteOffset || 0);
  78919. var targetLength = count * numComponents;
  78920. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  78921. return new typedArray(data.buffer, byteOffset, targetLength);
  78922. }
  78923. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  78924. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  78925. var targetBuffer = new typedArray(targetLength);
  78926. var sourceIndex = 0;
  78927. var targetIndex = 0;
  78928. while (targetIndex < targetLength) {
  78929. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  78930. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  78931. targetIndex++;
  78932. }
  78933. sourceIndex += elementStride;
  78934. }
  78935. return targetBuffer;
  78936. };
  78937. GLTFLoader.prototype._addPendingData = function (data) {
  78938. if (!this._renderReady) {
  78939. this._renderPendingCount++;
  78940. }
  78941. this._addLoaderPendingData(data);
  78942. };
  78943. GLTFLoader.prototype._removePendingData = function (data) {
  78944. if (!this._renderReady) {
  78945. if (--this._renderPendingCount === 0) {
  78946. this._renderReady = true;
  78947. this._onRenderReady();
  78948. }
  78949. }
  78950. this._removeLoaderPendingData(data);
  78951. };
  78952. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  78953. this._loaderPendingCount++;
  78954. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  78955. var tracker = _a[_i];
  78956. tracker._addPendingData(data);
  78957. }
  78958. };
  78959. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  78960. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  78961. var tracker = _a[_i];
  78962. tracker._removePendingData(data);
  78963. }
  78964. if (--this._loaderPendingCount === 0) {
  78965. this._onComplete();
  78966. }
  78967. };
  78968. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  78969. var _this = this;
  78970. var tracker = new GLTFLoaderTracker(function () {
  78971. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  78972. onComplete();
  78973. });
  78974. this._loaderTrackers.push(tracker);
  78975. this._addLoaderPendingData(tracker);
  78976. action();
  78977. this._removeLoaderPendingData(tracker);
  78978. };
  78979. GLTFLoader.prototype._getDefaultMaterial = function () {
  78980. if (!this._defaultMaterial) {
  78981. var id = "__gltf_default";
  78982. var material = this._babylonScene.getMaterialByName(id);
  78983. if (!material) {
  78984. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  78985. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78986. material.metallic = 1;
  78987. material.roughness = 1;
  78988. }
  78989. this._defaultMaterial = material;
  78990. }
  78991. return this._defaultMaterial;
  78992. };
  78993. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  78994. var babylonMaterial = material.babylonMaterial;
  78995. // Ensure metallic workflow
  78996. babylonMaterial.metallic = 1;
  78997. babylonMaterial.roughness = 1;
  78998. var properties = material.pbrMetallicRoughness;
  78999. if (!properties) {
  79000. return;
  79001. }
  79002. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  79003. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  79004. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  79005. if (properties.baseColorTexture) {
  79006. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index);
  79007. if (!texture) {
  79008. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  79009. }
  79010. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  79011. }
  79012. if (properties.metallicRoughnessTexture) {
  79013. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index);
  79014. if (!texture) {
  79015. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  79016. }
  79017. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  79018. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  79019. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  79020. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  79021. }
  79022. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  79023. };
  79024. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  79025. if (material.babylonMaterial) {
  79026. assign(material.babylonMaterial, false);
  79027. return;
  79028. }
  79029. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  79030. return;
  79031. }
  79032. this._createPbrMaterial(material);
  79033. this._loadMaterialBaseProperties(context, material);
  79034. this._loadMaterialMetallicRoughnessProperties(context, material);
  79035. if (material.babylonMaterial) {
  79036. assign(material.babylonMaterial, true);
  79037. }
  79038. };
  79039. GLTFLoader.prototype._createPbrMaterial = function (material) {
  79040. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  79041. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79042. material.babylonMaterial = babylonMaterial;
  79043. };
  79044. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  79045. var babylonMaterial = material.babylonMaterial;
  79046. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  79047. if (material.doubleSided) {
  79048. babylonMaterial.backFaceCulling = false;
  79049. babylonMaterial.twoSidedLighting = true;
  79050. }
  79051. if (material.normalTexture) {
  79052. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index);
  79053. if (!texture) {
  79054. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  79055. }
  79056. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  79057. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  79058. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  79059. if (material.normalTexture.scale != null) {
  79060. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  79061. }
  79062. }
  79063. if (material.occlusionTexture) {
  79064. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index);
  79065. if (!texture) {
  79066. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  79067. }
  79068. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  79069. babylonMaterial.useAmbientInGrayScale = true;
  79070. if (material.occlusionTexture.strength != null) {
  79071. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  79072. }
  79073. }
  79074. if (material.emissiveTexture) {
  79075. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index);
  79076. if (!texture) {
  79077. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  79078. }
  79079. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  79080. }
  79081. };
  79082. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  79083. var babylonMaterial = material.babylonMaterial;
  79084. var alphaMode = material.alphaMode || "OPAQUE";
  79085. switch (alphaMode) {
  79086. case "OPAQUE":
  79087. // default is opaque
  79088. break;
  79089. case "MASK":
  79090. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  79091. if (colorFactor) {
  79092. if (colorFactor[3] == 0) {
  79093. babylonMaterial.alphaCutOff = 1;
  79094. }
  79095. else {
  79096. babylonMaterial.alphaCutOff /= colorFactor[3];
  79097. }
  79098. }
  79099. if (babylonMaterial.albedoTexture) {
  79100. babylonMaterial.albedoTexture.hasAlpha = true;
  79101. }
  79102. break;
  79103. case "BLEND":
  79104. if (colorFactor) {
  79105. babylonMaterial.alpha = colorFactor[3];
  79106. }
  79107. if (babylonMaterial.albedoTexture) {
  79108. babylonMaterial.albedoTexture.hasAlpha = true;
  79109. babylonMaterial.useAlphaFromAlbedoTexture = true;
  79110. }
  79111. break;
  79112. default:
  79113. throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'");
  79114. }
  79115. };
  79116. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  79117. var _this = this;
  79118. if (coordinatesIndex === void 0) { coordinatesIndex = 0; }
  79119. var sampler = (texture.sampler == null ? {} : GLTF2.GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler));
  79120. if (!sampler) {
  79121. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  79122. }
  79123. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  79124. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  79125. this._addPendingData(texture);
  79126. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  79127. _this._tryCatchOnError(function () {
  79128. _this._removePendingData(texture);
  79129. });
  79130. }, function (message) {
  79131. _this._tryCatchOnError(function () {
  79132. throw new Error(context + ": " + message);
  79133. });
  79134. });
  79135. if (texture.url) {
  79136. babylonTexture.updateURL(texture.url);
  79137. }
  79138. else if (texture.dataReadyObservable) {
  79139. texture.dataReadyObservable.add(function (texture) {
  79140. babylonTexture.updateURL(texture.url);
  79141. });
  79142. }
  79143. else {
  79144. texture.dataReadyObservable = new BABYLON.Observable();
  79145. texture.dataReadyObservable.add(function (texture) {
  79146. babylonTexture.updateURL(texture.url);
  79147. });
  79148. var image_1 = GLTF2.GLTFUtils.GetArrayItem(this._gltf.images, texture.source);
  79149. if (!image_1) {
  79150. throw new Error(context + ": Failed to find source " + texture.source);
  79151. }
  79152. this._loadImage("#/images/" + image_1.index, image_1, function (data) {
  79153. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  79154. if (texture.dataReadyObservable) {
  79155. texture.dataReadyObservable.notifyObservers(texture);
  79156. }
  79157. });
  79158. }
  79159. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  79160. if (sampler.wrapS !== undefined) {
  79161. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  79162. }
  79163. if (sampler.wrapT !== undefined) {
  79164. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  79165. }
  79166. babylonTexture.name = texture.name || "texture" + texture.index;
  79167. if (this._parent.onTextureLoaded) {
  79168. this._parent.onTextureLoaded(babylonTexture);
  79169. }
  79170. return babylonTexture;
  79171. };
  79172. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  79173. if (image.uri) {
  79174. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  79175. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  79176. }
  79177. else {
  79178. this._loadUri(context, image.uri, onSuccess);
  79179. }
  79180. }
  79181. else {
  79182. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView);
  79183. if (!bufferView) {
  79184. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  79185. }
  79186. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  79187. }
  79188. };
  79189. GLTFLoader.prototype._loadUri = function (context, uri, onSuccess) {
  79190. var _this = this;
  79191. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  79192. throw new Error(context + ": Uri '" + uri + "' is invalid");
  79193. }
  79194. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  79195. _this._tryCatchOnError(function () {
  79196. onSuccess(new Uint8Array(data));
  79197. });
  79198. }, function (event) {
  79199. _this._tryCatchOnError(function () {
  79200. _this._onProgress(event);
  79201. });
  79202. }, this._babylonScene.database, true, function (request) {
  79203. _this._tryCatchOnError(function () {
  79204. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  79205. });
  79206. });
  79207. if (request) {
  79208. this._requests.push(request);
  79209. }
  79210. };
  79211. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  79212. try {
  79213. handler();
  79214. }
  79215. catch (e) {
  79216. this._onError(e.message);
  79217. }
  79218. };
  79219. GLTFLoader.Extensions = {};
  79220. return GLTFLoader;
  79221. }());
  79222. GLTF2.GLTFLoader = GLTFLoader;
  79223. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  79224. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79225. })(BABYLON || (BABYLON = {}));
  79226. //# sourceMappingURL=babylon.glTFLoader.js.map
  79227. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79228. var BABYLON;
  79229. (function (BABYLON) {
  79230. var GLTF2;
  79231. (function (GLTF2) {
  79232. /**
  79233. * Utils functions for GLTF
  79234. */
  79235. var GLTFUtils = /** @class */ (function () {
  79236. function GLTFUtils() {
  79237. }
  79238. /**
  79239. * If the uri is a base64 string
  79240. * @param uri: the uri to test
  79241. */
  79242. GLTFUtils.IsBase64 = function (uri) {
  79243. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  79244. };
  79245. /**
  79246. * Decode the base64 uri
  79247. * @param uri: the uri to decode
  79248. */
  79249. GLTFUtils.DecodeBase64 = function (uri) {
  79250. var decodedString = atob(uri.split(",")[1]);
  79251. var bufferLength = decodedString.length;
  79252. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  79253. for (var i = 0; i < bufferLength; i++) {
  79254. bufferView[i] = decodedString.charCodeAt(i);
  79255. }
  79256. return bufferView.buffer;
  79257. };
  79258. GLTFUtils.ValidateUri = function (uri) {
  79259. return (uri.indexOf("..") === -1);
  79260. };
  79261. GLTFUtils.AssignIndices = function (array) {
  79262. if (array) {
  79263. for (var index = 0; index < array.length; index++) {
  79264. array[index].index = index;
  79265. }
  79266. }
  79267. };
  79268. GLTFUtils.GetArrayItem = function (array, index) {
  79269. if (!array || !array[index]) {
  79270. return null;
  79271. }
  79272. return array[index];
  79273. };
  79274. GLTFUtils.GetTextureWrapMode = function (mode) {
  79275. // Set defaults if undefined
  79276. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  79277. switch (mode) {
  79278. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  79279. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  79280. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  79281. default:
  79282. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  79283. return BABYLON.Texture.WRAP_ADDRESSMODE;
  79284. }
  79285. };
  79286. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  79287. // Set defaults if undefined
  79288. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  79289. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  79290. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  79291. switch (minFilter) {
  79292. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  79293. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  79294. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  79295. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  79296. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  79297. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79298. default:
  79299. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79300. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79301. }
  79302. }
  79303. else {
  79304. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  79305. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  79306. }
  79307. switch (minFilter) {
  79308. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  79309. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  79310. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79311. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  79312. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  79313. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  79314. default:
  79315. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79316. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79317. }
  79318. }
  79319. };
  79320. return GLTFUtils;
  79321. }());
  79322. GLTF2.GLTFUtils = GLTFUtils;
  79323. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79324. })(BABYLON || (BABYLON = {}));
  79325. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  79326. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79327. var BABYLON;
  79328. (function (BABYLON) {
  79329. var GLTF2;
  79330. (function (GLTF2) {
  79331. var GLTFLoaderExtension = /** @class */ (function () {
  79332. function GLTFLoaderExtension() {
  79333. this.enabled = true;
  79334. }
  79335. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  79336. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  79337. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  79338. GLTFLoaderExtension.prototype._loadExtension = function (property, action) {
  79339. var _this = this;
  79340. if (!property.extensions) {
  79341. return false;
  79342. }
  79343. var extension = property.extensions[this.name];
  79344. if (!extension) {
  79345. return false;
  79346. }
  79347. // Clear out the extension before executing the action to avoid recursing into the same property.
  79348. property.extensions[this.name] = undefined;
  79349. action(extension, function () {
  79350. // Restore the extension after completing the action.
  79351. if (property.extensions) {
  79352. property.extensions[_this.name] = extension;
  79353. }
  79354. });
  79355. return true;
  79356. };
  79357. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  79358. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  79359. };
  79360. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  79361. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  79362. };
  79363. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  79364. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  79365. };
  79366. GLTFLoaderExtension._ApplyExtensions = function (action) {
  79367. var extensions = GLTFLoaderExtension._Extensions;
  79368. if (!extensions) {
  79369. return false;
  79370. }
  79371. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  79372. var extension = extensions_1[_i];
  79373. if (extension.enabled && action(extension)) {
  79374. return true;
  79375. }
  79376. }
  79377. return false;
  79378. };
  79379. //
  79380. // Utilities
  79381. //
  79382. GLTFLoaderExtension._Extensions = [];
  79383. return GLTFLoaderExtension;
  79384. }());
  79385. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  79386. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79387. })(BABYLON || (BABYLON = {}));
  79388. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  79389. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  79390. var BABYLON;
  79391. (function (BABYLON) {
  79392. var GLTF2;
  79393. (function (GLTF2) {
  79394. var Extensions;
  79395. (function (Extensions) {
  79396. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  79397. var MSFTLOD = /** @class */ (function (_super) {
  79398. __extends(MSFTLOD, _super);
  79399. function MSFTLOD() {
  79400. return _super !== null && _super.apply(this, arguments) || this;
  79401. }
  79402. Object.defineProperty(MSFTLOD.prototype, "name", {
  79403. get: function () {
  79404. return "MSFT_lod";
  79405. },
  79406. enumerable: true,
  79407. configurable: true
  79408. });
  79409. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  79410. return this._loadExtension(node, function (extension, onComplete) {
  79411. if (!loader._gltf.nodes) {
  79412. return;
  79413. }
  79414. for (var i = extension.ids.length - 1; i >= 0; i--) {
  79415. var lodNode = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.nodes, extension.ids[i]);
  79416. if (!lodNode) {
  79417. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  79418. }
  79419. loader._traverseNode(context, lodNode, action, parentNode);
  79420. }
  79421. loader._traverseNode(context, node, action, parentNode);
  79422. onComplete();
  79423. });
  79424. };
  79425. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  79426. var _this = this;
  79427. return this._loadExtension(node, function (extension, onComplete) {
  79428. var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; });
  79429. loader._addLoaderPendingData(node);
  79430. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  79431. loader._removeLoaderPendingData(node);
  79432. onComplete();
  79433. });
  79434. });
  79435. };
  79436. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  79437. var _this = this;
  79438. loader._whenAction(function () {
  79439. loader._loadNode(context, nodes[index]);
  79440. }, function () {
  79441. if (index !== nodes.length - 1) {
  79442. var previousNode = nodes[index + 1];
  79443. if (previousNode.babylonMesh) {
  79444. previousNode.babylonMesh.setEnabled(false);
  79445. }
  79446. }
  79447. if (index === 0) {
  79448. onComplete();
  79449. return;
  79450. }
  79451. setTimeout(function () {
  79452. loader._tryCatchOnError(function () {
  79453. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  79454. });
  79455. }, MSFTLOD.MinimalLODDelay);
  79456. });
  79457. };
  79458. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  79459. var _this = this;
  79460. return this._loadExtension(material, function (extension, onComplete) {
  79461. var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; });
  79462. loader._addLoaderPendingData(material);
  79463. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  79464. if (material.extensions) {
  79465. material.extensions[_this.name] = extension;
  79466. }
  79467. loader._removeLoaderPendingData(material);
  79468. onComplete();
  79469. });
  79470. });
  79471. };
  79472. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  79473. var _this = this;
  79474. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  79475. assign(babylonMaterial, isNew);
  79476. if (index === 0) {
  79477. onComplete();
  79478. return;
  79479. }
  79480. // Load the next LOD when the loader is ready to render and
  79481. // all active material textures of the current LOD are loaded.
  79482. loader._executeWhenRenderReady(function () {
  79483. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  79484. setTimeout(function () {
  79485. loader._tryCatchOnError(function () {
  79486. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  79487. });
  79488. }, MSFTLOD.MinimalLODDelay);
  79489. });
  79490. });
  79491. });
  79492. };
  79493. /**
  79494. * Specify the minimal delay between LODs in ms (default = 250)
  79495. */
  79496. MSFTLOD.MinimalLODDelay = 250;
  79497. return MSFTLOD;
  79498. }(GLTF2.GLTFLoaderExtension));
  79499. Extensions.MSFTLOD = MSFTLOD;
  79500. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  79501. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  79502. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79503. })(BABYLON || (BABYLON = {}));
  79504. //# sourceMappingURL=MSFT_lod.js.map
  79505. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  79506. var BABYLON;
  79507. (function (BABYLON) {
  79508. var GLTF2;
  79509. (function (GLTF2) {
  79510. var Extensions;
  79511. (function (Extensions) {
  79512. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  79513. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  79514. function KHRMaterialsPbrSpecularGlossiness() {
  79515. return _super !== null && _super.apply(this, arguments) || this;
  79516. }
  79517. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  79518. get: function () {
  79519. return "KHR_materials_pbrSpecularGlossiness";
  79520. },
  79521. enumerable: true,
  79522. configurable: true
  79523. });
  79524. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  79525. var _this = this;
  79526. return this._loadExtension(material, function (extension, onComplete) {
  79527. loader._createPbrMaterial(material);
  79528. loader._loadMaterialBaseProperties(context, material);
  79529. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  79530. if (material.babylonMaterial) {
  79531. assign(material.babylonMaterial, true);
  79532. }
  79533. });
  79534. };
  79535. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  79536. var babylonMaterial = material.babylonMaterial;
  79537. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  79538. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  79539. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  79540. if (loader._gltf.textures) {
  79541. if (properties.diffuseTexture) {
  79542. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.diffuseTexture.index);
  79543. if (!texture) {
  79544. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  79545. }
  79546. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  79547. }
  79548. if (properties.specularGlossinessTexture) {
  79549. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.specularGlossinessTexture.index);
  79550. if (!texture) {
  79551. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  79552. }
  79553. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  79554. babylonMaterial.reflectivityTexture.hasAlpha = true;
  79555. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  79556. }
  79557. }
  79558. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  79559. };
  79560. return KHRMaterialsPbrSpecularGlossiness;
  79561. }(GLTF2.GLTFLoaderExtension));
  79562. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  79563. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  79564. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  79565. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79566. })(BABYLON || (BABYLON = {}));
  79567. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  79568. (function universalModuleDefinition(root, factory) {
  79569. if (root && root["BABYLON"]) {
  79570. return;
  79571. }
  79572. if(typeof exports === 'object' && typeof module === 'object')
  79573. module.exports = factory();
  79574. else if(typeof define === 'function' && define.amd)
  79575. define([], factory);
  79576. else if(typeof exports === 'object')
  79577. exports["BABYLON"] = factory();
  79578. else {
  79579. root["BABYLON"] = factory();
  79580. }
  79581. })(this, function() {
  79582. return BABYLON;
  79583. });