babylon.max.js 3.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. var absX = Math.abs(this.x);
  1403. var absY = Math.abs(this.y);
  1404. if (absX !== absY) {
  1405. return true;
  1406. }
  1407. var absZ = Math.abs(this.z);
  1408. if (absX !== absZ) {
  1409. return true;
  1410. }
  1411. if (absY !== absZ) {
  1412. return true;
  1413. }
  1414. return false;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. // Properties
  1420. /**
  1421. * Returns the length of the Vector3 (float).
  1422. */
  1423. Vector3.prototype.length = function () {
  1424. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1425. };
  1426. /**
  1427. * Returns the squared length of the Vector3 (float).
  1428. */
  1429. Vector3.prototype.lengthSquared = function () {
  1430. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1431. };
  1432. // Methods
  1433. /**
  1434. * Normalize the current Vector3.
  1435. * Returns the updated Vector3.
  1436. */
  1437. Vector3.prototype.normalize = function () {
  1438. var len = this.length();
  1439. if (len === 0 || len === 1.0)
  1440. return this;
  1441. var num = 1.0 / len;
  1442. this.x *= num;
  1443. this.y *= num;
  1444. this.z *= num;
  1445. return this;
  1446. };
  1447. /**
  1448. * Returns a new Vector3 copied from the current Vector3.
  1449. */
  1450. Vector3.prototype.clone = function () {
  1451. return new Vector3(this.x, this.y, this.z);
  1452. };
  1453. /**
  1454. * Copies the passed vector coordinates to the current Vector3 ones.
  1455. * Returns the updated Vector3.
  1456. */
  1457. Vector3.prototype.copyFrom = function (source) {
  1458. this.x = source.x;
  1459. this.y = source.y;
  1460. this.z = source.z;
  1461. return this;
  1462. };
  1463. /**
  1464. * Copies the passed floats to the current Vector3 coordinates.
  1465. * Returns the updated Vector3.
  1466. */
  1467. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1468. this.x = x;
  1469. this.y = y;
  1470. this.z = z;
  1471. return this;
  1472. };
  1473. /**
  1474. * Copies the passed floats to the current Vector3 coordinates.
  1475. * Returns the updated Vector3.
  1476. */
  1477. Vector3.prototype.set = function (x, y, z) {
  1478. return this.copyFromFloats(x, y, z);
  1479. };
  1480. // Statics
  1481. /**
  1482. *
  1483. */
  1484. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1485. var d0 = Vector3.Dot(vector0, axis) - size;
  1486. var d1 = Vector3.Dot(vector1, axis) - size;
  1487. var s = d0 / (d0 - d1);
  1488. return s;
  1489. };
  1490. /**
  1491. * Returns a new Vector3 set from the index "offset" of the passed array.
  1492. */
  1493. Vector3.FromArray = function (array, offset) {
  1494. if (!offset) {
  1495. offset = 0;
  1496. }
  1497. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1498. };
  1499. /**
  1500. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1501. * This function is deprecated. Use FromArray instead.
  1502. */
  1503. Vector3.FromFloatArray = function (array, offset) {
  1504. return Vector3.FromArray(array, offset);
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1508. */
  1509. Vector3.FromArrayToRef = function (array, offset, result) {
  1510. result.x = array[offset];
  1511. result.y = array[offset + 1];
  1512. result.z = array[offset + 2];
  1513. };
  1514. /**
  1515. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1516. * This function is deprecated. Use FromArrayToRef instead.
  1517. */
  1518. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1519. return Vector3.FromArrayToRef(array, offset, result);
  1520. };
  1521. /**
  1522. * Sets the passed vector "result" with the passed floats.
  1523. */
  1524. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1525. result.x = x;
  1526. result.y = y;
  1527. result.z = z;
  1528. };
  1529. /**
  1530. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1531. */
  1532. Vector3.Zero = function () {
  1533. return new Vector3(0.0, 0.0, 0.0);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1537. */
  1538. Vector3.One = function () {
  1539. return new Vector3(1.0, 1.0, 1.0);
  1540. };
  1541. /**
  1542. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1543. */
  1544. Vector3.Up = function () {
  1545. return new Vector3(0.0, 1.0, 0.0);
  1546. };
  1547. /**
  1548. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1549. */
  1550. Vector3.Forward = function () {
  1551. return new Vector3(0.0, 0.0, 1.0);
  1552. };
  1553. /**
  1554. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1555. */
  1556. Vector3.Right = function () {
  1557. return new Vector3(1.0, 0.0, 0.0);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1561. */
  1562. Vector3.Left = function () {
  1563. return new Vector3(-1.0, 0.0, 0.0);
  1564. };
  1565. /**
  1566. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1567. * This method computes tranformed coordinates only, not transformed direction vectors.
  1568. */
  1569. Vector3.TransformCoordinates = function (vector, transformation) {
  1570. var result = Vector3.Zero();
  1571. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1572. return result;
  1573. };
  1574. /**
  1575. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1576. * This method computes tranformed coordinates only, not transformed direction vectors.
  1577. */
  1578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1583. result.x = x / w;
  1584. result.y = y / w;
  1585. result.z = z / w;
  1586. };
  1587. /**
  1588. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1589. * This method computes tranformed coordinates only, not transformed direction vectors.
  1590. */
  1591. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1592. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1593. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1594. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1595. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1596. result.x = rx / rw;
  1597. result.y = ry / rw;
  1598. result.z = rz / rw;
  1599. };
  1600. /**
  1601. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1602. * This methods computes transformed normalized direction vectors only.
  1603. */
  1604. Vector3.TransformNormal = function (vector, transformation) {
  1605. var result = Vector3.Zero();
  1606. Vector3.TransformNormalToRef(vector, transformation, result);
  1607. return result;
  1608. };
  1609. /**
  1610. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1611. * This methods computes transformed normalized direction vectors only.
  1612. */
  1613. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1614. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1615. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1616. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1617. result.x = x;
  1618. result.y = y;
  1619. result.z = z;
  1620. };
  1621. /**
  1622. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1623. * This methods computes transformed normalized direction vectors only.
  1624. */
  1625. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1626. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1627. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1628. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1629. };
  1630. /**
  1631. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1632. */
  1633. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1634. var squared = amount * amount;
  1635. var cubed = amount * squared;
  1636. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1637. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1638. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1639. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1640. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1641. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1642. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1643. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1644. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1645. return new Vector3(x, y, z);
  1646. };
  1647. /**
  1648. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1649. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1650. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1651. */
  1652. Vector3.Clamp = function (value, min, max) {
  1653. var x = value.x;
  1654. x = (x > max.x) ? max.x : x;
  1655. x = (x < min.x) ? min.x : x;
  1656. var y = value.y;
  1657. y = (y > max.y) ? max.y : y;
  1658. y = (y < min.y) ? min.y : y;
  1659. var z = value.z;
  1660. z = (z > max.z) ? max.z : z;
  1661. z = (z < min.z) ? min.z : z;
  1662. return new Vector3(x, y, z);
  1663. };
  1664. /**
  1665. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1666. */
  1667. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1668. var squared = amount * amount;
  1669. var cubed = amount * squared;
  1670. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1671. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1672. var part3 = (cubed - (2.0 * squared)) + amount;
  1673. var part4 = cubed - squared;
  1674. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1675. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1676. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1677. return new Vector3(x, y, z);
  1678. };
  1679. /**
  1680. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1681. */
  1682. Vector3.Lerp = function (start, end, amount) {
  1683. var result = new Vector3(0, 0, 0);
  1684. Vector3.LerpToRef(start, end, amount, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1689. */
  1690. Vector3.LerpToRef = function (start, end, amount, result) {
  1691. result.x = start.x + ((end.x - start.x) * amount);
  1692. result.y = start.y + ((end.y - start.y) * amount);
  1693. result.z = start.z + ((end.z - start.z) * amount);
  1694. };
  1695. /**
  1696. * Returns the dot product (float) between the vectors "left" and "right".
  1697. */
  1698. Vector3.Dot = function (left, right) {
  1699. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1700. };
  1701. /**
  1702. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1703. * The cross product is then orthogonal to both "left" and "right".
  1704. */
  1705. Vector3.Cross = function (left, right) {
  1706. var result = Vector3.Zero();
  1707. Vector3.CrossToRef(left, right, result);
  1708. return result;
  1709. };
  1710. /**
  1711. * Sets the passed vector "result" with the cross product of "left" and "right".
  1712. * The cross product is then orthogonal to both "left" and "right".
  1713. */
  1714. Vector3.CrossToRef = function (left, right, result) {
  1715. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1716. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1717. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1718. result.copyFrom(MathTmp.Vector3[0]);
  1719. };
  1720. /**
  1721. * Returns a new Vector3 as the normalization of the passed vector.
  1722. */
  1723. Vector3.Normalize = function (vector) {
  1724. var result = Vector3.Zero();
  1725. Vector3.NormalizeToRef(vector, result);
  1726. return result;
  1727. };
  1728. /**
  1729. * Sets the passed vector "result" with the normalization of the passed first vector.
  1730. */
  1731. Vector3.NormalizeToRef = function (vector, result) {
  1732. result.copyFrom(vector);
  1733. result.normalize();
  1734. };
  1735. Vector3.Project = function (vector, world, transform, viewport) {
  1736. var cw = viewport.width;
  1737. var ch = viewport.height;
  1738. var cx = viewport.x;
  1739. var cy = viewport.y;
  1740. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1741. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1742. var matrix = MathTmp.Matrix[0];
  1743. world.multiplyToRef(transform, matrix);
  1744. matrix.multiplyToRef(viewportMatrix, matrix);
  1745. return Vector3.TransformCoordinates(vector, matrix);
  1746. };
  1747. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1748. var matrix = MathTmp.Matrix[0];
  1749. world.multiplyToRef(transform, matrix);
  1750. matrix.invert();
  1751. source.x = source.x / viewportWidth * 2 - 1;
  1752. source.y = -(source.y / viewportHeight * 2 - 1);
  1753. var vector = Vector3.TransformCoordinates(source, matrix);
  1754. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1755. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1756. vector = vector.scale(1.0 / num);
  1757. }
  1758. return vector;
  1759. };
  1760. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1761. var matrix = MathTmp.Matrix[0];
  1762. world.multiplyToRef(view, matrix);
  1763. matrix.multiplyToRef(projection, matrix);
  1764. matrix.invert();
  1765. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1766. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1767. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1768. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1769. vector = vector.scale(1.0 / num);
  1770. }
  1771. return vector;
  1772. };
  1773. Vector3.Minimize = function (left, right) {
  1774. var min = left.clone();
  1775. min.MinimizeInPlace(right);
  1776. return min;
  1777. };
  1778. Vector3.Maximize = function (left, right) {
  1779. var max = left.clone();
  1780. max.MaximizeInPlace(right);
  1781. return max;
  1782. };
  1783. /**
  1784. * Returns the distance (float) between the vectors "value1" and "value2".
  1785. */
  1786. Vector3.Distance = function (value1, value2) {
  1787. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1788. };
  1789. /**
  1790. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1791. */
  1792. Vector3.DistanceSquared = function (value1, value2) {
  1793. var x = value1.x - value2.x;
  1794. var y = value1.y - value2.y;
  1795. var z = value1.z - value2.z;
  1796. return (x * x) + (y * y) + (z * z);
  1797. };
  1798. /**
  1799. * Returns a new Vector3 located at the center between "value1" and "value2".
  1800. */
  1801. Vector3.Center = function (value1, value2) {
  1802. var center = value1.add(value2);
  1803. center.scaleInPlace(0.5);
  1804. return center;
  1805. };
  1806. /**
  1807. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1808. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1809. * to something in order to rotate it from its local system to the given target system.
  1810. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1811. * Returns a new Vector3.
  1812. */
  1813. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1814. var rotation = Vector3.Zero();
  1815. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1816. return rotation;
  1817. };
  1818. /**
  1819. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1820. */
  1821. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1822. var quat = MathTmp.Quaternion[0];
  1823. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1824. quat.toEulerAnglesToRef(ref);
  1825. };
  1826. return Vector3;
  1827. }());
  1828. BABYLON.Vector3 = Vector3;
  1829. //Vector4 class created for EulerAngle class conversion to Quaternion
  1830. var Vector4 = /** @class */ (function () {
  1831. /**
  1832. * Creates a Vector4 object from the passed floats.
  1833. */
  1834. function Vector4(x, y, z, w) {
  1835. this.x = x;
  1836. this.y = y;
  1837. this.z = z;
  1838. this.w = w;
  1839. }
  1840. /**
  1841. * Returns the string with the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.toString = function () {
  1844. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1845. };
  1846. /**
  1847. * Returns the string "Vector4".
  1848. */
  1849. Vector4.prototype.getClassName = function () {
  1850. return "Vector4";
  1851. };
  1852. /**
  1853. * Returns the Vector4 hash code.
  1854. */
  1855. Vector4.prototype.getHashCode = function () {
  1856. var hash = this.x || 0;
  1857. hash = (hash * 397) ^ (this.y || 0);
  1858. hash = (hash * 397) ^ (this.z || 0);
  1859. hash = (hash * 397) ^ (this.w || 0);
  1860. return hash;
  1861. };
  1862. // Operators
  1863. /**
  1864. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1865. */
  1866. Vector4.prototype.asArray = function () {
  1867. var result = new Array();
  1868. this.toArray(result, 0);
  1869. return result;
  1870. };
  1871. /**
  1872. * Populates the passed array from the passed index with the Vector4 coordinates.
  1873. * Returns the Vector4.
  1874. */
  1875. Vector4.prototype.toArray = function (array, index) {
  1876. if (index === undefined) {
  1877. index = 0;
  1878. }
  1879. array[index] = this.x;
  1880. array[index + 1] = this.y;
  1881. array[index + 2] = this.z;
  1882. array[index + 3] = this.w;
  1883. return this;
  1884. };
  1885. /**
  1886. * Adds the passed vector to the current Vector4.
  1887. * Returns the updated Vector4.
  1888. */
  1889. Vector4.prototype.addInPlace = function (otherVector) {
  1890. this.x += otherVector.x;
  1891. this.y += otherVector.y;
  1892. this.z += otherVector.z;
  1893. this.w += otherVector.w;
  1894. return this;
  1895. };
  1896. /**
  1897. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1898. */
  1899. Vector4.prototype.add = function (otherVector) {
  1900. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1901. };
  1902. /**
  1903. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1904. * Returns the current Vector4.
  1905. */
  1906. Vector4.prototype.addToRef = function (otherVector, result) {
  1907. result.x = this.x + otherVector.x;
  1908. result.y = this.y + otherVector.y;
  1909. result.z = this.z + otherVector.z;
  1910. result.w = this.w + otherVector.w;
  1911. return this;
  1912. };
  1913. /**
  1914. * Subtract in place the passed vector from the current Vector4.
  1915. * Returns the updated Vector4.
  1916. */
  1917. Vector4.prototype.subtractInPlace = function (otherVector) {
  1918. this.x -= otherVector.x;
  1919. this.y -= otherVector.y;
  1920. this.z -= otherVector.z;
  1921. this.w -= otherVector.w;
  1922. return this;
  1923. };
  1924. /**
  1925. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1926. */
  1927. Vector4.prototype.subtract = function (otherVector) {
  1928. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1929. };
  1930. /**
  1931. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1932. * Returns the current Vector4.
  1933. */
  1934. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1935. result.x = this.x - otherVector.x;
  1936. result.y = this.y - otherVector.y;
  1937. result.z = this.z - otherVector.z;
  1938. result.w = this.w - otherVector.w;
  1939. return this;
  1940. };
  1941. /**
  1942. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1943. */
  1944. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1945. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1946. };
  1947. /**
  1948. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1949. * Returns the current Vector4.
  1950. */
  1951. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1952. result.x = this.x - x;
  1953. result.y = this.y - y;
  1954. result.z = this.z - z;
  1955. result.w = this.w - w;
  1956. return this;
  1957. };
  1958. /**
  1959. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1960. */
  1961. Vector4.prototype.negate = function () {
  1962. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1963. };
  1964. /**
  1965. * Multiplies the current Vector4 coordinates by scale (float).
  1966. * Returns the updated Vector4.
  1967. */
  1968. Vector4.prototype.scaleInPlace = function (scale) {
  1969. this.x *= scale;
  1970. this.y *= scale;
  1971. this.z *= scale;
  1972. this.w *= scale;
  1973. return this;
  1974. };
  1975. /**
  1976. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1977. */
  1978. Vector4.prototype.scale = function (scale) {
  1979. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1980. };
  1981. /**
  1982. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1983. * Returns the current Vector4.
  1984. */
  1985. Vector4.prototype.scaleToRef = function (scale, result) {
  1986. result.x = this.x * scale;
  1987. result.y = this.y * scale;
  1988. result.z = this.z * scale;
  1989. result.w = this.w * scale;
  1990. return this;
  1991. };
  1992. /**
  1993. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1994. */
  1995. Vector4.prototype.equals = function (otherVector) {
  1996. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1997. };
  1998. /**
  1999. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2000. */
  2001. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2002. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2003. return otherVector
  2004. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2005. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2006. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2007. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2008. };
  2009. /**
  2010. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2011. */
  2012. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2013. return this.x === x && this.y === y && this.z === z && this.w === w;
  2014. };
  2015. /**
  2016. * Multiplies in place the current Vector4 by the passed one.
  2017. * Returns the updated Vector4.
  2018. */
  2019. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2020. this.x *= otherVector.x;
  2021. this.y *= otherVector.y;
  2022. this.z *= otherVector.z;
  2023. this.w *= otherVector.w;
  2024. return this;
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2028. */
  2029. Vector4.prototype.multiply = function (otherVector) {
  2030. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2037. result.x = this.x * otherVector.x;
  2038. result.y = this.y * otherVector.y;
  2039. result.z = this.z * otherVector.z;
  2040. result.w = this.w * otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2045. */
  2046. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2047. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2048. };
  2049. /**
  2050. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2051. */
  2052. Vector4.prototype.divide = function (otherVector) {
  2053. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2054. };
  2055. /**
  2056. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2057. * Returns the current Vector4.
  2058. */
  2059. Vector4.prototype.divideToRef = function (otherVector, result) {
  2060. result.x = this.x / otherVector.x;
  2061. result.y = this.y / otherVector.y;
  2062. result.z = this.z / otherVector.z;
  2063. result.w = this.w / otherVector.w;
  2064. return this;
  2065. };
  2066. /**
  2067. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2068. */
  2069. Vector4.prototype.MinimizeInPlace = function (other) {
  2070. if (other.x < this.x)
  2071. this.x = other.x;
  2072. if (other.y < this.y)
  2073. this.y = other.y;
  2074. if (other.z < this.z)
  2075. this.z = other.z;
  2076. if (other.w < this.w)
  2077. this.w = other.w;
  2078. return this;
  2079. };
  2080. /**
  2081. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2082. */
  2083. Vector4.prototype.MaximizeInPlace = function (other) {
  2084. if (other.x > this.x)
  2085. this.x = other.x;
  2086. if (other.y > this.y)
  2087. this.y = other.y;
  2088. if (other.z > this.z)
  2089. this.z = other.z;
  2090. if (other.w > this.w)
  2091. this.w = other.w;
  2092. return this;
  2093. };
  2094. // Properties
  2095. /**
  2096. * Returns the Vector4 length (float).
  2097. */
  2098. Vector4.prototype.length = function () {
  2099. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2100. };
  2101. /**
  2102. * Returns the Vector4 squared length (float).
  2103. */
  2104. Vector4.prototype.lengthSquared = function () {
  2105. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2106. };
  2107. // Methods
  2108. /**
  2109. * Normalizes in place the Vector4.
  2110. * Returns the updated Vector4.
  2111. */
  2112. Vector4.prototype.normalize = function () {
  2113. var len = this.length();
  2114. if (len === 0)
  2115. return this;
  2116. var num = 1.0 / len;
  2117. this.x *= num;
  2118. this.y *= num;
  2119. this.z *= num;
  2120. this.w *= num;
  2121. return this;
  2122. };
  2123. /**
  2124. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2125. */
  2126. Vector4.prototype.toVector3 = function () {
  2127. return new Vector3(this.x, this.y, this.z);
  2128. };
  2129. /**
  2130. * Returns a new Vector4 copied from the current one.
  2131. */
  2132. Vector4.prototype.clone = function () {
  2133. return new Vector4(this.x, this.y, this.z, this.w);
  2134. };
  2135. /**
  2136. * Updates the current Vector4 with the passed one coordinates.
  2137. * Returns the updated Vector4.
  2138. */
  2139. Vector4.prototype.copyFrom = function (source) {
  2140. this.x = source.x;
  2141. this.y = source.y;
  2142. this.z = source.z;
  2143. this.w = source.w;
  2144. return this;
  2145. };
  2146. /**
  2147. * Updates the current Vector4 coordinates with the passed floats.
  2148. * Returns the updated Vector4.
  2149. */
  2150. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2151. this.x = x;
  2152. this.y = y;
  2153. this.z = z;
  2154. this.w = w;
  2155. return this;
  2156. };
  2157. /**
  2158. * Updates the current Vector4 coordinates with the passed floats.
  2159. * Returns the updated Vector4.
  2160. */
  2161. Vector4.prototype.set = function (x, y, z, w) {
  2162. return this.copyFromFloats(x, y, z, w);
  2163. };
  2164. // Statics
  2165. /**
  2166. * Returns a new Vector4 set from the starting index of the passed array.
  2167. */
  2168. Vector4.FromArray = function (array, offset) {
  2169. if (!offset) {
  2170. offset = 0;
  2171. }
  2172. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2173. };
  2174. /**
  2175. * Updates the passed vector "result" from the starting index of the passed array.
  2176. */
  2177. Vector4.FromArrayToRef = function (array, offset, result) {
  2178. result.x = array[offset];
  2179. result.y = array[offset + 1];
  2180. result.z = array[offset + 2];
  2181. result.w = array[offset + 3];
  2182. };
  2183. /**
  2184. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2185. */
  2186. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2187. Vector4.FromArrayToRef(array, offset, result);
  2188. };
  2189. /**
  2190. * Updates the passed vector "result" coordinates from the passed floats.
  2191. */
  2192. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2193. result.x = x;
  2194. result.y = y;
  2195. result.z = z;
  2196. result.w = w;
  2197. };
  2198. /**
  2199. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2200. */
  2201. Vector4.Zero = function () {
  2202. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2203. };
  2204. /**
  2205. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2206. */
  2207. Vector4.One = function () {
  2208. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2209. };
  2210. /**
  2211. * Returns a new normalized Vector4 from the passed one.
  2212. */
  2213. Vector4.Normalize = function (vector) {
  2214. var result = Vector4.Zero();
  2215. Vector4.NormalizeToRef(vector, result);
  2216. return result;
  2217. };
  2218. /**
  2219. * Updates the passed vector "result" from the normalization of the passed one.
  2220. */
  2221. Vector4.NormalizeToRef = function (vector, result) {
  2222. result.copyFrom(vector);
  2223. result.normalize();
  2224. };
  2225. Vector4.Minimize = function (left, right) {
  2226. var min = left.clone();
  2227. min.MinimizeInPlace(right);
  2228. return min;
  2229. };
  2230. Vector4.Maximize = function (left, right) {
  2231. var max = left.clone();
  2232. max.MaximizeInPlace(right);
  2233. return max;
  2234. };
  2235. /**
  2236. * Returns the distance (float) between the vectors "value1" and "value2".
  2237. */
  2238. Vector4.Distance = function (value1, value2) {
  2239. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2240. };
  2241. /**
  2242. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2243. */
  2244. Vector4.DistanceSquared = function (value1, value2) {
  2245. var x = value1.x - value2.x;
  2246. var y = value1.y - value2.y;
  2247. var z = value1.z - value2.z;
  2248. var w = value1.w - value2.w;
  2249. return (x * x) + (y * y) + (z * z) + (w * w);
  2250. };
  2251. /**
  2252. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2253. */
  2254. Vector4.Center = function (value1, value2) {
  2255. var center = value1.add(value2);
  2256. center.scaleInPlace(0.5);
  2257. return center;
  2258. };
  2259. /**
  2260. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2261. * This methods computes transformed normalized direction vectors only.
  2262. */
  2263. Vector4.TransformNormal = function (vector, transformation) {
  2264. var result = Vector4.Zero();
  2265. Vector4.TransformNormalToRef(vector, transformation, result);
  2266. return result;
  2267. };
  2268. /**
  2269. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2270. * This methods computes transformed normalized direction vectors only.
  2271. */
  2272. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2273. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2274. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2275. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2276. result.x = x;
  2277. result.y = y;
  2278. result.z = z;
  2279. result.w = vector.w;
  2280. };
  2281. /**
  2282. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2283. * This methods computes transformed normalized direction vectors only.
  2284. */
  2285. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2286. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2287. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2288. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2289. result.w = w;
  2290. };
  2291. return Vector4;
  2292. }());
  2293. BABYLON.Vector4 = Vector4;
  2294. var Size = /** @class */ (function () {
  2295. /**
  2296. * Creates a Size object from the passed width and height (floats).
  2297. */
  2298. function Size(width, height) {
  2299. this.width = width;
  2300. this.height = height;
  2301. }
  2302. // Returns a string with the Size width and height.
  2303. Size.prototype.toString = function () {
  2304. return "{W: " + this.width + ", H: " + this.height + "}";
  2305. };
  2306. /**
  2307. * Returns the string "Size"
  2308. */
  2309. Size.prototype.getClassName = function () {
  2310. return "Size";
  2311. };
  2312. /**
  2313. * Returns the Size hash code.
  2314. */
  2315. Size.prototype.getHashCode = function () {
  2316. var hash = this.width || 0;
  2317. hash = (hash * 397) ^ (this.height || 0);
  2318. return hash;
  2319. };
  2320. /**
  2321. * Updates the current size from the passed one.
  2322. * Returns the updated Size.
  2323. */
  2324. Size.prototype.copyFrom = function (src) {
  2325. this.width = src.width;
  2326. this.height = src.height;
  2327. };
  2328. /**
  2329. * Updates in place the current Size from the passed floats.
  2330. * Returns the updated Size.
  2331. */
  2332. Size.prototype.copyFromFloats = function (width, height) {
  2333. this.width = width;
  2334. this.height = height;
  2335. return this;
  2336. };
  2337. /**
  2338. * Updates in place the current Size from the passed floats.
  2339. * Returns the updated Size.
  2340. */
  2341. Size.prototype.set = function (width, height) {
  2342. return this.copyFromFloats(width, height);
  2343. };
  2344. /**
  2345. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2346. */
  2347. Size.prototype.multiplyByFloats = function (w, h) {
  2348. return new Size(this.width * w, this.height * h);
  2349. };
  2350. /**
  2351. * Returns a new Size copied from the passed one.
  2352. */
  2353. Size.prototype.clone = function () {
  2354. return new Size(this.width, this.height);
  2355. };
  2356. /**
  2357. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2358. */
  2359. Size.prototype.equals = function (other) {
  2360. if (!other) {
  2361. return false;
  2362. }
  2363. return (this.width === other.width) && (this.height === other.height);
  2364. };
  2365. Object.defineProperty(Size.prototype, "surface", {
  2366. /**
  2367. * Returns the surface of the Size : width * height (float).
  2368. */
  2369. get: function () {
  2370. return this.width * this.height;
  2371. },
  2372. enumerable: true,
  2373. configurable: true
  2374. });
  2375. /**
  2376. * Returns a new Size set to (0.0, 0.0)
  2377. */
  2378. Size.Zero = function () {
  2379. return new Size(0.0, 0.0);
  2380. };
  2381. /**
  2382. * Returns a new Size set as the addition result of the current Size and the passed one.
  2383. */
  2384. Size.prototype.add = function (otherSize) {
  2385. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2386. return r;
  2387. };
  2388. /**
  2389. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2390. */
  2391. Size.prototype.subtract = function (otherSize) {
  2392. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2393. return r;
  2394. };
  2395. /**
  2396. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2397. */
  2398. Size.Lerp = function (start, end, amount) {
  2399. var w = start.width + ((end.width - start.width) * amount);
  2400. var h = start.height + ((end.height - start.height) * amount);
  2401. return new Size(w, h);
  2402. };
  2403. return Size;
  2404. }());
  2405. BABYLON.Size = Size;
  2406. var Quaternion = /** @class */ (function () {
  2407. /**
  2408. * Creates a new Quaternion from the passed floats.
  2409. */
  2410. function Quaternion(x, y, z, w) {
  2411. if (x === void 0) { x = 0.0; }
  2412. if (y === void 0) { y = 0.0; }
  2413. if (z === void 0) { z = 0.0; }
  2414. if (w === void 0) { w = 1.0; }
  2415. this.x = x;
  2416. this.y = y;
  2417. this.z = z;
  2418. this.w = w;
  2419. }
  2420. /**
  2421. * Returns a string with the Quaternion coordinates.
  2422. */
  2423. Quaternion.prototype.toString = function () {
  2424. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2425. };
  2426. /**
  2427. * Returns the string "Quaternion".
  2428. */
  2429. Quaternion.prototype.getClassName = function () {
  2430. return "Quaternion";
  2431. };
  2432. /**
  2433. * Returns the Quaternion hash code.
  2434. */
  2435. Quaternion.prototype.getHashCode = function () {
  2436. var hash = this.x || 0;
  2437. hash = (hash * 397) ^ (this.y || 0);
  2438. hash = (hash * 397) ^ (this.z || 0);
  2439. hash = (hash * 397) ^ (this.w || 0);
  2440. return hash;
  2441. };
  2442. /**
  2443. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2444. */
  2445. Quaternion.prototype.asArray = function () {
  2446. return [this.x, this.y, this.z, this.w];
  2447. };
  2448. /**
  2449. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2450. */
  2451. Quaternion.prototype.equals = function (otherQuaternion) {
  2452. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2453. };
  2454. /**
  2455. * Returns a new Quaternion copied from the current one.
  2456. */
  2457. Quaternion.prototype.clone = function () {
  2458. return new Quaternion(this.x, this.y, this.z, this.w);
  2459. };
  2460. /**
  2461. * Updates the current Quaternion from the passed one coordinates.
  2462. * Returns the updated Quaterion.
  2463. */
  2464. Quaternion.prototype.copyFrom = function (other) {
  2465. this.x = other.x;
  2466. this.y = other.y;
  2467. this.z = other.z;
  2468. this.w = other.w;
  2469. return this;
  2470. };
  2471. /**
  2472. * Updates the current Quaternion from the passed float coordinates.
  2473. * Returns the updated Quaterion.
  2474. */
  2475. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2476. this.x = x;
  2477. this.y = y;
  2478. this.z = z;
  2479. this.w = w;
  2480. return this;
  2481. };
  2482. /**
  2483. * Updates the current Quaternion from the passed float coordinates.
  2484. * Returns the updated Quaterion.
  2485. */
  2486. Quaternion.prototype.set = function (x, y, z, w) {
  2487. return this.copyFromFloats(x, y, z, w);
  2488. };
  2489. /**
  2490. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2491. */
  2492. Quaternion.prototype.add = function (other) {
  2493. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2494. };
  2495. /**
  2496. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2497. */
  2498. Quaternion.prototype.subtract = function (other) {
  2499. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2500. };
  2501. /**
  2502. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2503. */
  2504. Quaternion.prototype.scale = function (value) {
  2505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2506. };
  2507. /**
  2508. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2509. */
  2510. Quaternion.prototype.multiply = function (q1) {
  2511. var result = new Quaternion(0, 0, 0, 1.0);
  2512. this.multiplyToRef(q1, result);
  2513. return result;
  2514. };
  2515. /**
  2516. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2517. * Returns the current Quaternion.
  2518. */
  2519. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2520. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2521. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2522. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2523. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2524. result.copyFromFloats(x, y, z, w);
  2525. return this;
  2526. };
  2527. /**
  2528. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2529. * Returns the updated Quaternion.
  2530. */
  2531. Quaternion.prototype.multiplyInPlace = function (q1) {
  2532. this.multiplyToRef(q1, this);
  2533. return this;
  2534. };
  2535. /**
  2536. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2537. * Returns the current Quaternion.
  2538. */
  2539. Quaternion.prototype.conjugateToRef = function (ref) {
  2540. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2541. return this;
  2542. };
  2543. /**
  2544. * Conjugates in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.conjugateInPlace = function () {
  2548. this.x *= -1;
  2549. this.y *= -1;
  2550. this.z *= -1;
  2551. return this;
  2552. };
  2553. /**
  2554. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2555. */
  2556. Quaternion.prototype.conjugate = function () {
  2557. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2558. return result;
  2559. };
  2560. /**
  2561. * Returns the Quaternion length (float).
  2562. */
  2563. Quaternion.prototype.length = function () {
  2564. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2565. };
  2566. /**
  2567. * Normalize in place the current Quaternion.
  2568. * Returns the updated Quaternion.
  2569. */
  2570. Quaternion.prototype.normalize = function () {
  2571. var length = 1.0 / this.length();
  2572. this.x *= length;
  2573. this.y *= length;
  2574. this.z *= length;
  2575. this.w *= length;
  2576. return this;
  2577. };
  2578. /**
  2579. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2580. */
  2581. Quaternion.prototype.toEulerAngles = function (order) {
  2582. if (order === void 0) { order = "YZX"; }
  2583. var result = Vector3.Zero();
  2584. this.toEulerAnglesToRef(result, order);
  2585. return result;
  2586. };
  2587. /**
  2588. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2589. * Returns the current Quaternion.
  2590. */
  2591. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2592. if (order === void 0) { order = "YZX"; }
  2593. var qz = this.z;
  2594. var qx = this.x;
  2595. var qy = this.y;
  2596. var qw = this.w;
  2597. var sqw = qw * qw;
  2598. var sqz = qz * qz;
  2599. var sqx = qx * qx;
  2600. var sqy = qy * qy;
  2601. var zAxisY = qy * qz - qx * qw;
  2602. var limit = .4999999;
  2603. if (zAxisY < -limit) {
  2604. result.y = 2 * Math.atan2(qy, qw);
  2605. result.x = Math.PI / 2;
  2606. result.z = 0;
  2607. }
  2608. else if (zAxisY > limit) {
  2609. result.y = 2 * Math.atan2(qy, qw);
  2610. result.x = -Math.PI / 2;
  2611. result.z = 0;
  2612. }
  2613. else {
  2614. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2615. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2616. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2617. }
  2618. return this;
  2619. };
  2620. /**
  2621. * Updates the passed rotation matrix with the current Quaternion values.
  2622. * Returns the current Quaternion.
  2623. */
  2624. Quaternion.prototype.toRotationMatrix = function (result) {
  2625. var xx = this.x * this.x;
  2626. var yy = this.y * this.y;
  2627. var zz = this.z * this.z;
  2628. var xy = this.x * this.y;
  2629. var zw = this.z * this.w;
  2630. var zx = this.z * this.x;
  2631. var yw = this.y * this.w;
  2632. var yz = this.y * this.z;
  2633. var xw = this.x * this.w;
  2634. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2635. result.m[1] = 2.0 * (xy + zw);
  2636. result.m[2] = 2.0 * (zx - yw);
  2637. result.m[3] = 0;
  2638. result.m[4] = 2.0 * (xy - zw);
  2639. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2640. result.m[6] = 2.0 * (yz + xw);
  2641. result.m[7] = 0;
  2642. result.m[8] = 2.0 * (zx + yw);
  2643. result.m[9] = 2.0 * (yz - xw);
  2644. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2645. result.m[11] = 0;
  2646. result.m[12] = 0;
  2647. result.m[13] = 0;
  2648. result.m[14] = 0;
  2649. result.m[15] = 1.0;
  2650. result._markAsUpdated();
  2651. return this;
  2652. };
  2653. /**
  2654. * Updates the current Quaternion from the passed rotation matrix values.
  2655. * Returns the updated Quaternion.
  2656. */
  2657. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2658. Quaternion.FromRotationMatrixToRef(matrix, this);
  2659. return this;
  2660. };
  2661. // Statics
  2662. /**
  2663. * Returns a new Quaternion set from the passed rotation matrix values.
  2664. */
  2665. Quaternion.FromRotationMatrix = function (matrix) {
  2666. var result = new Quaternion();
  2667. Quaternion.FromRotationMatrixToRef(matrix, result);
  2668. return result;
  2669. };
  2670. /**
  2671. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2672. */
  2673. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2674. var data = matrix.m;
  2675. var m11 = data[0], m12 = data[4], m13 = data[8];
  2676. var m21 = data[1], m22 = data[5], m23 = data[9];
  2677. var m31 = data[2], m32 = data[6], m33 = data[10];
  2678. var trace = m11 + m22 + m33;
  2679. var s;
  2680. if (trace > 0) {
  2681. s = 0.5 / Math.sqrt(trace + 1.0);
  2682. result.w = 0.25 / s;
  2683. result.x = (m32 - m23) * s;
  2684. result.y = (m13 - m31) * s;
  2685. result.z = (m21 - m12) * s;
  2686. }
  2687. else if (m11 > m22 && m11 > m33) {
  2688. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2689. result.w = (m32 - m23) / s;
  2690. result.x = 0.25 * s;
  2691. result.y = (m12 + m21) / s;
  2692. result.z = (m13 + m31) / s;
  2693. }
  2694. else if (m22 > m33) {
  2695. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2696. result.w = (m13 - m31) / s;
  2697. result.x = (m12 + m21) / s;
  2698. result.y = 0.25 * s;
  2699. result.z = (m23 + m32) / s;
  2700. }
  2701. else {
  2702. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2703. result.w = (m21 - m12) / s;
  2704. result.x = (m13 + m31) / s;
  2705. result.y = (m23 + m32) / s;
  2706. result.z = 0.25 * s;
  2707. }
  2708. };
  2709. /**
  2710. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2711. */
  2712. Quaternion.Zero = function () {
  2713. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2714. };
  2715. /**
  2716. * Returns a new Quaternion as the inverted current Quaternion.
  2717. */
  2718. Quaternion.Inverse = function (q) {
  2719. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2720. };
  2721. /**
  2722. * Returns the identity Quaternion.
  2723. */
  2724. Quaternion.Identity = function () {
  2725. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2726. };
  2727. Quaternion.IsIdentity = function (quaternion) {
  2728. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2729. };
  2730. /**
  2731. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2732. */
  2733. Quaternion.RotationAxis = function (axis, angle) {
  2734. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2735. };
  2736. /**
  2737. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2738. */
  2739. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2740. var sin = Math.sin(angle / 2);
  2741. axis.normalize();
  2742. result.w = Math.cos(angle / 2);
  2743. result.x = axis.x * sin;
  2744. result.y = axis.y * sin;
  2745. result.z = axis.z * sin;
  2746. return result;
  2747. };
  2748. /**
  2749. * Retuns a new Quaternion set from the starting index of the passed array.
  2750. */
  2751. Quaternion.FromArray = function (array, offset) {
  2752. if (!offset) {
  2753. offset = 0;
  2754. }
  2755. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2756. };
  2757. /**
  2758. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2759. */
  2760. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2761. var q = new Quaternion();
  2762. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2763. return q;
  2764. };
  2765. /**
  2766. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2767. */
  2768. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2769. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2770. var halfRoll = roll * 0.5;
  2771. var halfPitch = pitch * 0.5;
  2772. var halfYaw = yaw * 0.5;
  2773. var sinRoll = Math.sin(halfRoll);
  2774. var cosRoll = Math.cos(halfRoll);
  2775. var sinPitch = Math.sin(halfPitch);
  2776. var cosPitch = Math.cos(halfPitch);
  2777. var sinYaw = Math.sin(halfYaw);
  2778. var cosYaw = Math.cos(halfYaw);
  2779. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2780. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2781. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2782. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2783. };
  2784. /**
  2785. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2786. */
  2787. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2788. var result = new Quaternion();
  2789. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2790. return result;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2794. */
  2795. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2796. // Produces a quaternion from Euler angles in the z-x-z orientation
  2797. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2798. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2799. var halfBeta = beta * 0.5;
  2800. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2801. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2802. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2803. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2804. };
  2805. /**
  2806. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2807. * cf to Vector3.RotationFromAxis() documentation.
  2808. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2809. */
  2810. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2811. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2812. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2813. return quat;
  2814. };
  2815. /**
  2816. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2817. * cf to Vector3.RotationFromAxis() documentation.
  2818. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2819. */
  2820. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2821. var rotMat = MathTmp.Matrix[0];
  2822. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2823. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2824. };
  2825. Quaternion.Slerp = function (left, right, amount) {
  2826. var result = Quaternion.Identity();
  2827. Quaternion.SlerpToRef(left, right, amount, result);
  2828. return result;
  2829. };
  2830. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2831. var num2;
  2832. var num3;
  2833. var num = amount;
  2834. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2835. var flag = false;
  2836. if (num4 < 0) {
  2837. flag = true;
  2838. num4 = -num4;
  2839. }
  2840. if (num4 > 0.999999) {
  2841. num3 = 1 - num;
  2842. num2 = flag ? -num : num;
  2843. }
  2844. else {
  2845. var num5 = Math.acos(num4);
  2846. var num6 = (1.0 / Math.sin(num5));
  2847. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2848. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2849. }
  2850. result.x = (num3 * left.x) + (num2 * right.x);
  2851. result.y = (num3 * left.y) + (num2 * right.y);
  2852. result.z = (num3 * left.z) + (num2 * right.z);
  2853. result.w = (num3 * left.w) + (num2 * right.w);
  2854. };
  2855. /**
  2856. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2857. */
  2858. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2859. var squared = amount * amount;
  2860. var cubed = amount * squared;
  2861. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2862. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2863. var part3 = (cubed - (2.0 * squared)) + amount;
  2864. var part4 = cubed - squared;
  2865. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2866. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2867. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2868. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2869. return new Quaternion(x, y, z, w);
  2870. };
  2871. return Quaternion;
  2872. }());
  2873. BABYLON.Quaternion = Quaternion;
  2874. var Matrix = /** @class */ (function () {
  2875. function Matrix() {
  2876. this._isIdentity = false;
  2877. this._isIdentityDirty = true;
  2878. this.m = new Float32Array(16);
  2879. this._markAsUpdated();
  2880. }
  2881. Matrix.prototype._markAsUpdated = function () {
  2882. this.updateFlag = Matrix._updateFlagSeed++;
  2883. this._isIdentityDirty = true;
  2884. };
  2885. // Properties
  2886. /**
  2887. * Boolean : True is the matrix is the identity matrix
  2888. */
  2889. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2890. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2891. if (this._isIdentityDirty) {
  2892. this._isIdentityDirty = false;
  2893. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2894. this._isIdentity = false;
  2895. }
  2896. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2897. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2898. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2899. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2900. this._isIdentity = false;
  2901. }
  2902. else {
  2903. this._isIdentity = true;
  2904. }
  2905. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2906. this._isIdentity = false;
  2907. }
  2908. }
  2909. return this._isIdentity;
  2910. };
  2911. /**
  2912. * Returns the matrix determinant (float).
  2913. */
  2914. Matrix.prototype.determinant = function () {
  2915. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2916. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2917. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2918. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2919. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2920. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2921. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2922. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2923. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2924. };
  2925. // Methods
  2926. /**
  2927. * Returns the matrix underlying array.
  2928. */
  2929. Matrix.prototype.toArray = function () {
  2930. return this.m;
  2931. };
  2932. /**
  2933. * Returns the matrix underlying array.
  2934. */
  2935. Matrix.prototype.asArray = function () {
  2936. return this.toArray();
  2937. };
  2938. /**
  2939. * Inverts in place the Matrix.
  2940. * Returns the Matrix inverted.
  2941. */
  2942. Matrix.prototype.invert = function () {
  2943. this.invertToRef(this);
  2944. return this;
  2945. };
  2946. /**
  2947. * Sets all the matrix elements to zero.
  2948. * Returns the Matrix.
  2949. */
  2950. Matrix.prototype.reset = function () {
  2951. for (var index = 0; index < 16; index++) {
  2952. this.m[index] = 0.0;
  2953. }
  2954. this._markAsUpdated();
  2955. return this;
  2956. };
  2957. /**
  2958. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2959. */
  2960. Matrix.prototype.add = function (other) {
  2961. var result = new Matrix();
  2962. this.addToRef(other, result);
  2963. return result;
  2964. };
  2965. /**
  2966. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2967. * Returns the Matrix.
  2968. */
  2969. Matrix.prototype.addToRef = function (other, result) {
  2970. for (var index = 0; index < 16; index++) {
  2971. result.m[index] = this.m[index] + other.m[index];
  2972. }
  2973. result._markAsUpdated();
  2974. return this;
  2975. };
  2976. /**
  2977. * Adds in place the passed matrix to the current Matrix.
  2978. * Returns the updated Matrix.
  2979. */
  2980. Matrix.prototype.addToSelf = function (other) {
  2981. for (var index = 0; index < 16; index++) {
  2982. this.m[index] += other.m[index];
  2983. }
  2984. this._markAsUpdated();
  2985. return this;
  2986. };
  2987. /**
  2988. * Sets the passed matrix with the current inverted Matrix.
  2989. * Returns the unmodified current Matrix.
  2990. */
  2991. Matrix.prototype.invertToRef = function (other) {
  2992. var l1 = this.m[0];
  2993. var l2 = this.m[1];
  2994. var l3 = this.m[2];
  2995. var l4 = this.m[3];
  2996. var l5 = this.m[4];
  2997. var l6 = this.m[5];
  2998. var l7 = this.m[6];
  2999. var l8 = this.m[7];
  3000. var l9 = this.m[8];
  3001. var l10 = this.m[9];
  3002. var l11 = this.m[10];
  3003. var l12 = this.m[11];
  3004. var l13 = this.m[12];
  3005. var l14 = this.m[13];
  3006. var l15 = this.m[14];
  3007. var l16 = this.m[15];
  3008. var l17 = (l11 * l16) - (l12 * l15);
  3009. var l18 = (l10 * l16) - (l12 * l14);
  3010. var l19 = (l10 * l15) - (l11 * l14);
  3011. var l20 = (l9 * l16) - (l12 * l13);
  3012. var l21 = (l9 * l15) - (l11 * l13);
  3013. var l22 = (l9 * l14) - (l10 * l13);
  3014. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3015. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3016. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3017. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3018. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3019. var l28 = (l7 * l16) - (l8 * l15);
  3020. var l29 = (l6 * l16) - (l8 * l14);
  3021. var l30 = (l6 * l15) - (l7 * l14);
  3022. var l31 = (l5 * l16) - (l8 * l13);
  3023. var l32 = (l5 * l15) - (l7 * l13);
  3024. var l33 = (l5 * l14) - (l6 * l13);
  3025. var l34 = (l7 * l12) - (l8 * l11);
  3026. var l35 = (l6 * l12) - (l8 * l10);
  3027. var l36 = (l6 * l11) - (l7 * l10);
  3028. var l37 = (l5 * l12) - (l8 * l9);
  3029. var l38 = (l5 * l11) - (l7 * l9);
  3030. var l39 = (l5 * l10) - (l6 * l9);
  3031. other.m[0] = l23 * l27;
  3032. other.m[4] = l24 * l27;
  3033. other.m[8] = l25 * l27;
  3034. other.m[12] = l26 * l27;
  3035. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3036. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3037. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3038. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3039. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3040. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3041. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3042. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3043. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3044. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3045. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3046. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3047. other._markAsUpdated();
  3048. return this;
  3049. };
  3050. /**
  3051. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3052. * Returns the updated Matrix.
  3053. */
  3054. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3055. this.m[12] = x;
  3056. this.m[13] = y;
  3057. this.m[14] = z;
  3058. this._markAsUpdated();
  3059. return this;
  3060. };
  3061. /**
  3062. * Inserts the translation vector in the current Matrix.
  3063. * Returns the updated Matrix.
  3064. */
  3065. Matrix.prototype.setTranslation = function (vector3) {
  3066. this.m[12] = vector3.x;
  3067. this.m[13] = vector3.y;
  3068. this.m[14] = vector3.z;
  3069. this._markAsUpdated();
  3070. return this;
  3071. };
  3072. /**
  3073. * Returns a new Vector3 as the extracted translation from the Matrix.
  3074. */
  3075. Matrix.prototype.getTranslation = function () {
  3076. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3077. };
  3078. /**
  3079. * Fill a Vector3 with the extracted translation from the Matrix.
  3080. */
  3081. Matrix.prototype.getTranslationToRef = function (result) {
  3082. result.x = this.m[12];
  3083. result.y = this.m[13];
  3084. result.z = this.m[14];
  3085. return this;
  3086. };
  3087. /**
  3088. * Remove rotation and scaling part from the Matrix.
  3089. * Returns the updated Matrix.
  3090. */
  3091. Matrix.prototype.removeRotationAndScaling = function () {
  3092. this.setRowFromFloats(0, 1, 0, 0, 0);
  3093. this.setRowFromFloats(1, 0, 1, 0, 0);
  3094. this.setRowFromFloats(2, 0, 0, 1, 0);
  3095. return this;
  3096. };
  3097. /**
  3098. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3099. */
  3100. Matrix.prototype.multiply = function (other) {
  3101. var result = new Matrix();
  3102. this.multiplyToRef(other, result);
  3103. return result;
  3104. };
  3105. /**
  3106. * Updates the current Matrix from the passed one values.
  3107. * Returns the updated Matrix.
  3108. */
  3109. Matrix.prototype.copyFrom = function (other) {
  3110. for (var index = 0; index < 16; index++) {
  3111. this.m[index] = other.m[index];
  3112. }
  3113. this._markAsUpdated();
  3114. return this;
  3115. };
  3116. /**
  3117. * Populates the passed array from the starting index with the Matrix values.
  3118. * Returns the Matrix.
  3119. */
  3120. Matrix.prototype.copyToArray = function (array, offset) {
  3121. if (offset === void 0) { offset = 0; }
  3122. for (var index = 0; index < 16; index++) {
  3123. array[offset + index] = this.m[index];
  3124. }
  3125. return this;
  3126. };
  3127. /**
  3128. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3129. */
  3130. Matrix.prototype.multiplyToRef = function (other, result) {
  3131. this.multiplyToArray(other, result.m, 0);
  3132. result._markAsUpdated();
  3133. return this;
  3134. };
  3135. /**
  3136. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3137. */
  3138. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3139. var tm0 = this.m[0];
  3140. var tm1 = this.m[1];
  3141. var tm2 = this.m[2];
  3142. var tm3 = this.m[3];
  3143. var tm4 = this.m[4];
  3144. var tm5 = this.m[5];
  3145. var tm6 = this.m[6];
  3146. var tm7 = this.m[7];
  3147. var tm8 = this.m[8];
  3148. var tm9 = this.m[9];
  3149. var tm10 = this.m[10];
  3150. var tm11 = this.m[11];
  3151. var tm12 = this.m[12];
  3152. var tm13 = this.m[13];
  3153. var tm14 = this.m[14];
  3154. var tm15 = this.m[15];
  3155. var om0 = other.m[0];
  3156. var om1 = other.m[1];
  3157. var om2 = other.m[2];
  3158. var om3 = other.m[3];
  3159. var om4 = other.m[4];
  3160. var om5 = other.m[5];
  3161. var om6 = other.m[6];
  3162. var om7 = other.m[7];
  3163. var om8 = other.m[8];
  3164. var om9 = other.m[9];
  3165. var om10 = other.m[10];
  3166. var om11 = other.m[11];
  3167. var om12 = other.m[12];
  3168. var om13 = other.m[13];
  3169. var om14 = other.m[14];
  3170. var om15 = other.m[15];
  3171. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3172. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3173. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3174. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3175. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3176. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3177. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3178. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3179. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3180. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3181. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3182. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3183. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3184. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3185. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3186. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3187. return this;
  3188. };
  3189. /**
  3190. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3191. */
  3192. Matrix.prototype.equals = function (value) {
  3193. return value &&
  3194. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3195. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3196. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3197. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3198. };
  3199. /**
  3200. * Returns a new Matrix from the current Matrix.
  3201. */
  3202. Matrix.prototype.clone = function () {
  3203. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3204. };
  3205. /**
  3206. * Returns the string "Matrix"
  3207. */
  3208. Matrix.prototype.getClassName = function () {
  3209. return "Matrix";
  3210. };
  3211. /**
  3212. * Returns the Matrix hash code.
  3213. */
  3214. Matrix.prototype.getHashCode = function () {
  3215. var hash = this.m[0] || 0;
  3216. for (var i = 1; i < 16; i++) {
  3217. hash = (hash * 397) ^ (this.m[i] || 0);
  3218. }
  3219. return hash;
  3220. };
  3221. /**
  3222. * Decomposes the current Matrix into :
  3223. * - a scale vector3 passed as a reference to update,
  3224. * - a rotation quaternion passed as a reference to update,
  3225. * - a translation vector3 passed as a reference to update.
  3226. * Returns the boolean `true`.
  3227. */
  3228. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3229. translation.x = this.m[12];
  3230. translation.y = this.m[13];
  3231. translation.z = this.m[14];
  3232. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3233. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3234. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3235. if (this.determinant() <= 0) {
  3236. scale.y *= -1;
  3237. }
  3238. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3239. rotation.x = 0;
  3240. rotation.y = 0;
  3241. rotation.z = 0;
  3242. rotation.w = 1;
  3243. return false;
  3244. }
  3245. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3246. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3247. return true;
  3248. };
  3249. /**
  3250. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3251. */
  3252. Matrix.prototype.getRotationMatrix = function () {
  3253. var result = Matrix.Identity();
  3254. this.getRotationMatrixToRef(result);
  3255. return result;
  3256. };
  3257. /**
  3258. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3259. * Returns the current Matrix.
  3260. */
  3261. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3262. var m = this.m;
  3263. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3264. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3265. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3266. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3267. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3268. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3269. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3270. return this;
  3271. };
  3272. // Statics
  3273. /**
  3274. * Returns a new Matrix set from the starting index of the passed array.
  3275. */
  3276. Matrix.FromArray = function (array, offset) {
  3277. var result = new Matrix();
  3278. if (!offset) {
  3279. offset = 0;
  3280. }
  3281. Matrix.FromArrayToRef(array, offset, result);
  3282. return result;
  3283. };
  3284. /**
  3285. * Sets the passed "result" matrix from the starting index of the passed array.
  3286. */
  3287. Matrix.FromArrayToRef = function (array, offset, result) {
  3288. for (var index = 0; index < 16; index++) {
  3289. result.m[index] = array[index + offset];
  3290. }
  3291. result._markAsUpdated();
  3292. };
  3293. /**
  3294. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3295. */
  3296. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3297. for (var index = 0; index < 16; index++) {
  3298. result.m[index] = array[index + offset] * scale;
  3299. }
  3300. result._markAsUpdated();
  3301. };
  3302. /**
  3303. * Sets the passed matrix "result" with the 16 passed floats.
  3304. */
  3305. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3306. result.m[0] = initialM11;
  3307. result.m[1] = initialM12;
  3308. result.m[2] = initialM13;
  3309. result.m[3] = initialM14;
  3310. result.m[4] = initialM21;
  3311. result.m[5] = initialM22;
  3312. result.m[6] = initialM23;
  3313. result.m[7] = initialM24;
  3314. result.m[8] = initialM31;
  3315. result.m[9] = initialM32;
  3316. result.m[10] = initialM33;
  3317. result.m[11] = initialM34;
  3318. result.m[12] = initialM41;
  3319. result.m[13] = initialM42;
  3320. result.m[14] = initialM43;
  3321. result.m[15] = initialM44;
  3322. result._markAsUpdated();
  3323. };
  3324. /**
  3325. * Returns the index-th row of the current matrix as a new Vector4.
  3326. */
  3327. Matrix.prototype.getRow = function (index) {
  3328. if (index < 0 || index > 3) {
  3329. return null;
  3330. }
  3331. var i = index * 4;
  3332. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3333. };
  3334. /**
  3335. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3336. * Returns the updated Matrix.
  3337. */
  3338. Matrix.prototype.setRow = function (index, row) {
  3339. if (index < 0 || index > 3) {
  3340. return this;
  3341. }
  3342. var i = index * 4;
  3343. this.m[i + 0] = row.x;
  3344. this.m[i + 1] = row.y;
  3345. this.m[i + 2] = row.z;
  3346. this.m[i + 3] = row.w;
  3347. this._markAsUpdated();
  3348. return this;
  3349. };
  3350. /**
  3351. * Compute the transpose of the matrix.
  3352. * Returns a new Matrix.
  3353. */
  3354. Matrix.prototype.transpose = function () {
  3355. return Matrix.Transpose(this);
  3356. };
  3357. /**
  3358. * Compute the transpose of the matrix.
  3359. * Returns the current matrix.
  3360. */
  3361. Matrix.prototype.transposeToRef = function (result) {
  3362. Matrix.TransposeToRef(this, result);
  3363. return this;
  3364. };
  3365. /**
  3366. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3367. * Returns the updated Matrix.
  3368. */
  3369. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3370. if (index < 0 || index > 3) {
  3371. return this;
  3372. }
  3373. var i = index * 4;
  3374. this.m[i + 0] = x;
  3375. this.m[i + 1] = y;
  3376. this.m[i + 2] = z;
  3377. this.m[i + 3] = w;
  3378. this._markAsUpdated();
  3379. return this;
  3380. };
  3381. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3382. /**
  3383. * Static identity matrix to be used as readonly matrix
  3384. * Must not be updated.
  3385. */
  3386. get: function () {
  3387. return Matrix._identityReadOnly;
  3388. },
  3389. enumerable: true,
  3390. configurable: true
  3391. });
  3392. /**
  3393. * Returns a new Matrix set from the 16 passed floats.
  3394. */
  3395. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3396. var result = new Matrix();
  3397. result.m[0] = initialM11;
  3398. result.m[1] = initialM12;
  3399. result.m[2] = initialM13;
  3400. result.m[3] = initialM14;
  3401. result.m[4] = initialM21;
  3402. result.m[5] = initialM22;
  3403. result.m[6] = initialM23;
  3404. result.m[7] = initialM24;
  3405. result.m[8] = initialM31;
  3406. result.m[9] = initialM32;
  3407. result.m[10] = initialM33;
  3408. result.m[11] = initialM34;
  3409. result.m[12] = initialM41;
  3410. result.m[13] = initialM42;
  3411. result.m[14] = initialM43;
  3412. result.m[15] = initialM44;
  3413. return result;
  3414. };
  3415. /**
  3416. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3417. */
  3418. Matrix.Compose = function (scale, rotation, translation) {
  3419. var result = Matrix.Identity();
  3420. Matrix.ComposeToRef(scale, rotation, translation, result);
  3421. return result;
  3422. };
  3423. /**
  3424. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3425. */
  3426. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3427. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3428. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3429. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3430. result.setTranslation(translation);
  3431. };
  3432. /**
  3433. * Returns a new indentity Matrix.
  3434. */
  3435. Matrix.Identity = function () {
  3436. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3437. };
  3438. /**
  3439. * Sets the passed "result" as an identity matrix.
  3440. */
  3441. Matrix.IdentityToRef = function (result) {
  3442. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3443. };
  3444. /**
  3445. * Returns a new zero Matrix.
  3446. */
  3447. Matrix.Zero = function () {
  3448. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3449. };
  3450. /**
  3451. * Returns a new rotation matrix for "angle" radians around the X axis.
  3452. */
  3453. Matrix.RotationX = function (angle) {
  3454. var result = new Matrix();
  3455. Matrix.RotationXToRef(angle, result);
  3456. return result;
  3457. };
  3458. /**
  3459. * Returns a new Matrix as the passed inverted one.
  3460. */
  3461. Matrix.Invert = function (source) {
  3462. var result = new Matrix();
  3463. source.invertToRef(result);
  3464. return result;
  3465. };
  3466. /**
  3467. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3468. */
  3469. Matrix.RotationXToRef = function (angle, result) {
  3470. var s = Math.sin(angle);
  3471. var c = Math.cos(angle);
  3472. result.m[0] = 1.0;
  3473. result.m[15] = 1.0;
  3474. result.m[5] = c;
  3475. result.m[10] = c;
  3476. result.m[9] = -s;
  3477. result.m[6] = s;
  3478. result.m[1] = 0.0;
  3479. result.m[2] = 0.0;
  3480. result.m[3] = 0.0;
  3481. result.m[4] = 0.0;
  3482. result.m[7] = 0.0;
  3483. result.m[8] = 0.0;
  3484. result.m[11] = 0.0;
  3485. result.m[12] = 0.0;
  3486. result.m[13] = 0.0;
  3487. result.m[14] = 0.0;
  3488. result._markAsUpdated();
  3489. };
  3490. /**
  3491. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3492. */
  3493. Matrix.RotationY = function (angle) {
  3494. var result = new Matrix();
  3495. Matrix.RotationYToRef(angle, result);
  3496. return result;
  3497. };
  3498. /**
  3499. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3500. */
  3501. Matrix.RotationYToRef = function (angle, result) {
  3502. var s = Math.sin(angle);
  3503. var c = Math.cos(angle);
  3504. result.m[5] = 1.0;
  3505. result.m[15] = 1.0;
  3506. result.m[0] = c;
  3507. result.m[2] = -s;
  3508. result.m[8] = s;
  3509. result.m[10] = c;
  3510. result.m[1] = 0.0;
  3511. result.m[3] = 0.0;
  3512. result.m[4] = 0.0;
  3513. result.m[6] = 0.0;
  3514. result.m[7] = 0.0;
  3515. result.m[9] = 0.0;
  3516. result.m[11] = 0.0;
  3517. result.m[12] = 0.0;
  3518. result.m[13] = 0.0;
  3519. result.m[14] = 0.0;
  3520. result._markAsUpdated();
  3521. };
  3522. /**
  3523. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3524. */
  3525. Matrix.RotationZ = function (angle) {
  3526. var result = new Matrix();
  3527. Matrix.RotationZToRef(angle, result);
  3528. return result;
  3529. };
  3530. /**
  3531. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3532. */
  3533. Matrix.RotationZToRef = function (angle, result) {
  3534. var s = Math.sin(angle);
  3535. var c = Math.cos(angle);
  3536. result.m[10] = 1.0;
  3537. result.m[15] = 1.0;
  3538. result.m[0] = c;
  3539. result.m[1] = s;
  3540. result.m[4] = -s;
  3541. result.m[5] = c;
  3542. result.m[2] = 0.0;
  3543. result.m[3] = 0.0;
  3544. result.m[6] = 0.0;
  3545. result.m[7] = 0.0;
  3546. result.m[8] = 0.0;
  3547. result.m[9] = 0.0;
  3548. result.m[11] = 0.0;
  3549. result.m[12] = 0.0;
  3550. result.m[13] = 0.0;
  3551. result.m[14] = 0.0;
  3552. result._markAsUpdated();
  3553. };
  3554. /**
  3555. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3556. */
  3557. Matrix.RotationAxis = function (axis, angle) {
  3558. var result = Matrix.Zero();
  3559. Matrix.RotationAxisToRef(axis, angle, result);
  3560. return result;
  3561. };
  3562. /**
  3563. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3564. */
  3565. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3566. var s = Math.sin(-angle);
  3567. var c = Math.cos(-angle);
  3568. var c1 = 1 - c;
  3569. axis.normalize();
  3570. result.m[0] = (axis.x * axis.x) * c1 + c;
  3571. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3572. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3573. result.m[3] = 0.0;
  3574. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3575. result.m[5] = (axis.y * axis.y) * c1 + c;
  3576. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3577. result.m[7] = 0.0;
  3578. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3579. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3580. result.m[10] = (axis.z * axis.z) * c1 + c;
  3581. result.m[11] = 0.0;
  3582. result.m[15] = 1.0;
  3583. result._markAsUpdated();
  3584. };
  3585. /**
  3586. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3587. */
  3588. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3589. var result = new Matrix();
  3590. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3591. return result;
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3595. */
  3596. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3597. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3598. this._tempQuaternion.toRotationMatrix(result);
  3599. };
  3600. /**
  3601. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3602. */
  3603. Matrix.Scaling = function (x, y, z) {
  3604. var result = Matrix.Zero();
  3605. Matrix.ScalingToRef(x, y, z, result);
  3606. return result;
  3607. };
  3608. /**
  3609. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3610. */
  3611. Matrix.ScalingToRef = function (x, y, z, result) {
  3612. result.m[0] = x;
  3613. result.m[1] = 0.0;
  3614. result.m[2] = 0.0;
  3615. result.m[3] = 0.0;
  3616. result.m[4] = 0.0;
  3617. result.m[5] = y;
  3618. result.m[6] = 0.0;
  3619. result.m[7] = 0.0;
  3620. result.m[8] = 0.0;
  3621. result.m[9] = 0.0;
  3622. result.m[10] = z;
  3623. result.m[11] = 0.0;
  3624. result.m[12] = 0.0;
  3625. result.m[13] = 0.0;
  3626. result.m[14] = 0.0;
  3627. result.m[15] = 1.0;
  3628. result._markAsUpdated();
  3629. };
  3630. /**
  3631. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3632. */
  3633. Matrix.Translation = function (x, y, z) {
  3634. var result = Matrix.Identity();
  3635. Matrix.TranslationToRef(x, y, z, result);
  3636. return result;
  3637. };
  3638. /**
  3639. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3640. */
  3641. Matrix.TranslationToRef = function (x, y, z, result) {
  3642. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3643. };
  3644. /**
  3645. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3646. */
  3647. Matrix.Lerp = function (startValue, endValue, gradient) {
  3648. var result = Matrix.Zero();
  3649. for (var index = 0; index < 16; index++) {
  3650. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3651. }
  3652. result._markAsUpdated();
  3653. return result;
  3654. };
  3655. /**
  3656. * Returns a new Matrix whose values are computed by :
  3657. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3658. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3659. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3660. */
  3661. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3662. var startScale = new Vector3(0, 0, 0);
  3663. var startRotation = new Quaternion();
  3664. var startTranslation = new Vector3(0, 0, 0);
  3665. startValue.decompose(startScale, startRotation, startTranslation);
  3666. var endScale = new Vector3(0, 0, 0);
  3667. var endRotation = new Quaternion();
  3668. var endTranslation = new Vector3(0, 0, 0);
  3669. endValue.decompose(endScale, endRotation, endTranslation);
  3670. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3671. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3672. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3673. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3674. };
  3675. /**
  3676. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3677. * This methods works for a Left-Handed system.
  3678. */
  3679. Matrix.LookAtLH = function (eye, target, up) {
  3680. var result = Matrix.Zero();
  3681. Matrix.LookAtLHToRef(eye, target, up, result);
  3682. return result;
  3683. };
  3684. /**
  3685. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3686. * This methods works for a Left-Handed system.
  3687. */
  3688. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3689. // Z axis
  3690. target.subtractToRef(eye, this._zAxis);
  3691. this._zAxis.normalize();
  3692. // X axis
  3693. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3694. if (this._xAxis.lengthSquared() === 0) {
  3695. this._xAxis.x = 1.0;
  3696. }
  3697. else {
  3698. this._xAxis.normalize();
  3699. }
  3700. // Y axis
  3701. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3702. this._yAxis.normalize();
  3703. // Eye angles
  3704. var ex = -Vector3.Dot(this._xAxis, eye);
  3705. var ey = -Vector3.Dot(this._yAxis, eye);
  3706. var ez = -Vector3.Dot(this._zAxis, eye);
  3707. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3708. };
  3709. /**
  3710. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3711. * This methods works for a Right-Handed system.
  3712. */
  3713. Matrix.LookAtRH = function (eye, target, up) {
  3714. var result = Matrix.Zero();
  3715. Matrix.LookAtRHToRef(eye, target, up, result);
  3716. return result;
  3717. };
  3718. /**
  3719. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3720. * This methods works for a Left-Handed system.
  3721. */
  3722. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3723. // Z axis
  3724. eye.subtractToRef(target, this._zAxis);
  3725. this._zAxis.normalize();
  3726. // X axis
  3727. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3728. if (this._xAxis.lengthSquared() === 0) {
  3729. this._xAxis.x = 1.0;
  3730. }
  3731. else {
  3732. this._xAxis.normalize();
  3733. }
  3734. // Y axis
  3735. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3736. this._yAxis.normalize();
  3737. // Eye angles
  3738. var ex = -Vector3.Dot(this._xAxis, eye);
  3739. var ey = -Vector3.Dot(this._yAxis, eye);
  3740. var ez = -Vector3.Dot(this._zAxis, eye);
  3741. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3742. };
  3743. /**
  3744. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3745. */
  3746. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3747. var matrix = Matrix.Zero();
  3748. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3749. return matrix;
  3750. };
  3751. /**
  3752. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3753. */
  3754. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3755. var n = znear;
  3756. var f = zfar;
  3757. var a = 2.0 / width;
  3758. var b = 2.0 / height;
  3759. var c = 2.0 / (f - n);
  3760. var d = -(f + n) / (f - n);
  3761. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3762. };
  3763. /**
  3764. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3765. */
  3766. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3767. var matrix = Matrix.Zero();
  3768. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3769. return matrix;
  3770. };
  3771. /**
  3772. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3773. */
  3774. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3775. var n = znear;
  3776. var f = zfar;
  3777. var a = 2.0 / (right - left);
  3778. var b = 2.0 / (top - bottom);
  3779. var c = 2.0 / (f - n);
  3780. var d = -(f + n) / (f - n);
  3781. var i0 = (left + right) / (left - right);
  3782. var i1 = (top + bottom) / (bottom - top);
  3783. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3784. };
  3785. /**
  3786. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3787. */
  3788. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3789. var matrix = Matrix.Zero();
  3790. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3791. return matrix;
  3792. };
  3793. /**
  3794. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3795. */
  3796. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3797. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3798. result.m[10] *= -1.0;
  3799. };
  3800. /**
  3801. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3802. */
  3803. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3804. var matrix = Matrix.Zero();
  3805. var n = znear;
  3806. var f = zfar;
  3807. var a = 2.0 * n / width;
  3808. var b = 2.0 * n / height;
  3809. var c = (f + n) / (f - n);
  3810. var d = -2.0 * f * n / (f - n);
  3811. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3812. return matrix;
  3813. };
  3814. /**
  3815. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3816. */
  3817. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3818. var matrix = Matrix.Zero();
  3819. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3820. return matrix;
  3821. };
  3822. /**
  3823. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3824. */
  3825. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3826. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3827. var n = znear;
  3828. var f = zfar;
  3829. var t = 1.0 / (Math.tan(fov * 0.5));
  3830. var a = isVerticalFovFixed ? (t / aspect) : t;
  3831. var b = isVerticalFovFixed ? t : (t * aspect);
  3832. var c = (f + n) / (f - n);
  3833. var d = -2.0 * f * n / (f - n);
  3834. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3835. };
  3836. /**
  3837. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3838. */
  3839. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3840. var matrix = Matrix.Zero();
  3841. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3842. return matrix;
  3843. };
  3844. /**
  3845. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3846. */
  3847. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3848. //alternatively this could be expressed as:
  3849. // m = PerspectiveFovLHToRef
  3850. // m[10] *= -1.0;
  3851. // m[11] *= -1.0;
  3852. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3853. var n = znear;
  3854. var f = zfar;
  3855. var t = 1.0 / (Math.tan(fov * 0.5));
  3856. var a = isVerticalFovFixed ? (t / aspect) : t;
  3857. var b = isVerticalFovFixed ? t : (t * aspect);
  3858. var c = -(f + n) / (f - n);
  3859. var d = -2 * f * n / (f - n);
  3860. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3861. };
  3862. /**
  3863. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3864. */
  3865. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3866. if (rightHanded === void 0) { rightHanded = false; }
  3867. var rightHandedFactor = rightHanded ? -1 : 1;
  3868. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3869. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3870. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3871. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3872. var xScale = 2.0 / (leftTan + rightTan);
  3873. var yScale = 2.0 / (upTan + downTan);
  3874. result.m[0] = xScale;
  3875. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3876. result.m[5] = yScale;
  3877. result.m[6] = result.m[7] = 0.0;
  3878. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3879. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3880. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3881. result.m[10] = -zfar / (znear - zfar);
  3882. result.m[11] = 1.0 * rightHandedFactor;
  3883. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3884. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3885. // result.m[14] = (znear * zfar) / (znear - zfar);
  3886. result._markAsUpdated();
  3887. };
  3888. /**
  3889. * Returns the final transformation matrix : world * view * projection * viewport
  3890. */
  3891. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3892. var cw = viewport.width;
  3893. var ch = viewport.height;
  3894. var cx = viewport.x;
  3895. var cy = viewport.y;
  3896. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3897. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3898. };
  3899. /**
  3900. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3901. */
  3902. Matrix.GetAsMatrix2x2 = function (matrix) {
  3903. return new Float32Array([
  3904. matrix.m[0], matrix.m[1],
  3905. matrix.m[4], matrix.m[5]
  3906. ]);
  3907. };
  3908. /**
  3909. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3910. */
  3911. Matrix.GetAsMatrix3x3 = function (matrix) {
  3912. return new Float32Array([
  3913. matrix.m[0], matrix.m[1], matrix.m[2],
  3914. matrix.m[4], matrix.m[5], matrix.m[6],
  3915. matrix.m[8], matrix.m[9], matrix.m[10]
  3916. ]);
  3917. };
  3918. /**
  3919. * Compute the transpose of the passed Matrix.
  3920. * Returns a new Matrix.
  3921. */
  3922. Matrix.Transpose = function (matrix) {
  3923. var result = new Matrix();
  3924. Matrix.TransposeToRef(matrix, result);
  3925. return result;
  3926. };
  3927. /**
  3928. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3929. */
  3930. Matrix.TransposeToRef = function (matrix, result) {
  3931. result.m[0] = matrix.m[0];
  3932. result.m[1] = matrix.m[4];
  3933. result.m[2] = matrix.m[8];
  3934. result.m[3] = matrix.m[12];
  3935. result.m[4] = matrix.m[1];
  3936. result.m[5] = matrix.m[5];
  3937. result.m[6] = matrix.m[9];
  3938. result.m[7] = matrix.m[13];
  3939. result.m[8] = matrix.m[2];
  3940. result.m[9] = matrix.m[6];
  3941. result.m[10] = matrix.m[10];
  3942. result.m[11] = matrix.m[14];
  3943. result.m[12] = matrix.m[3];
  3944. result.m[13] = matrix.m[7];
  3945. result.m[14] = matrix.m[11];
  3946. result.m[15] = matrix.m[15];
  3947. };
  3948. /**
  3949. * Returns a new Matrix as the reflection matrix across the passed plane.
  3950. */
  3951. Matrix.Reflection = function (plane) {
  3952. var matrix = new Matrix();
  3953. Matrix.ReflectionToRef(plane, matrix);
  3954. return matrix;
  3955. };
  3956. /**
  3957. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3958. */
  3959. Matrix.ReflectionToRef = function (plane, result) {
  3960. plane.normalize();
  3961. var x = plane.normal.x;
  3962. var y = plane.normal.y;
  3963. var z = plane.normal.z;
  3964. var temp = -2 * x;
  3965. var temp2 = -2 * y;
  3966. var temp3 = -2 * z;
  3967. result.m[0] = (temp * x) + 1;
  3968. result.m[1] = temp2 * x;
  3969. result.m[2] = temp3 * x;
  3970. result.m[3] = 0.0;
  3971. result.m[4] = temp * y;
  3972. result.m[5] = (temp2 * y) + 1;
  3973. result.m[6] = temp3 * y;
  3974. result.m[7] = 0.0;
  3975. result.m[8] = temp * z;
  3976. result.m[9] = temp2 * z;
  3977. result.m[10] = (temp3 * z) + 1;
  3978. result.m[11] = 0.0;
  3979. result.m[12] = temp * plane.d;
  3980. result.m[13] = temp2 * plane.d;
  3981. result.m[14] = temp3 * plane.d;
  3982. result.m[15] = 1.0;
  3983. result._markAsUpdated();
  3984. };
  3985. /**
  3986. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3987. */
  3988. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3989. result.m[0] = xaxis.x;
  3990. result.m[1] = xaxis.y;
  3991. result.m[2] = xaxis.z;
  3992. result.m[3] = 0.0;
  3993. result.m[4] = yaxis.x;
  3994. result.m[5] = yaxis.y;
  3995. result.m[6] = yaxis.z;
  3996. result.m[7] = 0.0;
  3997. result.m[8] = zaxis.x;
  3998. result.m[9] = zaxis.y;
  3999. result.m[10] = zaxis.z;
  4000. result.m[11] = 0.0;
  4001. result.m[12] = 0.0;
  4002. result.m[13] = 0.0;
  4003. result.m[14] = 0.0;
  4004. result.m[15] = 1.0;
  4005. result._markAsUpdated();
  4006. };
  4007. /**
  4008. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4009. */
  4010. Matrix.FromQuaternionToRef = function (quat, result) {
  4011. var xx = quat.x * quat.x;
  4012. var yy = quat.y * quat.y;
  4013. var zz = quat.z * quat.z;
  4014. var xy = quat.x * quat.y;
  4015. var zw = quat.z * quat.w;
  4016. var zx = quat.z * quat.x;
  4017. var yw = quat.y * quat.w;
  4018. var yz = quat.y * quat.z;
  4019. var xw = quat.x * quat.w;
  4020. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4021. result.m[1] = 2.0 * (xy + zw);
  4022. result.m[2] = 2.0 * (zx - yw);
  4023. result.m[3] = 0.0;
  4024. result.m[4] = 2.0 * (xy - zw);
  4025. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4026. result.m[6] = 2.0 * (yz + xw);
  4027. result.m[7] = 0.0;
  4028. result.m[8] = 2.0 * (zx + yw);
  4029. result.m[9] = 2.0 * (yz - xw);
  4030. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4031. result.m[11] = 0.0;
  4032. result.m[12] = 0.0;
  4033. result.m[13] = 0.0;
  4034. result.m[14] = 0.0;
  4035. result.m[15] = 1.0;
  4036. result._markAsUpdated();
  4037. };
  4038. Matrix._tempQuaternion = new Quaternion();
  4039. Matrix._xAxis = Vector3.Zero();
  4040. Matrix._yAxis = Vector3.Zero();
  4041. Matrix._zAxis = Vector3.Zero();
  4042. Matrix._updateFlagSeed = 0;
  4043. Matrix._identityReadOnly = Matrix.Identity();
  4044. return Matrix;
  4045. }());
  4046. BABYLON.Matrix = Matrix;
  4047. var Plane = /** @class */ (function () {
  4048. /**
  4049. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4050. */
  4051. function Plane(a, b, c, d) {
  4052. this.normal = new Vector3(a, b, c);
  4053. this.d = d;
  4054. }
  4055. /**
  4056. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4057. */
  4058. Plane.prototype.asArray = function () {
  4059. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4060. };
  4061. // Methods
  4062. /**
  4063. * Returns a new plane copied from the current Plane.
  4064. */
  4065. Plane.prototype.clone = function () {
  4066. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4067. };
  4068. /**
  4069. * Returns the string "Plane".
  4070. */
  4071. Plane.prototype.getClassName = function () {
  4072. return "Plane";
  4073. };
  4074. /**
  4075. * Returns the Plane hash code.
  4076. */
  4077. Plane.prototype.getHashCode = function () {
  4078. var hash = this.normal.getHashCode();
  4079. hash = (hash * 397) ^ (this.d || 0);
  4080. return hash;
  4081. };
  4082. /**
  4083. * Normalize the current Plane in place.
  4084. * Returns the updated Plane.
  4085. */
  4086. Plane.prototype.normalize = function () {
  4087. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4088. var magnitude = 0.0;
  4089. if (norm !== 0) {
  4090. magnitude = 1.0 / norm;
  4091. }
  4092. this.normal.x *= magnitude;
  4093. this.normal.y *= magnitude;
  4094. this.normal.z *= magnitude;
  4095. this.d *= magnitude;
  4096. return this;
  4097. };
  4098. /**
  4099. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4100. */
  4101. Plane.prototype.transform = function (transformation) {
  4102. var transposedMatrix = Matrix.Transpose(transformation);
  4103. var x = this.normal.x;
  4104. var y = this.normal.y;
  4105. var z = this.normal.z;
  4106. var d = this.d;
  4107. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4108. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4109. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4110. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4111. return new Plane(normalX, normalY, normalZ, finalD);
  4112. };
  4113. /**
  4114. * Returns the dot product (float) of the point coordinates and the plane normal.
  4115. */
  4116. Plane.prototype.dotCoordinate = function (point) {
  4117. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4118. };
  4119. /**
  4120. * Updates the current Plane from the plane defined by the three passed points.
  4121. * Returns the updated Plane.
  4122. */
  4123. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4124. var x1 = point2.x - point1.x;
  4125. var y1 = point2.y - point1.y;
  4126. var z1 = point2.z - point1.z;
  4127. var x2 = point3.x - point1.x;
  4128. var y2 = point3.y - point1.y;
  4129. var z2 = point3.z - point1.z;
  4130. var yz = (y1 * z2) - (z1 * y2);
  4131. var xz = (z1 * x2) - (x1 * z2);
  4132. var xy = (x1 * y2) - (y1 * x2);
  4133. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4134. var invPyth;
  4135. if (pyth !== 0) {
  4136. invPyth = 1.0 / pyth;
  4137. }
  4138. else {
  4139. invPyth = 0.0;
  4140. }
  4141. this.normal.x = yz * invPyth;
  4142. this.normal.y = xz * invPyth;
  4143. this.normal.z = xy * invPyth;
  4144. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4145. return this;
  4146. };
  4147. /**
  4148. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4149. */
  4150. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4151. var dot = Vector3.Dot(this.normal, direction);
  4152. return (dot <= epsilon);
  4153. };
  4154. /**
  4155. * Returns the signed distance (float) from the passed point to the Plane.
  4156. */
  4157. Plane.prototype.signedDistanceTo = function (point) {
  4158. return Vector3.Dot(point, this.normal) + this.d;
  4159. };
  4160. // Statics
  4161. /**
  4162. * Returns a new Plane from the passed array.
  4163. */
  4164. Plane.FromArray = function (array) {
  4165. return new Plane(array[0], array[1], array[2], array[3]);
  4166. };
  4167. /**
  4168. * Returns a new Plane defined by the three passed points.
  4169. */
  4170. Plane.FromPoints = function (point1, point2, point3) {
  4171. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4172. result.copyFromPoints(point1, point2, point3);
  4173. return result;
  4174. };
  4175. /**
  4176. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4177. * Note : the vector "normal" is updated because normalized.
  4178. */
  4179. Plane.FromPositionAndNormal = function (origin, normal) {
  4180. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4181. normal.normalize();
  4182. result.normal = normal;
  4183. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4184. return result;
  4185. };
  4186. /**
  4187. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4188. */
  4189. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4190. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4191. return Vector3.Dot(point, normal) + d;
  4192. };
  4193. return Plane;
  4194. }());
  4195. BABYLON.Plane = Plane;
  4196. var Viewport = /** @class */ (function () {
  4197. /**
  4198. * Creates a Viewport object located at (x, y) and sized (width, height).
  4199. */
  4200. function Viewport(x, y, width, height) {
  4201. this.x = x;
  4202. this.y = y;
  4203. this.width = width;
  4204. this.height = height;
  4205. }
  4206. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4207. if (renderWidthOrEngine.getRenderWidth) {
  4208. var engine = renderWidthOrEngine;
  4209. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4210. }
  4211. var renderWidth = renderWidthOrEngine;
  4212. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4213. };
  4214. /**
  4215. * Returns a new Viewport copied from the current one.
  4216. */
  4217. Viewport.prototype.clone = function () {
  4218. return new Viewport(this.x, this.y, this.width, this.height);
  4219. };
  4220. return Viewport;
  4221. }());
  4222. BABYLON.Viewport = Viewport;
  4223. var Frustum = /** @class */ (function () {
  4224. function Frustum() {
  4225. }
  4226. /**
  4227. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4228. */
  4229. Frustum.GetPlanes = function (transform) {
  4230. var frustumPlanes = [];
  4231. for (var index = 0; index < 6; index++) {
  4232. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4233. }
  4234. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4235. return frustumPlanes;
  4236. };
  4237. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4238. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4239. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4240. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4241. frustumPlane.d = transform.m[15] + transform.m[14];
  4242. frustumPlane.normalize();
  4243. };
  4244. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4245. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4246. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4247. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4248. frustumPlane.d = transform.m[15] - transform.m[14];
  4249. frustumPlane.normalize();
  4250. };
  4251. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4252. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4253. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4254. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4255. frustumPlane.d = transform.m[15] + transform.m[12];
  4256. frustumPlane.normalize();
  4257. };
  4258. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4259. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4260. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4261. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4262. frustumPlane.d = transform.m[15] - transform.m[12];
  4263. frustumPlane.normalize();
  4264. };
  4265. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4266. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4267. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4268. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4269. frustumPlane.d = transform.m[15] - transform.m[13];
  4270. frustumPlane.normalize();
  4271. };
  4272. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4273. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4274. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4275. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4276. frustumPlane.d = transform.m[15] + transform.m[13];
  4277. frustumPlane.normalize();
  4278. };
  4279. /**
  4280. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4281. */
  4282. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4283. // Near
  4284. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4285. // Far
  4286. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4287. // Left
  4288. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4289. // Right
  4290. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4291. // Top
  4292. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4293. // Bottom
  4294. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4295. };
  4296. return Frustum;
  4297. }());
  4298. BABYLON.Frustum = Frustum;
  4299. var Space;
  4300. (function (Space) {
  4301. Space[Space["LOCAL"] = 0] = "LOCAL";
  4302. Space[Space["WORLD"] = 1] = "WORLD";
  4303. Space[Space["BONE"] = 2] = "BONE";
  4304. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4305. var Axis = /** @class */ (function () {
  4306. function Axis() {
  4307. }
  4308. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4309. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4310. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4311. return Axis;
  4312. }());
  4313. BABYLON.Axis = Axis;
  4314. ;
  4315. var BezierCurve = /** @class */ (function () {
  4316. function BezierCurve() {
  4317. }
  4318. /**
  4319. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4320. */
  4321. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4322. // Extract X (which is equal to time here)
  4323. var f0 = 1 - 3 * x2 + 3 * x1;
  4324. var f1 = 3 * x2 - 6 * x1;
  4325. var f2 = 3 * x1;
  4326. var refinedT = t;
  4327. for (var i = 0; i < 5; i++) {
  4328. var refinedT2 = refinedT * refinedT;
  4329. var refinedT3 = refinedT2 * refinedT;
  4330. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4331. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4332. refinedT -= (x - t) * slope;
  4333. refinedT = Math.min(1, Math.max(0, refinedT));
  4334. }
  4335. // Resolve cubic bezier for the given x
  4336. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4337. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4338. Math.pow(refinedT, 3);
  4339. };
  4340. return BezierCurve;
  4341. }());
  4342. BABYLON.BezierCurve = BezierCurve;
  4343. var Orientation;
  4344. (function (Orientation) {
  4345. Orientation[Orientation["CW"] = 0] = "CW";
  4346. Orientation[Orientation["CCW"] = 1] = "CCW";
  4347. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4348. var Angle = /** @class */ (function () {
  4349. /**
  4350. * Creates an Angle object of "radians" radians (float).
  4351. */
  4352. function Angle(radians) {
  4353. var _this = this;
  4354. /**
  4355. * Returns the Angle value in degrees (float).
  4356. */
  4357. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4358. /**
  4359. * Returns the Angle value in radians (float).
  4360. */
  4361. this.radians = function () { return _this._radians; };
  4362. this._radians = radians;
  4363. if (this._radians < 0.0)
  4364. this._radians += (2.0 * Math.PI);
  4365. }
  4366. /**
  4367. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4368. */
  4369. Angle.BetweenTwoPoints = function (a, b) {
  4370. var delta = b.subtract(a);
  4371. var theta = Math.atan2(delta.y, delta.x);
  4372. return new Angle(theta);
  4373. };
  4374. /**
  4375. * Returns a new Angle object from the passed float in radians.
  4376. */
  4377. Angle.FromRadians = function (radians) {
  4378. return new Angle(radians);
  4379. };
  4380. /**
  4381. * Returns a new Angle object from the passed float in degrees.
  4382. */
  4383. Angle.FromDegrees = function (degrees) {
  4384. return new Angle(degrees * Math.PI / 180.0);
  4385. };
  4386. return Angle;
  4387. }());
  4388. BABYLON.Angle = Angle;
  4389. var Arc2 = /** @class */ (function () {
  4390. /**
  4391. * Creates an Arc object from the three passed points : start, middle and end.
  4392. */
  4393. function Arc2(startPoint, midPoint, endPoint) {
  4394. this.startPoint = startPoint;
  4395. this.midPoint = midPoint;
  4396. this.endPoint = endPoint;
  4397. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4398. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4399. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4400. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4401. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4402. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4403. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4404. var a1 = this.startAngle.degrees();
  4405. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4406. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4407. // angles correction
  4408. if (a2 - a1 > +180.0)
  4409. a2 -= 360.0;
  4410. if (a2 - a1 < -180.0)
  4411. a2 += 360.0;
  4412. if (a3 - a2 > +180.0)
  4413. a3 -= 360.0;
  4414. if (a3 - a2 < -180.0)
  4415. a3 += 360.0;
  4416. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4417. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4418. }
  4419. return Arc2;
  4420. }());
  4421. BABYLON.Arc2 = Arc2;
  4422. var Path2 = /** @class */ (function () {
  4423. /**
  4424. * Creates a Path2 object from the starting 2D coordinates x and y.
  4425. */
  4426. function Path2(x, y) {
  4427. this._points = new Array();
  4428. this._length = 0.0;
  4429. this.closed = false;
  4430. this._points.push(new Vector2(x, y));
  4431. }
  4432. /**
  4433. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4434. * Returns the updated Path2.
  4435. */
  4436. Path2.prototype.addLineTo = function (x, y) {
  4437. if (closed) {
  4438. //Tools.Error("cannot add lines to closed paths");
  4439. return this;
  4440. }
  4441. var newPoint = new Vector2(x, y);
  4442. var previousPoint = this._points[this._points.length - 1];
  4443. this._points.push(newPoint);
  4444. this._length += newPoint.subtract(previousPoint).length();
  4445. return this;
  4446. };
  4447. /**
  4448. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4449. * Returns the updated Path2.
  4450. */
  4451. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4452. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4453. if (closed) {
  4454. //Tools.Error("cannot add arcs to closed paths");
  4455. return this;
  4456. }
  4457. var startPoint = this._points[this._points.length - 1];
  4458. var midPoint = new Vector2(midX, midY);
  4459. var endPoint = new Vector2(endX, endY);
  4460. var arc = new Arc2(startPoint, midPoint, endPoint);
  4461. var increment = arc.angle.radians() / numberOfSegments;
  4462. if (arc.orientation === Orientation.CW)
  4463. increment *= -1;
  4464. var currentAngle = arc.startAngle.radians() + increment;
  4465. for (var i = 0; i < numberOfSegments; i++) {
  4466. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4467. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4468. this.addLineTo(x, y);
  4469. currentAngle += increment;
  4470. }
  4471. return this;
  4472. };
  4473. /**
  4474. * Closes the Path2.
  4475. * Returns the Path2.
  4476. */
  4477. Path2.prototype.close = function () {
  4478. this.closed = true;
  4479. return this;
  4480. };
  4481. /**
  4482. * Returns the Path2 total length (float).
  4483. */
  4484. Path2.prototype.length = function () {
  4485. var result = this._length;
  4486. if (!this.closed) {
  4487. var lastPoint = this._points[this._points.length - 1];
  4488. var firstPoint = this._points[0];
  4489. result += (firstPoint.subtract(lastPoint).length());
  4490. }
  4491. return result;
  4492. };
  4493. /**
  4494. * Returns the Path2 internal array of points.
  4495. */
  4496. Path2.prototype.getPoints = function () {
  4497. return this._points;
  4498. };
  4499. /**
  4500. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4501. */
  4502. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4503. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4504. //Tools.Error("normalized length position should be between 0 and 1.");
  4505. return Vector2.Zero();
  4506. }
  4507. var lengthPosition = normalizedLengthPosition * this.length();
  4508. var previousOffset = 0;
  4509. for (var i = 0; i < this._points.length; i++) {
  4510. var j = (i + 1) % this._points.length;
  4511. var a = this._points[i];
  4512. var b = this._points[j];
  4513. var bToA = b.subtract(a);
  4514. var nextOffset = (bToA.length() + previousOffset);
  4515. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4516. var dir = bToA.normalize();
  4517. var localOffset = lengthPosition - previousOffset;
  4518. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4519. }
  4520. previousOffset = nextOffset;
  4521. }
  4522. //Tools.Error("internal error");
  4523. return Vector2.Zero();
  4524. };
  4525. /**
  4526. * Returns a new Path2 starting at the coordinates (x, y).
  4527. */
  4528. Path2.StartingAt = function (x, y) {
  4529. return new Path2(x, y);
  4530. };
  4531. return Path2;
  4532. }());
  4533. BABYLON.Path2 = Path2;
  4534. var Path3D = /** @class */ (function () {
  4535. /**
  4536. * new Path3D(path, normal, raw)
  4537. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4538. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4539. * path : an array of Vector3, the curve axis of the Path3D
  4540. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4541. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4542. */
  4543. function Path3D(path, firstNormal, raw) {
  4544. if (firstNormal === void 0) { firstNormal = null; }
  4545. this.path = path;
  4546. this._curve = new Array();
  4547. this._distances = new Array();
  4548. this._tangents = new Array();
  4549. this._normals = new Array();
  4550. this._binormals = new Array();
  4551. for (var p = 0; p < path.length; p++) {
  4552. this._curve[p] = path[p].clone(); // hard copy
  4553. }
  4554. this._raw = raw || false;
  4555. this._compute(firstNormal);
  4556. }
  4557. /**
  4558. * Returns the Path3D array of successive Vector3 designing its curve.
  4559. */
  4560. Path3D.prototype.getCurve = function () {
  4561. return this._curve;
  4562. };
  4563. /**
  4564. * Returns an array populated with tangent vectors on each Path3D curve point.
  4565. */
  4566. Path3D.prototype.getTangents = function () {
  4567. return this._tangents;
  4568. };
  4569. /**
  4570. * Returns an array populated with normal vectors on each Path3D curve point.
  4571. */
  4572. Path3D.prototype.getNormals = function () {
  4573. return this._normals;
  4574. };
  4575. /**
  4576. * Returns an array populated with binormal vectors on each Path3D curve point.
  4577. */
  4578. Path3D.prototype.getBinormals = function () {
  4579. return this._binormals;
  4580. };
  4581. /**
  4582. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4583. */
  4584. Path3D.prototype.getDistances = function () {
  4585. return this._distances;
  4586. };
  4587. /**
  4588. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4589. * Returns the same object updated.
  4590. */
  4591. Path3D.prototype.update = function (path, firstNormal) {
  4592. if (firstNormal === void 0) { firstNormal = null; }
  4593. for (var p = 0; p < path.length; p++) {
  4594. this._curve[p].x = path[p].x;
  4595. this._curve[p].y = path[p].y;
  4596. this._curve[p].z = path[p].z;
  4597. }
  4598. this._compute(firstNormal);
  4599. return this;
  4600. };
  4601. // private function compute() : computes tangents, normals and binormals
  4602. Path3D.prototype._compute = function (firstNormal) {
  4603. var l = this._curve.length;
  4604. // first and last tangents
  4605. this._tangents[0] = this._getFirstNonNullVector(0);
  4606. if (!this._raw) {
  4607. this._tangents[0].normalize();
  4608. }
  4609. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4610. if (!this._raw) {
  4611. this._tangents[l - 1].normalize();
  4612. }
  4613. // normals and binormals at first point : arbitrary vector with _normalVector()
  4614. var tg0 = this._tangents[0];
  4615. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4616. this._normals[0] = pp0;
  4617. if (!this._raw) {
  4618. this._normals[0].normalize();
  4619. }
  4620. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4621. if (!this._raw) {
  4622. this._binormals[0].normalize();
  4623. }
  4624. this._distances[0] = 0.0;
  4625. // normals and binormals : next points
  4626. var prev; // previous vector (segment)
  4627. var cur; // current vector (segment)
  4628. var curTang; // current tangent
  4629. // previous normal
  4630. var prevBinor; // previous binormal
  4631. for (var i = 1; i < l; i++) {
  4632. // tangents
  4633. prev = this._getLastNonNullVector(i);
  4634. if (i < l - 1) {
  4635. cur = this._getFirstNonNullVector(i);
  4636. this._tangents[i] = prev.add(cur);
  4637. this._tangents[i].normalize();
  4638. }
  4639. this._distances[i] = this._distances[i - 1] + prev.length();
  4640. // normals and binormals
  4641. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4642. curTang = this._tangents[i];
  4643. prevBinor = this._binormals[i - 1];
  4644. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4645. if (!this._raw) {
  4646. this._normals[i].normalize();
  4647. }
  4648. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4649. if (!this._raw) {
  4650. this._binormals[i].normalize();
  4651. }
  4652. }
  4653. };
  4654. // private function getFirstNonNullVector(index)
  4655. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4656. Path3D.prototype._getFirstNonNullVector = function (index) {
  4657. var i = 1;
  4658. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4659. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4660. i++;
  4661. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4662. }
  4663. return nNVector;
  4664. };
  4665. // private function getLastNonNullVector(index)
  4666. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4667. Path3D.prototype._getLastNonNullVector = function (index) {
  4668. var i = 1;
  4669. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4670. while (nLVector.length() === 0 && index > i + 1) {
  4671. i++;
  4672. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4673. }
  4674. return nLVector;
  4675. };
  4676. // private function normalVector(v0, vt, va) :
  4677. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4678. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4679. Path3D.prototype._normalVector = function (v0, vt, va) {
  4680. var normal0;
  4681. var tgl = vt.length();
  4682. if (tgl === 0.0) {
  4683. tgl = 1.0;
  4684. }
  4685. if (va === undefined || va === null) {
  4686. var point;
  4687. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4688. point = new Vector3(0.0, -1.0, 0.0);
  4689. }
  4690. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4691. point = new Vector3(1.0, 0.0, 0.0);
  4692. }
  4693. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4694. point = new Vector3(0.0, 0.0, 1.0);
  4695. }
  4696. else {
  4697. point = Vector3.Zero();
  4698. }
  4699. normal0 = Vector3.Cross(vt, point);
  4700. }
  4701. else {
  4702. normal0 = Vector3.Cross(vt, va);
  4703. Vector3.CrossToRef(normal0, vt, normal0);
  4704. }
  4705. normal0.normalize();
  4706. return normal0;
  4707. };
  4708. return Path3D;
  4709. }());
  4710. BABYLON.Path3D = Path3D;
  4711. var Curve3 = /** @class */ (function () {
  4712. /**
  4713. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4714. * A Curve3 is designed from a series of successive Vector3.
  4715. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4716. */
  4717. function Curve3(points) {
  4718. this._length = 0.0;
  4719. this._points = points;
  4720. this._length = this._computeLength(points);
  4721. }
  4722. /**
  4723. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4724. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4725. * @param v1 (Vector3) the control point
  4726. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4727. * @param nbPoints (integer) the wanted number of points in the curve
  4728. */
  4729. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4730. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4731. var bez = new Array();
  4732. var equation = function (t, val0, val1, val2) {
  4733. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4734. return res;
  4735. };
  4736. for (var i = 0; i <= nbPoints; i++) {
  4737. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4738. }
  4739. return new Curve3(bez);
  4740. };
  4741. /**
  4742. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4743. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4744. * @param v1 (Vector3) the first control point
  4745. * @param v2 (Vector3) the second control point
  4746. * @param v3 (Vector3) the end point of the Cubic Bezier
  4747. * @param nbPoints (integer) the wanted number of points in the curve
  4748. */
  4749. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4750. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4751. var bez = new Array();
  4752. var equation = function (t, val0, val1, val2, val3) {
  4753. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4754. return res;
  4755. };
  4756. for (var i = 0; i <= nbPoints; i++) {
  4757. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4758. }
  4759. return new Curve3(bez);
  4760. };
  4761. /**
  4762. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4763. * @param p1 (Vector3) the origin point of the Hermite Spline
  4764. * @param t1 (Vector3) the tangent vector at the origin point
  4765. * @param p2 (Vector3) the end point of the Hermite Spline
  4766. * @param t2 (Vector3) the tangent vector at the end point
  4767. * @param nbPoints (integer) the wanted number of points in the curve
  4768. */
  4769. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4770. var hermite = new Array();
  4771. var step = 1.0 / nbPoints;
  4772. for (var i = 0; i <= nbPoints; i++) {
  4773. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4774. }
  4775. return new Curve3(hermite);
  4776. };
  4777. /**
  4778. * Returns a Curve3 object along a CatmullRom Spline curve :
  4779. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4780. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4781. */
  4782. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4783. var totalPoints = new Array();
  4784. totalPoints.push(points[0].clone());
  4785. Array.prototype.push.apply(totalPoints, points);
  4786. totalPoints.push(points[points.length - 1].clone());
  4787. var catmullRom = new Array();
  4788. var step = 1.0 / nbPoints;
  4789. var amount = 0.0;
  4790. for (var i = 0; i < totalPoints.length - 3; i++) {
  4791. amount = 0;
  4792. for (var c = 0; c < nbPoints; c++) {
  4793. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4794. amount += step;
  4795. }
  4796. }
  4797. i--;
  4798. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4799. return new Curve3(catmullRom);
  4800. };
  4801. /**
  4802. * Returns the Curve3 stored array of successive Vector3
  4803. */
  4804. Curve3.prototype.getPoints = function () {
  4805. return this._points;
  4806. };
  4807. /**
  4808. * Returns the computed length (float) of the curve.
  4809. */
  4810. Curve3.prototype.length = function () {
  4811. return this._length;
  4812. };
  4813. /**
  4814. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4815. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4816. * curveA and curveB keep unchanged.
  4817. */
  4818. Curve3.prototype.continue = function (curve) {
  4819. var lastPoint = this._points[this._points.length - 1];
  4820. var continuedPoints = this._points.slice();
  4821. var curvePoints = curve.getPoints();
  4822. for (var i = 1; i < curvePoints.length; i++) {
  4823. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4824. }
  4825. var continuedCurve = new Curve3(continuedPoints);
  4826. return continuedCurve;
  4827. };
  4828. Curve3.prototype._computeLength = function (path) {
  4829. var l = 0;
  4830. for (var i = 1; i < path.length; i++) {
  4831. l += (path[i].subtract(path[i - 1])).length();
  4832. }
  4833. return l;
  4834. };
  4835. return Curve3;
  4836. }());
  4837. BABYLON.Curve3 = Curve3;
  4838. // Vertex formats
  4839. var PositionNormalVertex = /** @class */ (function () {
  4840. function PositionNormalVertex(position, normal) {
  4841. if (position === void 0) { position = Vector3.Zero(); }
  4842. if (normal === void 0) { normal = Vector3.Up(); }
  4843. this.position = position;
  4844. this.normal = normal;
  4845. }
  4846. PositionNormalVertex.prototype.clone = function () {
  4847. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4848. };
  4849. return PositionNormalVertex;
  4850. }());
  4851. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4852. var PositionNormalTextureVertex = /** @class */ (function () {
  4853. function PositionNormalTextureVertex(position, normal, uv) {
  4854. if (position === void 0) { position = Vector3.Zero(); }
  4855. if (normal === void 0) { normal = Vector3.Up(); }
  4856. if (uv === void 0) { uv = Vector2.Zero(); }
  4857. this.position = position;
  4858. this.normal = normal;
  4859. this.uv = uv;
  4860. }
  4861. PositionNormalTextureVertex.prototype.clone = function () {
  4862. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4863. };
  4864. return PositionNormalTextureVertex;
  4865. }());
  4866. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4867. // Temporary pre-allocated objects for engine internal use
  4868. // usage in any internal function :
  4869. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4870. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4871. var Tmp = /** @class */ (function () {
  4872. function Tmp() {
  4873. }
  4874. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4875. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4876. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4877. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4878. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4879. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4880. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4881. Matrix.Zero(), Matrix.Zero(),
  4882. Matrix.Zero(), Matrix.Zero(),
  4883. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4884. return Tmp;
  4885. }());
  4886. BABYLON.Tmp = Tmp;
  4887. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4888. var MathTmp = /** @class */ (function () {
  4889. function MathTmp() {
  4890. }
  4891. MathTmp.Vector3 = [Vector3.Zero()];
  4892. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4893. MathTmp.Quaternion = [Quaternion.Zero()];
  4894. return MathTmp;
  4895. }());
  4896. })(BABYLON || (BABYLON = {}));
  4897. //# sourceMappingURL=babylon.math.js.map
  4898. var BABYLON;
  4899. (function (BABYLON) {
  4900. var Scalar = /** @class */ (function () {
  4901. function Scalar() {
  4902. }
  4903. /**
  4904. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4905. */
  4906. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4907. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4908. var num = a - b;
  4909. return -epsilon <= num && num <= epsilon;
  4910. };
  4911. /**
  4912. * Returns a string : the upper case translation of the number i to hexadecimal.
  4913. */
  4914. Scalar.ToHex = function (i) {
  4915. var str = i.toString(16);
  4916. if (i <= 15) {
  4917. return ("0" + str).toUpperCase();
  4918. }
  4919. return str.toUpperCase();
  4920. };
  4921. /**
  4922. * Returns -1 if value is negative and +1 is value is positive.
  4923. * Returns the value itself if it's equal to zero.
  4924. */
  4925. Scalar.Sign = function (value) {
  4926. value = +value; // convert to a number
  4927. if (value === 0 || isNaN(value))
  4928. return value;
  4929. return value > 0 ? 1 : -1;
  4930. };
  4931. /**
  4932. * Returns the value itself if it's between min and max.
  4933. * Returns min if the value is lower than min.
  4934. * Returns max if the value is greater than max.
  4935. */
  4936. Scalar.Clamp = function (value, min, max) {
  4937. if (min === void 0) { min = 0; }
  4938. if (max === void 0) { max = 1; }
  4939. return Math.min(max, Math.max(min, value));
  4940. };
  4941. /**
  4942. * Returns the log2 of value.
  4943. */
  4944. Scalar.Log2 = function (value) {
  4945. return Math.log(value) * Math.LOG2E;
  4946. };
  4947. /**
  4948. * Loops the value, so that it is never larger than length and never smaller than 0.
  4949. *
  4950. * This is similar to the modulo operator but it works with floating point numbers.
  4951. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4952. * With t = 5 and length = 2.5, the result would be 0.0.
  4953. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4954. */
  4955. Scalar.Repeat = function (value, length) {
  4956. return value - Math.floor(value / length) * length;
  4957. };
  4958. /**
  4959. * Normalize the value between 0.0 and 1.0 using min and max values
  4960. */
  4961. Scalar.Normalize = function (value, min, max) {
  4962. return (value - min) / (max - min);
  4963. };
  4964. /**
  4965. * Denormalize the value from 0.0 and 1.0 using min and max values
  4966. */
  4967. Scalar.Denormalize = function (normalized, min, max) {
  4968. return (normalized * (max - min) + min);
  4969. };
  4970. /**
  4971. * Calculates the shortest difference between two given angles given in degrees.
  4972. */
  4973. Scalar.DeltaAngle = function (current, target) {
  4974. var num = Scalar.Repeat(target - current, 360.0);
  4975. if (num > 180.0) {
  4976. num -= 360.0;
  4977. }
  4978. return num;
  4979. };
  4980. /**
  4981. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4982. *
  4983. * The returned value will move back and forth between 0 and length
  4984. */
  4985. Scalar.PingPong = function (tx, length) {
  4986. var t = Scalar.Repeat(tx, length * 2.0);
  4987. return length - Math.abs(t - length);
  4988. };
  4989. /**
  4990. * Interpolates between min and max with smoothing at the limits.
  4991. *
  4992. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4993. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4994. */
  4995. Scalar.SmoothStep = function (from, to, tx) {
  4996. var t = Scalar.Clamp(tx);
  4997. t = -2.0 * t * t * t + 3.0 * t * t;
  4998. return to * t + from * (1.0 - t);
  4999. };
  5000. /**
  5001. * Moves a value current towards target.
  5002. *
  5003. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5004. * Negative values of maxDelta pushes the value away from target.
  5005. */
  5006. Scalar.MoveTowards = function (current, target, maxDelta) {
  5007. var result = 0;
  5008. if (Math.abs(target - current) <= maxDelta) {
  5009. result = target;
  5010. }
  5011. else {
  5012. result = current + Scalar.Sign(target - current) * maxDelta;
  5013. }
  5014. return result;
  5015. };
  5016. /**
  5017. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5018. *
  5019. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5020. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5021. */
  5022. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5023. var num = Scalar.DeltaAngle(current, target);
  5024. var result = 0;
  5025. if (-maxDelta < num && num < maxDelta) {
  5026. result = target;
  5027. }
  5028. else {
  5029. target = current + num;
  5030. result = Scalar.MoveTowards(current, target, maxDelta);
  5031. }
  5032. return result;
  5033. };
  5034. /**
  5035. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5036. */
  5037. Scalar.Lerp = function (start, end, amount) {
  5038. return start + ((end - start) * amount);
  5039. };
  5040. /**
  5041. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5042. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5043. */
  5044. Scalar.LerpAngle = function (start, end, amount) {
  5045. var num = Scalar.Repeat(end - start, 360.0);
  5046. if (num > 180.0) {
  5047. num -= 360.0;
  5048. }
  5049. return start + num * Scalar.Clamp(amount);
  5050. };
  5051. /**
  5052. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5053. */
  5054. Scalar.InverseLerp = function (a, b, value) {
  5055. var result = 0;
  5056. if (a != b) {
  5057. result = Scalar.Clamp((value - a) / (b - a));
  5058. }
  5059. else {
  5060. result = 0.0;
  5061. }
  5062. return result;
  5063. };
  5064. /**
  5065. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5066. */
  5067. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5068. var squared = amount * amount;
  5069. var cubed = amount * squared;
  5070. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5071. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5072. var part3 = (cubed - (2.0 * squared)) + amount;
  5073. var part4 = cubed - squared;
  5074. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5075. };
  5076. /**
  5077. * Returns a random float number between and min and max values
  5078. */
  5079. Scalar.RandomRange = function (min, max) {
  5080. if (min === max)
  5081. return min;
  5082. return ((Math.random() * (max - min)) + min);
  5083. };
  5084. /**
  5085. * This function returns percentage of a number in a given range.
  5086. *
  5087. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5088. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5089. */
  5090. Scalar.RangeToPercent = function (number, min, max) {
  5091. return ((number - min) / (max - min));
  5092. };
  5093. /**
  5094. * This function returns number that corresponds to the percentage in a given range.
  5095. *
  5096. * PercentToRange(0.34,0,100) will return 34.
  5097. */
  5098. Scalar.PercentToRange = function (percent, min, max) {
  5099. return ((max - min) * percent + min);
  5100. };
  5101. return Scalar;
  5102. }());
  5103. BABYLON.Scalar = Scalar;
  5104. })(BABYLON || (BABYLON = {}));
  5105. //# sourceMappingURL=babylon.math.scalar.js.map
  5106. //# sourceMappingURL=babylon.mixins.js.map
  5107. var BABYLON;
  5108. (function (BABYLON) {
  5109. var __decoratorInitialStore = {};
  5110. var __mergedStore = {};
  5111. var _copySource = function (creationFunction, source, instanciate) {
  5112. var destination = creationFunction();
  5113. // Tags
  5114. if (BABYLON.Tags) {
  5115. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5116. }
  5117. var classStore = getMergedStore(destination);
  5118. // Properties
  5119. for (var property in classStore) {
  5120. var propertyDescriptor = classStore[property];
  5121. var sourceProperty = source[property];
  5122. var propertyType = propertyDescriptor.type;
  5123. if (sourceProperty !== undefined && sourceProperty !== null) {
  5124. switch (propertyType) {
  5125. case 0: // Value
  5126. case 6:// Mesh reference
  5127. destination[property] = sourceProperty;
  5128. break;
  5129. case 1:// Texture
  5130. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5131. break;
  5132. case 2: // Color3
  5133. case 3: // FresnelParameters
  5134. case 4: // Vector2
  5135. case 5: // Vector3
  5136. case 7:// Color Curves
  5137. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5138. break;
  5139. }
  5140. }
  5141. }
  5142. return destination;
  5143. };
  5144. function getDirectStore(target) {
  5145. var classKey = target.getClassName();
  5146. if (!__decoratorInitialStore[classKey]) {
  5147. __decoratorInitialStore[classKey] = {};
  5148. }
  5149. return __decoratorInitialStore[classKey];
  5150. }
  5151. /**
  5152. * Return the list of properties flagged as serializable
  5153. * @param target: host object
  5154. */
  5155. function getMergedStore(target) {
  5156. var classKey = target.getClassName();
  5157. if (__mergedStore[classKey]) {
  5158. return __mergedStore[classKey];
  5159. }
  5160. __mergedStore[classKey] = {};
  5161. var store = __mergedStore[classKey];
  5162. var currentTarget = target;
  5163. var currentKey = classKey;
  5164. while (currentKey) {
  5165. var initialStore = __decoratorInitialStore[currentKey];
  5166. for (var property in initialStore) {
  5167. store[property] = initialStore[property];
  5168. }
  5169. var parent_1 = void 0;
  5170. var done = false;
  5171. do {
  5172. parent_1 = Object.getPrototypeOf(currentTarget);
  5173. if (!parent_1.getClassName) {
  5174. done = true;
  5175. break;
  5176. }
  5177. if (parent_1.getClassName() !== currentKey) {
  5178. break;
  5179. }
  5180. currentTarget = parent_1;
  5181. } while (parent_1);
  5182. if (done) {
  5183. break;
  5184. }
  5185. currentKey = parent_1.getClassName();
  5186. currentTarget = parent_1;
  5187. }
  5188. return store;
  5189. }
  5190. function generateSerializableMember(type, sourceName) {
  5191. return function (target, propertyKey) {
  5192. var classStore = getDirectStore(target);
  5193. if (!classStore[propertyKey]) {
  5194. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5195. }
  5196. };
  5197. }
  5198. function generateExpandMember(setCallback, targetKey) {
  5199. if (targetKey === void 0) { targetKey = null; }
  5200. return function (target, propertyKey) {
  5201. var key = targetKey || ("_" + propertyKey);
  5202. Object.defineProperty(target, propertyKey, {
  5203. get: function () {
  5204. return this[key];
  5205. },
  5206. set: function (value) {
  5207. if (this[key] === value) {
  5208. return;
  5209. }
  5210. this[key] = value;
  5211. target[setCallback].apply(this);
  5212. },
  5213. enumerable: true,
  5214. configurable: true
  5215. });
  5216. };
  5217. }
  5218. function expandToProperty(callback, targetKey) {
  5219. if (targetKey === void 0) { targetKey = null; }
  5220. return generateExpandMember(callback, targetKey);
  5221. }
  5222. BABYLON.expandToProperty = expandToProperty;
  5223. function serialize(sourceName) {
  5224. return generateSerializableMember(0, sourceName); // value member
  5225. }
  5226. BABYLON.serialize = serialize;
  5227. function serializeAsTexture(sourceName) {
  5228. return generateSerializableMember(1, sourceName); // texture member
  5229. }
  5230. BABYLON.serializeAsTexture = serializeAsTexture;
  5231. function serializeAsColor3(sourceName) {
  5232. return generateSerializableMember(2, sourceName); // color3 member
  5233. }
  5234. BABYLON.serializeAsColor3 = serializeAsColor3;
  5235. function serializeAsFresnelParameters(sourceName) {
  5236. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5237. }
  5238. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5239. function serializeAsVector2(sourceName) {
  5240. return generateSerializableMember(4, sourceName); // vector2 member
  5241. }
  5242. BABYLON.serializeAsVector2 = serializeAsVector2;
  5243. function serializeAsVector3(sourceName) {
  5244. return generateSerializableMember(5, sourceName); // vector3 member
  5245. }
  5246. BABYLON.serializeAsVector3 = serializeAsVector3;
  5247. function serializeAsMeshReference(sourceName) {
  5248. return generateSerializableMember(6, sourceName); // mesh reference member
  5249. }
  5250. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5251. function serializeAsColorCurves(sourceName) {
  5252. return generateSerializableMember(7, sourceName); // color curves
  5253. }
  5254. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5255. function serializeAsColor4(sourceName) {
  5256. return generateSerializableMember(8, sourceName); // color 4
  5257. }
  5258. BABYLON.serializeAsColor4 = serializeAsColor4;
  5259. function serializeAsImageProcessingConfiguration(sourceName) {
  5260. return generateSerializableMember(9, sourceName); // image processing
  5261. }
  5262. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5263. var SerializationHelper = /** @class */ (function () {
  5264. function SerializationHelper() {
  5265. }
  5266. SerializationHelper.Serialize = function (entity, serializationObject) {
  5267. if (!serializationObject) {
  5268. serializationObject = {};
  5269. }
  5270. // Tags
  5271. if (BABYLON.Tags) {
  5272. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5273. }
  5274. var serializedProperties = getMergedStore(entity);
  5275. // Properties
  5276. for (var property in serializedProperties) {
  5277. var propertyDescriptor = serializedProperties[property];
  5278. var targetPropertyName = propertyDescriptor.sourceName || property;
  5279. var propertyType = propertyDescriptor.type;
  5280. var sourceProperty = entity[property];
  5281. if (sourceProperty !== undefined && sourceProperty !== null) {
  5282. switch (propertyType) {
  5283. case 0:// Value
  5284. serializationObject[targetPropertyName] = sourceProperty;
  5285. break;
  5286. case 1:// Texture
  5287. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5288. break;
  5289. case 2:// Color3
  5290. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5291. break;
  5292. case 3:// FresnelParameters
  5293. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5294. break;
  5295. case 4:// Vector2
  5296. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5297. break;
  5298. case 5:// Vector3
  5299. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5300. break;
  5301. case 6:// Mesh reference
  5302. serializationObject[targetPropertyName] = sourceProperty.id;
  5303. break;
  5304. case 7:// Color Curves
  5305. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5306. break;
  5307. case 8:// Color 4
  5308. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5309. break;
  5310. case 9:// Image Processing
  5311. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5312. break;
  5313. }
  5314. }
  5315. }
  5316. return serializationObject;
  5317. };
  5318. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5319. if (rootUrl === void 0) { rootUrl = null; }
  5320. var destination = creationFunction();
  5321. if (!rootUrl) {
  5322. rootUrl = "";
  5323. }
  5324. // Tags
  5325. if (BABYLON.Tags) {
  5326. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5327. }
  5328. var classStore = getMergedStore(destination);
  5329. // Properties
  5330. for (var property in classStore) {
  5331. var propertyDescriptor = classStore[property];
  5332. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5333. var propertyType = propertyDescriptor.type;
  5334. if (sourceProperty !== undefined && sourceProperty !== null) {
  5335. var dest = destination;
  5336. switch (propertyType) {
  5337. case 0:// Value
  5338. dest[property] = sourceProperty;
  5339. break;
  5340. case 1:// Texture
  5341. if (scene) {
  5342. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5343. }
  5344. break;
  5345. case 2:// Color3
  5346. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5347. break;
  5348. case 3:// FresnelParameters
  5349. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5350. break;
  5351. case 4:// Vector2
  5352. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5353. break;
  5354. case 5:// Vector3
  5355. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5356. break;
  5357. case 6:// Mesh reference
  5358. if (scene) {
  5359. dest[property] = scene.getLastMeshByID(sourceProperty);
  5360. }
  5361. break;
  5362. case 7:// Color Curves
  5363. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5364. break;
  5365. case 8:// Color 4
  5366. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5367. break;
  5368. case 9:// Image Processing
  5369. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5370. break;
  5371. }
  5372. }
  5373. }
  5374. return destination;
  5375. };
  5376. SerializationHelper.Clone = function (creationFunction, source) {
  5377. return _copySource(creationFunction, source, false);
  5378. };
  5379. SerializationHelper.Instanciate = function (creationFunction, source) {
  5380. return _copySource(creationFunction, source, true);
  5381. };
  5382. return SerializationHelper;
  5383. }());
  5384. BABYLON.SerializationHelper = SerializationHelper;
  5385. })(BABYLON || (BABYLON = {}));
  5386. //# sourceMappingURL=babylon.decorators.js.map
  5387. var BABYLON;
  5388. (function (BABYLON) {
  5389. /**
  5390. * A class serves as a medium between the observable and its observers
  5391. */
  5392. var EventState = /** @class */ (function () {
  5393. /**
  5394. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5395. */
  5396. function EventState(mask, skipNextObservers, target, currentTarget) {
  5397. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5398. this.initalize(mask, skipNextObservers, target, currentTarget);
  5399. }
  5400. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5401. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5402. this.mask = mask;
  5403. this.skipNextObservers = skipNextObservers;
  5404. this.target = target;
  5405. this.currentTarget = currentTarget;
  5406. return this;
  5407. };
  5408. return EventState;
  5409. }());
  5410. BABYLON.EventState = EventState;
  5411. /**
  5412. * Represent an Observer registered to a given Observable object.
  5413. */
  5414. var Observer = /** @class */ (function () {
  5415. function Observer(callback, mask, scope) {
  5416. if (scope === void 0) { scope = null; }
  5417. this.callback = callback;
  5418. this.mask = mask;
  5419. this.scope = scope;
  5420. }
  5421. return Observer;
  5422. }());
  5423. BABYLON.Observer = Observer;
  5424. /**
  5425. * Represent a list of observers registered to multiple Observables object.
  5426. */
  5427. var MultiObserver = /** @class */ (function () {
  5428. function MultiObserver() {
  5429. }
  5430. MultiObserver.prototype.dispose = function () {
  5431. if (this._observers && this._observables) {
  5432. for (var index = 0; index < this._observers.length; index++) {
  5433. this._observables[index].remove(this._observers[index]);
  5434. }
  5435. }
  5436. this._observers = null;
  5437. this._observables = null;
  5438. };
  5439. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5440. if (mask === void 0) { mask = -1; }
  5441. if (scope === void 0) { scope = null; }
  5442. var result = new MultiObserver();
  5443. result._observers = new Array();
  5444. result._observables = observables;
  5445. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5446. var observable = observables_1[_i];
  5447. var observer = observable.add(callback, mask, false, scope);
  5448. if (observer) {
  5449. result._observers.push(observer);
  5450. }
  5451. }
  5452. return result;
  5453. };
  5454. return MultiObserver;
  5455. }());
  5456. BABYLON.MultiObserver = MultiObserver;
  5457. /**
  5458. * The Observable class is a simple implementation of the Observable pattern.
  5459. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  5460. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5461. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  5462. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  5463. */
  5464. var Observable = /** @class */ (function () {
  5465. function Observable(onObserverAdded) {
  5466. this._observers = new Array();
  5467. this._eventState = new EventState(0);
  5468. if (onObserverAdded) {
  5469. this._onObserverAdded = onObserverAdded;
  5470. }
  5471. }
  5472. /**
  5473. * Create a new Observer with the specified callback
  5474. * @param callback the callback that will be executed for that Observer
  5475. * @param mask the mask used to filter observers
  5476. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  5477. * @param scope optional scope for the callback to be called from
  5478. */
  5479. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5480. if (mask === void 0) { mask = -1; }
  5481. if (insertFirst === void 0) { insertFirst = false; }
  5482. if (scope === void 0) { scope = null; }
  5483. if (!callback) {
  5484. return null;
  5485. }
  5486. var observer = new Observer(callback, mask, scope);
  5487. if (insertFirst) {
  5488. this._observers.unshift(observer);
  5489. }
  5490. else {
  5491. this._observers.push(observer);
  5492. }
  5493. if (this._onObserverAdded) {
  5494. this._onObserverAdded(observer);
  5495. }
  5496. return observer;
  5497. };
  5498. /**
  5499. * Remove an Observer from the Observable object
  5500. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5501. */
  5502. Observable.prototype.remove = function (observer) {
  5503. if (!observer) {
  5504. return false;
  5505. }
  5506. var index = this._observers.indexOf(observer);
  5507. if (index !== -1) {
  5508. this._observers.splice(index, 1);
  5509. return true;
  5510. }
  5511. return false;
  5512. };
  5513. /**
  5514. * Remove a callback from the Observable object
  5515. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5516. */
  5517. Observable.prototype.removeCallback = function (callback) {
  5518. for (var index = 0; index < this._observers.length; index++) {
  5519. if (this._observers[index].callback === callback) {
  5520. this._observers.splice(index, 1);
  5521. return true;
  5522. }
  5523. }
  5524. return false;
  5525. };
  5526. /**
  5527. * Notify all Observers by calling their respective callback with the given data
  5528. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5529. * @param eventData
  5530. * @param mask
  5531. */
  5532. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5533. if (mask === void 0) { mask = -1; }
  5534. var state = this._eventState;
  5535. state.mask = mask;
  5536. state.target = target;
  5537. state.currentTarget = currentTarget;
  5538. state.skipNextObservers = false;
  5539. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5540. var obs = _a[_i];
  5541. if (obs.mask & mask) {
  5542. if (obs.scope) {
  5543. obs.callback.apply(obs.scope, [eventData, state]);
  5544. }
  5545. else {
  5546. obs.callback(eventData, state);
  5547. }
  5548. }
  5549. if (state.skipNextObservers) {
  5550. return false;
  5551. }
  5552. }
  5553. return true;
  5554. };
  5555. /**
  5556. * Notify a specific observer
  5557. * @param eventData
  5558. * @param mask
  5559. */
  5560. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5561. if (mask === void 0) { mask = -1; }
  5562. var state = this._eventState;
  5563. state.mask = mask;
  5564. state.skipNextObservers = false;
  5565. observer.callback(eventData, state);
  5566. };
  5567. /**
  5568. * return true is the Observable has at least one Observer registered
  5569. */
  5570. Observable.prototype.hasObservers = function () {
  5571. return this._observers.length > 0;
  5572. };
  5573. /**
  5574. * Clear the list of observers
  5575. */
  5576. Observable.prototype.clear = function () {
  5577. this._observers = new Array();
  5578. this._onObserverAdded = null;
  5579. };
  5580. /**
  5581. * Clone the current observable
  5582. */
  5583. Observable.prototype.clone = function () {
  5584. var result = new Observable();
  5585. result._observers = this._observers.slice(0);
  5586. return result;
  5587. };
  5588. /**
  5589. * Does this observable handles observer registered with a given mask
  5590. * @param {number} trigger - the mask to be tested
  5591. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5592. **/
  5593. Observable.prototype.hasSpecificMask = function (mask) {
  5594. if (mask === void 0) { mask = -1; }
  5595. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5596. var obs = _a[_i];
  5597. if (obs.mask & mask || obs.mask === mask) {
  5598. return true;
  5599. }
  5600. }
  5601. return false;
  5602. };
  5603. return Observable;
  5604. }());
  5605. BABYLON.Observable = Observable;
  5606. })(BABYLON || (BABYLON = {}));
  5607. //# sourceMappingURL=babylon.observable.js.map
  5608. var BABYLON;
  5609. (function (BABYLON) {
  5610. var SmartArray = /** @class */ (function () {
  5611. function SmartArray(capacity) {
  5612. this.length = 0;
  5613. this._duplicateId = 0;
  5614. this.data = new Array(capacity);
  5615. this._id = SmartArray._GlobalId++;
  5616. }
  5617. SmartArray.prototype.push = function (value) {
  5618. this.data[this.length++] = value;
  5619. if (this.length > this.data.length) {
  5620. this.data.length *= 2;
  5621. }
  5622. if (!value.__smartArrayFlags) {
  5623. value.__smartArrayFlags = {};
  5624. }
  5625. value.__smartArrayFlags[this._id] = this._duplicateId;
  5626. };
  5627. SmartArray.prototype.forEach = function (func) {
  5628. for (var index = 0; index < this.length; index++) {
  5629. func(this.data[index]);
  5630. }
  5631. };
  5632. SmartArray.prototype.pushNoDuplicate = function (value) {
  5633. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5634. return false;
  5635. }
  5636. this.push(value);
  5637. return true;
  5638. };
  5639. SmartArray.prototype.sort = function (compareFn) {
  5640. this.data.sort(compareFn);
  5641. };
  5642. SmartArray.prototype.reset = function () {
  5643. this.length = 0;
  5644. this._duplicateId++;
  5645. };
  5646. SmartArray.prototype.dispose = function () {
  5647. this.reset();
  5648. if (this.data) {
  5649. this.data.length = 0;
  5650. this.data = [];
  5651. }
  5652. };
  5653. SmartArray.prototype.concat = function (array) {
  5654. if (array.length === 0) {
  5655. return;
  5656. }
  5657. if (this.length + array.length > this.data.length) {
  5658. this.data.length = (this.length + array.length) * 2;
  5659. }
  5660. for (var index = 0; index < array.length; index++) {
  5661. this.data[this.length++] = (array.data || array)[index];
  5662. }
  5663. };
  5664. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5665. if (array.length === 0) {
  5666. return;
  5667. }
  5668. if (this.length + array.length > this.data.length) {
  5669. this.data.length = (this.length + array.length) * 2;
  5670. }
  5671. for (var index = 0; index < array.length; index++) {
  5672. var item = (array.data || array)[index];
  5673. this.pushNoDuplicate(item);
  5674. }
  5675. };
  5676. SmartArray.prototype.indexOf = function (value) {
  5677. var position = this.data.indexOf(value);
  5678. if (position >= this.length) {
  5679. return -1;
  5680. }
  5681. return position;
  5682. };
  5683. SmartArray.prototype.contains = function (value) {
  5684. return this.data.indexOf(value) !== -1;
  5685. };
  5686. // Statics
  5687. SmartArray._GlobalId = 0;
  5688. return SmartArray;
  5689. }());
  5690. BABYLON.SmartArray = SmartArray;
  5691. })(BABYLON || (BABYLON = {}));
  5692. //# sourceMappingURL=babylon.smartArray.js.map
  5693. var BABYLON;
  5694. (function (BABYLON) {
  5695. // Screenshots
  5696. var screenshotCanvas;
  5697. var cloneValue = function (source, destinationObject) {
  5698. if (!source)
  5699. return null;
  5700. if (source instanceof BABYLON.Mesh) {
  5701. return null;
  5702. }
  5703. if (source instanceof BABYLON.SubMesh) {
  5704. return source.clone(destinationObject);
  5705. }
  5706. else if (source.clone) {
  5707. return source.clone();
  5708. }
  5709. return null;
  5710. };
  5711. var Tools = /** @class */ (function () {
  5712. function Tools() {
  5713. }
  5714. ;
  5715. /**
  5716. * Interpolates between a and b via alpha
  5717. * @param a The lower value (returned when alpha = 0)
  5718. * @param b The upper value (returned when alpha = 1)
  5719. * @param alpha The interpolation-factor
  5720. * @return The mixed value
  5721. */
  5722. Tools.Mix = function (a, b, alpha) {
  5723. return a * (1 - alpha) + b * alpha;
  5724. };
  5725. Tools.Instantiate = function (className) {
  5726. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5727. return Tools.RegisteredExternalClasses[className];
  5728. }
  5729. var arr = className.split(".");
  5730. var fn = (window || this);
  5731. for (var i = 0, len = arr.length; i < len; i++) {
  5732. fn = fn[arr[i]];
  5733. }
  5734. if (typeof fn !== "function") {
  5735. return null;
  5736. }
  5737. return fn;
  5738. };
  5739. Tools.SetImmediate = function (action) {
  5740. if (window.setImmediate) {
  5741. window.setImmediate(action);
  5742. }
  5743. else {
  5744. setTimeout(action, 1);
  5745. }
  5746. };
  5747. Tools.IsExponentOfTwo = function (value) {
  5748. var count = 1;
  5749. do {
  5750. count *= 2;
  5751. } while (count < value);
  5752. return count === value;
  5753. };
  5754. /**
  5755. * Find the next highest power of two.
  5756. * @param x Number to start search from.
  5757. * @return Next highest power of two.
  5758. */
  5759. Tools.CeilingPOT = function (x) {
  5760. x--;
  5761. x |= x >> 1;
  5762. x |= x >> 2;
  5763. x |= x >> 4;
  5764. x |= x >> 8;
  5765. x |= x >> 16;
  5766. x++;
  5767. return x;
  5768. };
  5769. /**
  5770. * Find the next lowest power of two.
  5771. * @param x Number to start search from.
  5772. * @return Next lowest power of two.
  5773. */
  5774. Tools.FloorPOT = function (x) {
  5775. x = x | (x >> 1);
  5776. x = x | (x >> 2);
  5777. x = x | (x >> 4);
  5778. x = x | (x >> 8);
  5779. x = x | (x >> 16);
  5780. return x - (x >> 1);
  5781. };
  5782. /**
  5783. * Find the nearest power of two.
  5784. * @param x Number to start search from.
  5785. * @return Next nearest power of two.
  5786. */
  5787. Tools.NearestPOT = function (x) {
  5788. var c = Tools.CeilingPOT(x);
  5789. var f = Tools.FloorPOT(x);
  5790. return (c - x) > (x - f) ? f : c;
  5791. };
  5792. Tools.GetExponentOfTwo = function (value, max, mode) {
  5793. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5794. var pot;
  5795. switch (mode) {
  5796. case BABYLON.Engine.SCALEMODE_FLOOR:
  5797. pot = Tools.FloorPOT(value);
  5798. break;
  5799. case BABYLON.Engine.SCALEMODE_NEAREST:
  5800. pot = Tools.NearestPOT(value);
  5801. break;
  5802. case BABYLON.Engine.SCALEMODE_CEILING:
  5803. default:
  5804. pot = Tools.CeilingPOT(value);
  5805. break;
  5806. }
  5807. return Math.min(pot, max);
  5808. };
  5809. Tools.GetFilename = function (path) {
  5810. var index = path.lastIndexOf("/");
  5811. if (index < 0)
  5812. return path;
  5813. return path.substring(index + 1);
  5814. };
  5815. Tools.GetDOMTextContent = function (element) {
  5816. var result = "";
  5817. var child = element.firstChild;
  5818. while (child) {
  5819. if (child.nodeType === 3) {
  5820. result += child.textContent;
  5821. }
  5822. child = child.nextSibling;
  5823. }
  5824. return result;
  5825. };
  5826. Tools.ToDegrees = function (angle) {
  5827. return angle * 180 / Math.PI;
  5828. };
  5829. Tools.ToRadians = function (angle) {
  5830. return angle * Math.PI / 180;
  5831. };
  5832. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5833. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5834. var output = "";
  5835. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5836. var i = 0;
  5837. var bytes = new Uint8Array(buffer);
  5838. while (i < bytes.length) {
  5839. chr1 = bytes[i++];
  5840. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5841. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5842. enc1 = chr1 >> 2;
  5843. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5844. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5845. enc4 = chr3 & 63;
  5846. if (isNaN(chr2)) {
  5847. enc3 = enc4 = 64;
  5848. }
  5849. else if (isNaN(chr3)) {
  5850. enc4 = 64;
  5851. }
  5852. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5853. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5854. }
  5855. return "data:image/png;base64," + output;
  5856. };
  5857. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5858. if (bias === void 0) { bias = null; }
  5859. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5860. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5861. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5862. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5863. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5864. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5865. }
  5866. if (bias) {
  5867. minimum.x -= minimum.x * bias.x + bias.y;
  5868. minimum.y -= minimum.y * bias.x + bias.y;
  5869. minimum.z -= minimum.z * bias.x + bias.y;
  5870. maximum.x += maximum.x * bias.x + bias.y;
  5871. maximum.y += maximum.y * bias.x + bias.y;
  5872. maximum.z += maximum.z * bias.x + bias.y;
  5873. }
  5874. return {
  5875. minimum: minimum,
  5876. maximum: maximum
  5877. };
  5878. };
  5879. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5880. if (bias === void 0) { bias = null; }
  5881. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5882. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5883. if (!stride) {
  5884. stride = 3;
  5885. }
  5886. for (var index = start; index < start + count; index++) {
  5887. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5888. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5889. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5890. }
  5891. if (bias) {
  5892. minimum.x -= minimum.x * bias.x + bias.y;
  5893. minimum.y -= minimum.y * bias.x + bias.y;
  5894. minimum.z -= minimum.z * bias.x + bias.y;
  5895. maximum.x += maximum.x * bias.x + bias.y;
  5896. maximum.y += maximum.y * bias.x + bias.y;
  5897. maximum.z += maximum.z * bias.x + bias.y;
  5898. }
  5899. return {
  5900. minimum: minimum,
  5901. maximum: maximum
  5902. };
  5903. };
  5904. Tools.Vector2ArrayFeeder = function (array) {
  5905. return function (index) {
  5906. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5907. var length = isFloatArray ? array.length / 2 : array.length;
  5908. if (index >= length) {
  5909. return null;
  5910. }
  5911. if (isFloatArray) {
  5912. var fa = array;
  5913. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5914. }
  5915. var a = array;
  5916. return a[index];
  5917. };
  5918. };
  5919. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5920. if (bias === void 0) { bias = null; }
  5921. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5922. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5923. var i = 0;
  5924. var cur = feeder(i++);
  5925. while (cur) {
  5926. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5927. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5928. cur = feeder(i++);
  5929. }
  5930. if (bias) {
  5931. minimum.x -= minimum.x * bias.x + bias.y;
  5932. minimum.y -= minimum.y * bias.x + bias.y;
  5933. maximum.x += maximum.x * bias.x + bias.y;
  5934. maximum.y += maximum.y * bias.x + bias.y;
  5935. }
  5936. return {
  5937. minimum: minimum,
  5938. maximum: maximum
  5939. };
  5940. };
  5941. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5942. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5943. return null;
  5944. return Array.isArray(obj) ? obj : [obj];
  5945. };
  5946. // Misc.
  5947. Tools.GetPointerPrefix = function () {
  5948. var eventPrefix = "pointer";
  5949. // Check if pointer events are supported
  5950. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5951. eventPrefix = "mouse";
  5952. }
  5953. return eventPrefix;
  5954. };
  5955. /**
  5956. * @param func - the function to be called
  5957. * @param requester - the object that will request the next frame. Falls back to window.
  5958. */
  5959. Tools.QueueNewFrame = function (func, requester) {
  5960. if (!Tools.IsWindowObjectExist()) {
  5961. return setTimeout(func, 16);
  5962. }
  5963. if (!requester) {
  5964. requester = window;
  5965. }
  5966. if (requester.requestAnimationFrame) {
  5967. return requester.requestAnimationFrame(func);
  5968. }
  5969. else if (requester.msRequestAnimationFrame) {
  5970. return requester.msRequestAnimationFrame(func);
  5971. }
  5972. else if (requester.webkitRequestAnimationFrame) {
  5973. return requester.webkitRequestAnimationFrame(func);
  5974. }
  5975. else if (requester.mozRequestAnimationFrame) {
  5976. return requester.mozRequestAnimationFrame(func);
  5977. }
  5978. else if (requester.oRequestAnimationFrame) {
  5979. return requester.oRequestAnimationFrame(func);
  5980. }
  5981. else {
  5982. return window.setTimeout(func, 16);
  5983. }
  5984. };
  5985. Tools.RequestFullscreen = function (element) {
  5986. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5987. if (!requestFunction)
  5988. return;
  5989. requestFunction.call(element);
  5990. };
  5991. Tools.ExitFullscreen = function () {
  5992. if (document.exitFullscreen) {
  5993. document.exitFullscreen();
  5994. }
  5995. else if (document.mozCancelFullScreen) {
  5996. document.mozCancelFullScreen();
  5997. }
  5998. else if (document.webkitCancelFullScreen) {
  5999. document.webkitCancelFullScreen();
  6000. }
  6001. else if (document.msCancelFullScreen) {
  6002. document.msCancelFullScreen();
  6003. }
  6004. };
  6005. Tools.SetCorsBehavior = function (url, img) {
  6006. if (Tools.CorsBehavior) {
  6007. switch (typeof (Tools.CorsBehavior)) {
  6008. case "function":
  6009. var result = Tools.CorsBehavior(url);
  6010. if (result) {
  6011. img.crossOrigin = result;
  6012. }
  6013. break;
  6014. case "string":
  6015. default:
  6016. img.crossOrigin = Tools.CorsBehavior;
  6017. break;
  6018. }
  6019. }
  6020. };
  6021. // External files
  6022. Tools.CleanUrl = function (url) {
  6023. url = url.replace(/#/mg, "%23");
  6024. return url;
  6025. };
  6026. Tools.LoadImage = function (url, onLoad, onError, database) {
  6027. if (url instanceof ArrayBuffer) {
  6028. url = Tools.EncodeArrayBufferTobase64(url);
  6029. }
  6030. url = Tools.CleanUrl(url);
  6031. url = Tools.PreprocessUrl(url);
  6032. var img = new Image();
  6033. if (url.substr(0, 5) !== "data:") {
  6034. Tools.SetCorsBehavior(url, img);
  6035. }
  6036. img.onload = function () {
  6037. onLoad(img);
  6038. };
  6039. img.onerror = function (err) {
  6040. Tools.Error("Error while trying to load image: " + url);
  6041. if (Tools.UseFallbackTexture) {
  6042. img.src = Tools.fallbackTexture;
  6043. onLoad(img);
  6044. }
  6045. else {
  6046. onError("Error while trying to load image: " + url, err);
  6047. }
  6048. };
  6049. var noIndexedDB = function () {
  6050. img.src = url;
  6051. };
  6052. var loadFromIndexedDB = function () {
  6053. if (database) {
  6054. database.loadImageFromDB(url, img);
  6055. }
  6056. };
  6057. //ANY database to do!
  6058. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6059. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6060. }
  6061. else {
  6062. if (url.indexOf("file:") !== 0) {
  6063. noIndexedDB();
  6064. }
  6065. else {
  6066. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6067. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6068. try {
  6069. var blobURL;
  6070. try {
  6071. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6072. }
  6073. catch (ex) {
  6074. // Chrome doesn't support oneTimeOnly parameter
  6075. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6076. }
  6077. img.src = blobURL;
  6078. }
  6079. catch (e) {
  6080. img.src = "";
  6081. }
  6082. }
  6083. else {
  6084. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6085. img.src = Tools.fallbackTexture;
  6086. }
  6087. }
  6088. }
  6089. return img;
  6090. };
  6091. //ANY
  6092. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6093. url = Tools.CleanUrl(url);
  6094. url = Tools.PreprocessUrl(url);
  6095. var request = null;
  6096. var noIndexedDB = function () {
  6097. request = new XMLHttpRequest();
  6098. var loadUrl = Tools.BaseUrl + url;
  6099. request.open('GET', loadUrl, true);
  6100. if (useArrayBuffer) {
  6101. request.responseType = "arraybuffer";
  6102. }
  6103. if (progressCallBack) {
  6104. request.onprogress = progressCallBack;
  6105. }
  6106. request.onreadystatechange = function () {
  6107. var req = request;
  6108. // In case of undefined state in some browsers.
  6109. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6110. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6111. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6112. callback(!useArrayBuffer ? req.responseText : req.response);
  6113. }
  6114. else {
  6115. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6116. if (onError) {
  6117. onError(req, e);
  6118. }
  6119. else {
  6120. throw e;
  6121. }
  6122. }
  6123. }
  6124. };
  6125. request.send(null);
  6126. };
  6127. var loadFromIndexedDB = function () {
  6128. if (database) {
  6129. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6130. }
  6131. };
  6132. if (url.indexOf("file:") !== -1) {
  6133. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6134. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6135. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6136. }
  6137. else {
  6138. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6139. if (onError) {
  6140. var e = new Error(errorMessage);
  6141. onError(undefined, e);
  6142. }
  6143. else {
  6144. Tools.Error(errorMessage);
  6145. }
  6146. }
  6147. }
  6148. else {
  6149. // Caching all files
  6150. if (database && database.enableSceneOffline) {
  6151. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6152. }
  6153. else {
  6154. noIndexedDB();
  6155. }
  6156. }
  6157. return request;
  6158. };
  6159. /**
  6160. * Load a script (identified by an url). When the url returns, the
  6161. * content of this file is added into a new script element, attached to the DOM (body element)
  6162. */
  6163. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6164. var head = document.getElementsByTagName('head')[0];
  6165. var script = document.createElement('script');
  6166. script.type = 'text/javascript';
  6167. script.src = scriptUrl;
  6168. script.onload = function () {
  6169. if (onSuccess) {
  6170. onSuccess();
  6171. }
  6172. };
  6173. script.onerror = function (e) {
  6174. if (onError) {
  6175. onError("Unable to load script", e);
  6176. }
  6177. };
  6178. head.appendChild(script);
  6179. };
  6180. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6181. var reader = new FileReader();
  6182. reader.onload = function (e) {
  6183. //target doesn't have result from ts 1.3
  6184. callback(e.target['result']);
  6185. };
  6186. reader.onprogress = progressCallback;
  6187. reader.readAsDataURL(fileToLoad);
  6188. };
  6189. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6190. var reader = new FileReader();
  6191. reader.onerror = function (e) {
  6192. Tools.Log("Error while reading file: " + fileToLoad.name);
  6193. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6194. };
  6195. reader.onload = function (e) {
  6196. //target doesn't have result from ts 1.3
  6197. callback(e.target['result']);
  6198. };
  6199. if (progressCallBack) {
  6200. reader.onprogress = progressCallBack;
  6201. }
  6202. if (!useArrayBuffer) {
  6203. // Asynchronous read
  6204. reader.readAsText(fileToLoad);
  6205. }
  6206. else {
  6207. reader.readAsArrayBuffer(fileToLoad);
  6208. }
  6209. };
  6210. //returns a downloadable url to a file content.
  6211. Tools.FileAsURL = function (content) {
  6212. var fileBlob = new Blob([content]);
  6213. var url = window.URL || window.webkitURL;
  6214. var link = url.createObjectURL(fileBlob);
  6215. return link;
  6216. };
  6217. // Misc.
  6218. Tools.Format = function (value, decimals) {
  6219. if (decimals === void 0) { decimals = 2; }
  6220. return value.toFixed(decimals);
  6221. };
  6222. Tools.CheckExtends = function (v, min, max) {
  6223. if (v.x < min.x)
  6224. min.x = v.x;
  6225. if (v.y < min.y)
  6226. min.y = v.y;
  6227. if (v.z < min.z)
  6228. min.z = v.z;
  6229. if (v.x > max.x)
  6230. max.x = v.x;
  6231. if (v.y > max.y)
  6232. max.y = v.y;
  6233. if (v.z > max.z)
  6234. max.z = v.z;
  6235. };
  6236. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6237. for (var prop in source) {
  6238. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6239. continue;
  6240. }
  6241. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6242. continue;
  6243. }
  6244. var sourceValue = source[prop];
  6245. var typeOfSourceValue = typeof sourceValue;
  6246. if (typeOfSourceValue === "function") {
  6247. continue;
  6248. }
  6249. if (typeOfSourceValue === "object") {
  6250. if (sourceValue instanceof Array) {
  6251. destination[prop] = [];
  6252. if (sourceValue.length > 0) {
  6253. if (typeof sourceValue[0] == "object") {
  6254. for (var index = 0; index < sourceValue.length; index++) {
  6255. var clonedValue = cloneValue(sourceValue[index], destination);
  6256. if (destination[prop].indexOf(clonedValue) === -1) {
  6257. destination[prop].push(clonedValue);
  6258. }
  6259. }
  6260. }
  6261. else {
  6262. destination[prop] = sourceValue.slice(0);
  6263. }
  6264. }
  6265. }
  6266. else {
  6267. destination[prop] = cloneValue(sourceValue, destination);
  6268. }
  6269. }
  6270. else {
  6271. destination[prop] = sourceValue;
  6272. }
  6273. }
  6274. };
  6275. Tools.IsEmpty = function (obj) {
  6276. for (var i in obj) {
  6277. if (obj.hasOwnProperty(i)) {
  6278. return false;
  6279. }
  6280. }
  6281. return true;
  6282. };
  6283. Tools.RegisterTopRootEvents = function (events) {
  6284. for (var index = 0; index < events.length; index++) {
  6285. var event = events[index];
  6286. window.addEventListener(event.name, event.handler, false);
  6287. try {
  6288. if (window.parent) {
  6289. window.parent.addEventListener(event.name, event.handler, false);
  6290. }
  6291. }
  6292. catch (e) {
  6293. // Silently fails...
  6294. }
  6295. }
  6296. };
  6297. Tools.UnregisterTopRootEvents = function (events) {
  6298. for (var index = 0; index < events.length; index++) {
  6299. var event = events[index];
  6300. window.removeEventListener(event.name, event.handler);
  6301. try {
  6302. if (window.parent) {
  6303. window.parent.removeEventListener(event.name, event.handler);
  6304. }
  6305. }
  6306. catch (e) {
  6307. // Silently fails...
  6308. }
  6309. }
  6310. };
  6311. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6312. if (mimeType === void 0) { mimeType = "image/png"; }
  6313. // Read the contents of the framebuffer
  6314. var numberOfChannelsByLine = width * 4;
  6315. var halfHeight = height / 2;
  6316. //Reading datas from WebGL
  6317. var data = engine.readPixels(0, 0, width, height);
  6318. //To flip image on Y axis.
  6319. for (var i = 0; i < halfHeight; i++) {
  6320. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6321. var currentCell = j + i * numberOfChannelsByLine;
  6322. var targetLine = height - i - 1;
  6323. var targetCell = j + targetLine * numberOfChannelsByLine;
  6324. var temp = data[currentCell];
  6325. data[currentCell] = data[targetCell];
  6326. data[targetCell] = temp;
  6327. }
  6328. }
  6329. // Create a 2D canvas to store the result
  6330. if (!screenshotCanvas) {
  6331. screenshotCanvas = document.createElement('canvas');
  6332. }
  6333. screenshotCanvas.width = width;
  6334. screenshotCanvas.height = height;
  6335. var context = screenshotCanvas.getContext('2d');
  6336. if (context) {
  6337. // Copy the pixels to a 2D canvas
  6338. var imageData = context.createImageData(width, height);
  6339. var castData = (imageData.data);
  6340. castData.set(data);
  6341. context.putImageData(imageData, 0, 0);
  6342. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6343. }
  6344. };
  6345. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6346. if (mimeType === void 0) { mimeType = "image/png"; }
  6347. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6348. if (successCallback) {
  6349. successCallback(base64Image);
  6350. }
  6351. else {
  6352. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6353. if (("download" in document.createElement("a"))) {
  6354. var a = window.document.createElement("a");
  6355. a.href = base64Image;
  6356. var date = new Date();
  6357. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6358. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6359. window.document.body.appendChild(a);
  6360. a.addEventListener("click", function () {
  6361. if (a.parentElement) {
  6362. a.parentElement.removeChild(a);
  6363. }
  6364. });
  6365. a.click();
  6366. //Or opening a new tab with the image if it is not possible to automatically start download.
  6367. }
  6368. else {
  6369. var newWindow = window.open("");
  6370. var img = newWindow.document.createElement("img");
  6371. img.src = base64Image;
  6372. newWindow.document.body.appendChild(img);
  6373. }
  6374. }
  6375. };
  6376. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6377. if (mimeType === void 0) { mimeType = "image/png"; }
  6378. var width;
  6379. var height;
  6380. // If a precision value is specified
  6381. if (size.precision) {
  6382. width = Math.round(engine.getRenderWidth() * size.precision);
  6383. height = Math.round(width / engine.getAspectRatio(camera));
  6384. }
  6385. else if (size.width && size.height) {
  6386. width = size.width;
  6387. height = size.height;
  6388. }
  6389. else if (size.width && !size.height) {
  6390. width = size.width;
  6391. height = Math.round(width / engine.getAspectRatio(camera));
  6392. }
  6393. else if (size.height && !size.width) {
  6394. height = size.height;
  6395. width = Math.round(height * engine.getAspectRatio(camera));
  6396. }
  6397. else if (!isNaN(size)) {
  6398. height = size;
  6399. width = size;
  6400. }
  6401. else {
  6402. Tools.Error("Invalid 'size' parameter !");
  6403. return;
  6404. }
  6405. if (!screenshotCanvas) {
  6406. screenshotCanvas = document.createElement('canvas');
  6407. }
  6408. screenshotCanvas.width = width;
  6409. screenshotCanvas.height = height;
  6410. var renderContext = screenshotCanvas.getContext("2d");
  6411. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6412. var newWidth = width;
  6413. var newHeight = newWidth / ratio;
  6414. if (newHeight > height) {
  6415. newHeight = height;
  6416. newWidth = newHeight * ratio;
  6417. }
  6418. var offsetX = Math.max(0, width - newWidth) / 2;
  6419. var offsetY = Math.max(0, height - newHeight) / 2;
  6420. var renderingCanvas = engine.getRenderingCanvas();
  6421. if (renderContext && renderingCanvas) {
  6422. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6423. }
  6424. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6425. };
  6426. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6427. if (mimeType === void 0) { mimeType = "image/png"; }
  6428. if (samples === void 0) { samples = 1; }
  6429. var width;
  6430. var height;
  6431. //If a precision value is specified
  6432. if (size.precision) {
  6433. width = Math.round(engine.getRenderWidth() * size.precision);
  6434. height = Math.round(width / engine.getAspectRatio(camera));
  6435. size = { width: width, height: height };
  6436. }
  6437. else if (size.width && size.height) {
  6438. width = size.width;
  6439. height = size.height;
  6440. }
  6441. else if (size.width && !size.height) {
  6442. width = size.width;
  6443. height = Math.round(width / engine.getAspectRatio(camera));
  6444. size = { width: width, height: height };
  6445. }
  6446. else if (size.height && !size.width) {
  6447. height = size.height;
  6448. width = Math.round(height * engine.getAspectRatio(camera));
  6449. size = { width: width, height: height };
  6450. }
  6451. else if (!isNaN(size)) {
  6452. height = size;
  6453. width = size;
  6454. }
  6455. else {
  6456. Tools.Error("Invalid 'size' parameter !");
  6457. return;
  6458. }
  6459. var scene = camera.getScene();
  6460. var previousCamera = null;
  6461. if (scene.activeCamera !== camera) {
  6462. previousCamera = scene.activeCamera;
  6463. scene.activeCamera = camera;
  6464. }
  6465. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6466. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6467. texture.renderList = null;
  6468. texture.samples = samples;
  6469. texture.onAfterRenderObservable.add(function () {
  6470. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6471. });
  6472. scene.incrementRenderId();
  6473. scene.resetCachedMaterial();
  6474. texture.render(true);
  6475. texture.dispose();
  6476. if (previousCamera) {
  6477. scene.activeCamera = previousCamera;
  6478. }
  6479. camera.getProjectionMatrix(true); // Force cache refresh;
  6480. };
  6481. // XHR response validator for local file scenario
  6482. Tools.ValidateXHRData = function (xhr, dataType) {
  6483. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6484. if (dataType === void 0) { dataType = 7; }
  6485. try {
  6486. if (dataType & 1) {
  6487. if (xhr.responseText && xhr.responseText.length > 0) {
  6488. return true;
  6489. }
  6490. else if (dataType === 1) {
  6491. return false;
  6492. }
  6493. }
  6494. if (dataType & 2) {
  6495. // Check header width and height since there is no "TGA" magic number
  6496. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6497. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6498. return true;
  6499. }
  6500. else if (dataType === 2) {
  6501. return false;
  6502. }
  6503. }
  6504. if (dataType & 4) {
  6505. // Check for the "DDS" magic number
  6506. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6507. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6508. return true;
  6509. }
  6510. else {
  6511. return false;
  6512. }
  6513. }
  6514. }
  6515. catch (e) {
  6516. // Global protection
  6517. }
  6518. return false;
  6519. };
  6520. /**
  6521. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6522. * Be aware Math.random() could cause collisions, but:
  6523. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  6524. */
  6525. Tools.RandomId = function () {
  6526. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6527. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6528. return v.toString(16);
  6529. });
  6530. };
  6531. Object.defineProperty(Tools, "NoneLogLevel", {
  6532. get: function () {
  6533. return Tools._NoneLogLevel;
  6534. },
  6535. enumerable: true,
  6536. configurable: true
  6537. });
  6538. Object.defineProperty(Tools, "MessageLogLevel", {
  6539. get: function () {
  6540. return Tools._MessageLogLevel;
  6541. },
  6542. enumerable: true,
  6543. configurable: true
  6544. });
  6545. Object.defineProperty(Tools, "WarningLogLevel", {
  6546. get: function () {
  6547. return Tools._WarningLogLevel;
  6548. },
  6549. enumerable: true,
  6550. configurable: true
  6551. });
  6552. Object.defineProperty(Tools, "ErrorLogLevel", {
  6553. get: function () {
  6554. return Tools._ErrorLogLevel;
  6555. },
  6556. enumerable: true,
  6557. configurable: true
  6558. });
  6559. Object.defineProperty(Tools, "AllLogLevel", {
  6560. get: function () {
  6561. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6562. },
  6563. enumerable: true,
  6564. configurable: true
  6565. });
  6566. Tools._AddLogEntry = function (entry) {
  6567. Tools._LogCache = entry + Tools._LogCache;
  6568. if (Tools.OnNewCacheEntry) {
  6569. Tools.OnNewCacheEntry(entry);
  6570. }
  6571. };
  6572. Tools._FormatMessage = function (message) {
  6573. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6574. var date = new Date();
  6575. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6576. };
  6577. Tools._LogDisabled = function (message) {
  6578. // nothing to do
  6579. };
  6580. Tools._LogEnabled = function (message) {
  6581. var formattedMessage = Tools._FormatMessage(message);
  6582. console.log("BJS - " + formattedMessage);
  6583. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6584. Tools._AddLogEntry(entry);
  6585. };
  6586. Tools._WarnDisabled = function (message) {
  6587. // nothing to do
  6588. };
  6589. Tools._WarnEnabled = function (message) {
  6590. var formattedMessage = Tools._FormatMessage(message);
  6591. console.warn("BJS - " + formattedMessage);
  6592. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6593. Tools._AddLogEntry(entry);
  6594. };
  6595. Tools._ErrorDisabled = function (message) {
  6596. // nothing to do
  6597. };
  6598. Tools._ErrorEnabled = function (message) {
  6599. Tools.errorsCount++;
  6600. var formattedMessage = Tools._FormatMessage(message);
  6601. console.error("BJS - " + formattedMessage);
  6602. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6603. Tools._AddLogEntry(entry);
  6604. };
  6605. Object.defineProperty(Tools, "LogCache", {
  6606. get: function () {
  6607. return Tools._LogCache;
  6608. },
  6609. enumerable: true,
  6610. configurable: true
  6611. });
  6612. Tools.ClearLogCache = function () {
  6613. Tools._LogCache = "";
  6614. Tools.errorsCount = 0;
  6615. };
  6616. Object.defineProperty(Tools, "LogLevels", {
  6617. set: function (level) {
  6618. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6619. Tools.Log = Tools._LogEnabled;
  6620. }
  6621. else {
  6622. Tools.Log = Tools._LogDisabled;
  6623. }
  6624. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6625. Tools.Warn = Tools._WarnEnabled;
  6626. }
  6627. else {
  6628. Tools.Warn = Tools._WarnDisabled;
  6629. }
  6630. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6631. Tools.Error = Tools._ErrorEnabled;
  6632. }
  6633. else {
  6634. Tools.Error = Tools._ErrorDisabled;
  6635. }
  6636. },
  6637. enumerable: true,
  6638. configurable: true
  6639. });
  6640. Tools.IsWindowObjectExist = function () {
  6641. return (typeof window) !== "undefined";
  6642. };
  6643. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6644. get: function () {
  6645. return Tools._PerformanceNoneLogLevel;
  6646. },
  6647. enumerable: true,
  6648. configurable: true
  6649. });
  6650. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6651. get: function () {
  6652. return Tools._PerformanceUserMarkLogLevel;
  6653. },
  6654. enumerable: true,
  6655. configurable: true
  6656. });
  6657. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6658. get: function () {
  6659. return Tools._PerformanceConsoleLogLevel;
  6660. },
  6661. enumerable: true,
  6662. configurable: true
  6663. });
  6664. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6665. set: function (level) {
  6666. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6667. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6668. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6669. return;
  6670. }
  6671. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6672. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6673. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6674. return;
  6675. }
  6676. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6677. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6678. },
  6679. enumerable: true,
  6680. configurable: true
  6681. });
  6682. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6683. };
  6684. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6685. };
  6686. Tools._StartUserMark = function (counterName, condition) {
  6687. if (condition === void 0) { condition = true; }
  6688. if (!Tools._performance) {
  6689. if (!Tools.IsWindowObjectExist()) {
  6690. return;
  6691. }
  6692. Tools._performance = window.performance;
  6693. }
  6694. if (!condition || !Tools._performance.mark) {
  6695. return;
  6696. }
  6697. Tools._performance.mark(counterName + "-Begin");
  6698. };
  6699. Tools._EndUserMark = function (counterName, condition) {
  6700. if (condition === void 0) { condition = true; }
  6701. if (!condition || !Tools._performance.mark) {
  6702. return;
  6703. }
  6704. Tools._performance.mark(counterName + "-End");
  6705. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6706. };
  6707. Tools._StartPerformanceConsole = function (counterName, condition) {
  6708. if (condition === void 0) { condition = true; }
  6709. if (!condition) {
  6710. return;
  6711. }
  6712. Tools._StartUserMark(counterName, condition);
  6713. if (console.time) {
  6714. console.time(counterName);
  6715. }
  6716. };
  6717. Tools._EndPerformanceConsole = function (counterName, condition) {
  6718. if (condition === void 0) { condition = true; }
  6719. if (!condition) {
  6720. return;
  6721. }
  6722. Tools._EndUserMark(counterName, condition);
  6723. if (console.time) {
  6724. console.timeEnd(counterName);
  6725. }
  6726. };
  6727. Object.defineProperty(Tools, "Now", {
  6728. get: function () {
  6729. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6730. return window.performance.now();
  6731. }
  6732. return new Date().getTime();
  6733. },
  6734. enumerable: true,
  6735. configurable: true
  6736. });
  6737. /**
  6738. * This method will return the name of the class used to create the instance of the given object.
  6739. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6740. * @param object the object to get the class name from
  6741. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6742. */
  6743. Tools.GetClassName = function (object, isType) {
  6744. if (isType === void 0) { isType = false; }
  6745. var name = null;
  6746. if (!isType && object.getClassName) {
  6747. name = object.getClassName();
  6748. }
  6749. else {
  6750. if (object instanceof Object) {
  6751. var classObj = isType ? object : Object.getPrototypeOf(object);
  6752. name = classObj.constructor["__bjsclassName__"];
  6753. }
  6754. if (!name) {
  6755. name = typeof object;
  6756. }
  6757. }
  6758. return name;
  6759. };
  6760. Tools.First = function (array, predicate) {
  6761. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6762. var el = array_1[_i];
  6763. if (predicate(el)) {
  6764. return el;
  6765. }
  6766. }
  6767. return null;
  6768. };
  6769. /**
  6770. * This method will return the name of the full name of the class, including its owning module (if any).
  6771. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6772. * @param object the object to get the class name from
  6773. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6774. */
  6775. Tools.getFullClassName = function (object, isType) {
  6776. if (isType === void 0) { isType = false; }
  6777. var className = null;
  6778. var moduleName = null;
  6779. if (!isType && object.getClassName) {
  6780. className = object.getClassName();
  6781. }
  6782. else {
  6783. if (object instanceof Object) {
  6784. var classObj = isType ? object : Object.getPrototypeOf(object);
  6785. className = classObj.constructor["__bjsclassName__"];
  6786. moduleName = classObj.constructor["__bjsmoduleName__"];
  6787. }
  6788. if (!className) {
  6789. className = typeof object;
  6790. }
  6791. }
  6792. if (!className) {
  6793. return null;
  6794. }
  6795. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6796. };
  6797. /**
  6798. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  6799. * @param array
  6800. */
  6801. Tools.arrayOrStringFeeder = function (array) {
  6802. return function (index) {
  6803. if (index >= array.length) {
  6804. return null;
  6805. }
  6806. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6807. if (val && val.getHashCode) {
  6808. val = val.getHashCode();
  6809. }
  6810. if (typeof val === "string") {
  6811. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6812. }
  6813. return val;
  6814. };
  6815. };
  6816. /**
  6817. * Compute the hashCode of a stream of number
  6818. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6819. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6820. * @return the hash code computed
  6821. */
  6822. Tools.hashCodeFromStream = function (feeder) {
  6823. // Based from here: http://stackoverflow.com/a/7616484/802124
  6824. var hash = 0;
  6825. var index = 0;
  6826. var chr = feeder(index++);
  6827. while (chr != null) {
  6828. hash = ((hash << 5) - hash) + chr;
  6829. hash |= 0; // Convert to 32bit integer
  6830. chr = feeder(index++);
  6831. }
  6832. return hash;
  6833. };
  6834. Tools.BaseUrl = "";
  6835. Tools.CorsBehavior = "anonymous";
  6836. Tools.UseFallbackTexture = true;
  6837. /**
  6838. * Use this object to register external classes like custom textures or material
  6839. * to allow the laoders to instantiate them
  6840. */
  6841. Tools.RegisteredExternalClasses = {};
  6842. // Used in case of a texture loading problem
  6843. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  6844. Tools.PreprocessUrl = function (url) {
  6845. return url;
  6846. };
  6847. // Logs
  6848. Tools._NoneLogLevel = 0;
  6849. Tools._MessageLogLevel = 1;
  6850. Tools._WarningLogLevel = 2;
  6851. Tools._ErrorLogLevel = 4;
  6852. Tools._LogCache = "";
  6853. Tools.errorsCount = 0;
  6854. Tools.Log = Tools._LogEnabled;
  6855. Tools.Warn = Tools._WarnEnabled;
  6856. Tools.Error = Tools._ErrorEnabled;
  6857. // Performances
  6858. Tools._PerformanceNoneLogLevel = 0;
  6859. Tools._PerformanceUserMarkLogLevel = 1;
  6860. Tools._PerformanceConsoleLogLevel = 2;
  6861. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6862. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6863. return Tools;
  6864. }());
  6865. BABYLON.Tools = Tools;
  6866. /**
  6867. * This class is used to track a performance counter which is number based.
  6868. * The user has access to many properties which give statistics of different nature
  6869. *
  6870. * The implementer can track two kinds of Performance Counter: time and count
  6871. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  6872. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  6873. */
  6874. var PerfCounter = /** @class */ (function () {
  6875. function PerfCounter() {
  6876. this._startMonitoringTime = 0;
  6877. this._min = 0;
  6878. this._max = 0;
  6879. this._average = 0;
  6880. this._lastSecAverage = 0;
  6881. this._current = 0;
  6882. this._totalValueCount = 0;
  6883. this._totalAccumulated = 0;
  6884. this._lastSecAccumulated = 0;
  6885. this._lastSecTime = 0;
  6886. this._lastSecValueCount = 0;
  6887. }
  6888. Object.defineProperty(PerfCounter.prototype, "min", {
  6889. /**
  6890. * Returns the smallest value ever
  6891. */
  6892. get: function () {
  6893. return this._min;
  6894. },
  6895. enumerable: true,
  6896. configurable: true
  6897. });
  6898. Object.defineProperty(PerfCounter.prototype, "max", {
  6899. /**
  6900. * Returns the biggest value ever
  6901. */
  6902. get: function () {
  6903. return this._max;
  6904. },
  6905. enumerable: true,
  6906. configurable: true
  6907. });
  6908. Object.defineProperty(PerfCounter.prototype, "average", {
  6909. /**
  6910. * Returns the average value since the performance counter is running
  6911. */
  6912. get: function () {
  6913. return this._average;
  6914. },
  6915. enumerable: true,
  6916. configurable: true
  6917. });
  6918. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6919. /**
  6920. * Returns the average value of the last second the counter was monitored
  6921. */
  6922. get: function () {
  6923. return this._lastSecAverage;
  6924. },
  6925. enumerable: true,
  6926. configurable: true
  6927. });
  6928. Object.defineProperty(PerfCounter.prototype, "current", {
  6929. /**
  6930. * Returns the current value
  6931. */
  6932. get: function () {
  6933. return this._current;
  6934. },
  6935. enumerable: true,
  6936. configurable: true
  6937. });
  6938. Object.defineProperty(PerfCounter.prototype, "total", {
  6939. get: function () {
  6940. return this._totalAccumulated;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Object.defineProperty(PerfCounter.prototype, "count", {
  6946. get: function () {
  6947. return this._totalValueCount;
  6948. },
  6949. enumerable: true,
  6950. configurable: true
  6951. });
  6952. /**
  6953. * Call this method to start monitoring a new frame.
  6954. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  6955. */
  6956. PerfCounter.prototype.fetchNewFrame = function () {
  6957. this._totalValueCount++;
  6958. this._current = 0;
  6959. this._lastSecValueCount++;
  6960. };
  6961. /**
  6962. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6963. * @param newCount the count value to add to the monitored count
  6964. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  6965. */
  6966. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6967. if (!PerfCounter.Enabled) {
  6968. return;
  6969. }
  6970. this._current += newCount;
  6971. if (fetchResult) {
  6972. this._fetchResult();
  6973. }
  6974. };
  6975. /**
  6976. * Start monitoring this performance counter
  6977. */
  6978. PerfCounter.prototype.beginMonitoring = function () {
  6979. if (!PerfCounter.Enabled) {
  6980. return;
  6981. }
  6982. this._startMonitoringTime = Tools.Now;
  6983. };
  6984. /**
  6985. * Compute the time lapsed since the previous beginMonitoring() call.
  6986. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  6987. */
  6988. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6989. if (newFrame === void 0) { newFrame = true; }
  6990. if (!PerfCounter.Enabled) {
  6991. return;
  6992. }
  6993. if (newFrame) {
  6994. this.fetchNewFrame();
  6995. }
  6996. var currentTime = Tools.Now;
  6997. this._current = currentTime - this._startMonitoringTime;
  6998. if (newFrame) {
  6999. this._fetchResult();
  7000. }
  7001. };
  7002. PerfCounter.prototype._fetchResult = function () {
  7003. this._totalAccumulated += this._current;
  7004. this._lastSecAccumulated += this._current;
  7005. // Min/Max update
  7006. this._min = Math.min(this._min, this._current);
  7007. this._max = Math.max(this._max, this._current);
  7008. this._average = this._totalAccumulated / this._totalValueCount;
  7009. // Reset last sec?
  7010. var now = Tools.Now;
  7011. if ((now - this._lastSecTime) > 1000) {
  7012. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7013. this._lastSecTime = now;
  7014. this._lastSecAccumulated = 0;
  7015. this._lastSecValueCount = 0;
  7016. }
  7017. };
  7018. PerfCounter.Enabled = true;
  7019. return PerfCounter;
  7020. }());
  7021. BABYLON.PerfCounter = PerfCounter;
  7022. /**
  7023. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7024. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7025. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7026. * @param name The name of the class, case should be preserved
  7027. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7028. */
  7029. function className(name, module) {
  7030. return function (target) {
  7031. target["__bjsclassName__"] = name;
  7032. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7033. };
  7034. }
  7035. BABYLON.className = className;
  7036. /**
  7037. * An implementation of a loop for asynchronous functions.
  7038. */
  7039. var AsyncLoop = /** @class */ (function () {
  7040. /**
  7041. * Constroctor.
  7042. * @param iterations the number of iterations.
  7043. * @param _fn the function to run each iteration
  7044. * @param _successCallback the callback that will be called upon succesful execution
  7045. * @param offset starting offset.
  7046. */
  7047. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7048. if (offset === void 0) { offset = 0; }
  7049. this.iterations = iterations;
  7050. this._fn = _fn;
  7051. this._successCallback = _successCallback;
  7052. this.index = offset - 1;
  7053. this._done = false;
  7054. }
  7055. /**
  7056. * Execute the next iteration. Must be called after the last iteration was finished.
  7057. */
  7058. AsyncLoop.prototype.executeNext = function () {
  7059. if (!this._done) {
  7060. if (this.index + 1 < this.iterations) {
  7061. ++this.index;
  7062. this._fn(this);
  7063. }
  7064. else {
  7065. this.breakLoop();
  7066. }
  7067. }
  7068. };
  7069. /**
  7070. * Break the loop and run the success callback.
  7071. */
  7072. AsyncLoop.prototype.breakLoop = function () {
  7073. this._done = true;
  7074. this._successCallback();
  7075. };
  7076. /**
  7077. * Helper function
  7078. */
  7079. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7080. if (offset === void 0) { offset = 0; }
  7081. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7082. loop.executeNext();
  7083. return loop;
  7084. };
  7085. /**
  7086. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7087. * @param iterations total number of iterations
  7088. * @param syncedIterations number of synchronous iterations in each async iteration.
  7089. * @param fn the function to call each iteration.
  7090. * @param callback a success call back that will be called when iterating stops.
  7091. * @param breakFunction a break condition (optional)
  7092. * @param timeout timeout settings for the setTimeout function. default - 0.
  7093. * @constructor
  7094. */
  7095. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7096. if (timeout === void 0) { timeout = 0; }
  7097. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7098. if (breakFunction && breakFunction())
  7099. loop.breakLoop();
  7100. else {
  7101. setTimeout(function () {
  7102. for (var i = 0; i < syncedIterations; ++i) {
  7103. var iteration = (loop.index * syncedIterations) + i;
  7104. if (iteration >= iterations)
  7105. break;
  7106. fn(iteration);
  7107. if (breakFunction && breakFunction()) {
  7108. loop.breakLoop();
  7109. break;
  7110. }
  7111. }
  7112. loop.executeNext();
  7113. }, timeout);
  7114. }
  7115. }, callback);
  7116. };
  7117. return AsyncLoop;
  7118. }());
  7119. BABYLON.AsyncLoop = AsyncLoop;
  7120. })(BABYLON || (BABYLON = {}));
  7121. //# sourceMappingURL=babylon.tools.js.map
  7122. var BABYLON;
  7123. (function (BABYLON) {
  7124. var Internals;
  7125. (function (Internals) {
  7126. var _AlphaState = /** @class */ (function () {
  7127. /**
  7128. * Initializes the state.
  7129. */
  7130. function _AlphaState() {
  7131. this._isAlphaBlendDirty = false;
  7132. this._isBlendFunctionParametersDirty = false;
  7133. this._isBlendEquationParametersDirty = false;
  7134. this._isBlendConstantsDirty = false;
  7135. this._alphaBlend = false;
  7136. this._blendFunctionParameters = new Array(4);
  7137. this._blendEquationParameters = new Array(2);
  7138. this._blendConstants = new Array(4);
  7139. this.reset();
  7140. }
  7141. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7142. get: function () {
  7143. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7144. },
  7145. enumerable: true,
  7146. configurable: true
  7147. });
  7148. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7149. get: function () {
  7150. return this._alphaBlend;
  7151. },
  7152. set: function (value) {
  7153. if (this._alphaBlend === value) {
  7154. return;
  7155. }
  7156. this._alphaBlend = value;
  7157. this._isAlphaBlendDirty = true;
  7158. },
  7159. enumerable: true,
  7160. configurable: true
  7161. });
  7162. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7163. if (this._blendConstants[0] === r &&
  7164. this._blendConstants[1] === g &&
  7165. this._blendConstants[2] === b &&
  7166. this._blendConstants[3] === a) {
  7167. return;
  7168. }
  7169. this._blendConstants[0] = r;
  7170. this._blendConstants[1] = g;
  7171. this._blendConstants[2] = b;
  7172. this._blendConstants[3] = a;
  7173. this._isBlendConstantsDirty = true;
  7174. };
  7175. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7176. if (this._blendFunctionParameters[0] === value0 &&
  7177. this._blendFunctionParameters[1] === value1 &&
  7178. this._blendFunctionParameters[2] === value2 &&
  7179. this._blendFunctionParameters[3] === value3) {
  7180. return;
  7181. }
  7182. this._blendFunctionParameters[0] = value0;
  7183. this._blendFunctionParameters[1] = value1;
  7184. this._blendFunctionParameters[2] = value2;
  7185. this._blendFunctionParameters[3] = value3;
  7186. this._isBlendFunctionParametersDirty = true;
  7187. };
  7188. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7189. if (this._blendEquationParameters[0] === rgb &&
  7190. this._blendEquationParameters[1] === alpha) {
  7191. return;
  7192. }
  7193. this._blendEquationParameters[0] = rgb;
  7194. this._blendEquationParameters[1] = alpha;
  7195. this._isBlendEquationParametersDirty = true;
  7196. };
  7197. _AlphaState.prototype.reset = function () {
  7198. this._alphaBlend = false;
  7199. this._blendFunctionParameters[0] = null;
  7200. this._blendFunctionParameters[1] = null;
  7201. this._blendFunctionParameters[2] = null;
  7202. this._blendFunctionParameters[3] = null;
  7203. this._blendEquationParameters[0] = null;
  7204. this._blendEquationParameters[1] = null;
  7205. this._blendConstants[0] = null;
  7206. this._blendConstants[1] = null;
  7207. this._blendConstants[2] = null;
  7208. this._blendConstants[3] = null;
  7209. this._isAlphaBlendDirty = true;
  7210. this._isBlendFunctionParametersDirty = false;
  7211. this._isBlendEquationParametersDirty = false;
  7212. this._isBlendConstantsDirty = false;
  7213. };
  7214. _AlphaState.prototype.apply = function (gl) {
  7215. if (!this.isDirty) {
  7216. return;
  7217. }
  7218. // Alpha blend
  7219. if (this._isAlphaBlendDirty) {
  7220. if (this._alphaBlend) {
  7221. gl.enable(gl.BLEND);
  7222. }
  7223. else {
  7224. gl.disable(gl.BLEND);
  7225. }
  7226. this._isAlphaBlendDirty = false;
  7227. }
  7228. // Alpha function
  7229. if (this._isBlendFunctionParametersDirty) {
  7230. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7231. this._isBlendFunctionParametersDirty = false;
  7232. }
  7233. // Alpha equation
  7234. if (this._isBlendEquationParametersDirty) {
  7235. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7236. this._isBlendEquationParametersDirty = false;
  7237. }
  7238. // Constants
  7239. if (this._isBlendConstantsDirty) {
  7240. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7241. this._isBlendConstantsDirty = false;
  7242. }
  7243. };
  7244. return _AlphaState;
  7245. }());
  7246. Internals._AlphaState = _AlphaState;
  7247. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7248. })(BABYLON || (BABYLON = {}));
  7249. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7250. var BABYLON;
  7251. (function (BABYLON) {
  7252. var Internals;
  7253. (function (Internals) {
  7254. var _DepthCullingState = /** @class */ (function () {
  7255. /**
  7256. * Initializes the state.
  7257. */
  7258. function _DepthCullingState() {
  7259. this._isDepthTestDirty = false;
  7260. this._isDepthMaskDirty = false;
  7261. this._isDepthFuncDirty = false;
  7262. this._isCullFaceDirty = false;
  7263. this._isCullDirty = false;
  7264. this._isZOffsetDirty = false;
  7265. this.reset();
  7266. }
  7267. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7268. get: function () {
  7269. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7270. },
  7271. enumerable: true,
  7272. configurable: true
  7273. });
  7274. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7275. get: function () {
  7276. return this._zOffset;
  7277. },
  7278. set: function (value) {
  7279. if (this._zOffset === value) {
  7280. return;
  7281. }
  7282. this._zOffset = value;
  7283. this._isZOffsetDirty = true;
  7284. },
  7285. enumerable: true,
  7286. configurable: true
  7287. });
  7288. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7289. get: function () {
  7290. return this._cullFace;
  7291. },
  7292. set: function (value) {
  7293. if (this._cullFace === value) {
  7294. return;
  7295. }
  7296. this._cullFace = value;
  7297. this._isCullFaceDirty = true;
  7298. },
  7299. enumerable: true,
  7300. configurable: true
  7301. });
  7302. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7303. get: function () {
  7304. return this._cull;
  7305. },
  7306. set: function (value) {
  7307. if (this._cull === value) {
  7308. return;
  7309. }
  7310. this._cull = value;
  7311. this._isCullDirty = true;
  7312. },
  7313. enumerable: true,
  7314. configurable: true
  7315. });
  7316. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7317. get: function () {
  7318. return this._depthFunc;
  7319. },
  7320. set: function (value) {
  7321. if (this._depthFunc === value) {
  7322. return;
  7323. }
  7324. this._depthFunc = value;
  7325. this._isDepthFuncDirty = true;
  7326. },
  7327. enumerable: true,
  7328. configurable: true
  7329. });
  7330. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7331. get: function () {
  7332. return this._depthMask;
  7333. },
  7334. set: function (value) {
  7335. if (this._depthMask === value) {
  7336. return;
  7337. }
  7338. this._depthMask = value;
  7339. this._isDepthMaskDirty = true;
  7340. },
  7341. enumerable: true,
  7342. configurable: true
  7343. });
  7344. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7345. get: function () {
  7346. return this._depthTest;
  7347. },
  7348. set: function (value) {
  7349. if (this._depthTest === value) {
  7350. return;
  7351. }
  7352. this._depthTest = value;
  7353. this._isDepthTestDirty = true;
  7354. },
  7355. enumerable: true,
  7356. configurable: true
  7357. });
  7358. _DepthCullingState.prototype.reset = function () {
  7359. this._depthMask = true;
  7360. this._depthTest = true;
  7361. this._depthFunc = null;
  7362. this._cullFace = null;
  7363. this._cull = null;
  7364. this._zOffset = 0;
  7365. this._isDepthTestDirty = true;
  7366. this._isDepthMaskDirty = true;
  7367. this._isDepthFuncDirty = false;
  7368. this._isCullFaceDirty = false;
  7369. this._isCullDirty = false;
  7370. this._isZOffsetDirty = false;
  7371. };
  7372. _DepthCullingState.prototype.apply = function (gl) {
  7373. if (!this.isDirty) {
  7374. return;
  7375. }
  7376. // Cull
  7377. if (this._isCullDirty) {
  7378. if (this.cull) {
  7379. gl.enable(gl.CULL_FACE);
  7380. }
  7381. else {
  7382. gl.disable(gl.CULL_FACE);
  7383. }
  7384. this._isCullDirty = false;
  7385. }
  7386. // Cull face
  7387. if (this._isCullFaceDirty) {
  7388. gl.cullFace(this.cullFace);
  7389. this._isCullFaceDirty = false;
  7390. }
  7391. // Depth mask
  7392. if (this._isDepthMaskDirty) {
  7393. gl.depthMask(this.depthMask);
  7394. this._isDepthMaskDirty = false;
  7395. }
  7396. // Depth test
  7397. if (this._isDepthTestDirty) {
  7398. if (this.depthTest) {
  7399. gl.enable(gl.DEPTH_TEST);
  7400. }
  7401. else {
  7402. gl.disable(gl.DEPTH_TEST);
  7403. }
  7404. this._isDepthTestDirty = false;
  7405. }
  7406. // Depth func
  7407. if (this._isDepthFuncDirty) {
  7408. gl.depthFunc(this.depthFunc);
  7409. this._isDepthFuncDirty = false;
  7410. }
  7411. // zOffset
  7412. if (this._isZOffsetDirty) {
  7413. if (this.zOffset) {
  7414. gl.enable(gl.POLYGON_OFFSET_FILL);
  7415. gl.polygonOffset(this.zOffset, 0);
  7416. }
  7417. else {
  7418. gl.disable(gl.POLYGON_OFFSET_FILL);
  7419. }
  7420. this._isZOffsetDirty = false;
  7421. }
  7422. };
  7423. return _DepthCullingState;
  7424. }());
  7425. Internals._DepthCullingState = _DepthCullingState;
  7426. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7427. })(BABYLON || (BABYLON = {}));
  7428. //# sourceMappingURL=babylon.depthCullingState.js.map
  7429. var BABYLON;
  7430. (function (BABYLON) {
  7431. var Internals;
  7432. (function (Internals) {
  7433. var _StencilState = /** @class */ (function () {
  7434. function _StencilState() {
  7435. this._isStencilTestDirty = false;
  7436. this._isStencilMaskDirty = false;
  7437. this._isStencilFuncDirty = false;
  7438. this._isStencilOpDirty = false;
  7439. this.reset();
  7440. }
  7441. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7442. get: function () {
  7443. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7444. },
  7445. enumerable: true,
  7446. configurable: true
  7447. });
  7448. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7449. get: function () {
  7450. return this._stencilFunc;
  7451. },
  7452. set: function (value) {
  7453. if (this._stencilFunc === value) {
  7454. return;
  7455. }
  7456. this._stencilFunc = value;
  7457. this._isStencilFuncDirty = true;
  7458. },
  7459. enumerable: true,
  7460. configurable: true
  7461. });
  7462. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7463. get: function () {
  7464. return this._stencilFuncRef;
  7465. },
  7466. set: function (value) {
  7467. if (this._stencilFuncRef === value) {
  7468. return;
  7469. }
  7470. this._stencilFuncRef = value;
  7471. this._isStencilFuncDirty = true;
  7472. },
  7473. enumerable: true,
  7474. configurable: true
  7475. });
  7476. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7477. get: function () {
  7478. return this._stencilFuncMask;
  7479. },
  7480. set: function (value) {
  7481. if (this._stencilFuncMask === value) {
  7482. return;
  7483. }
  7484. this._stencilFuncMask = value;
  7485. this._isStencilFuncDirty = true;
  7486. },
  7487. enumerable: true,
  7488. configurable: true
  7489. });
  7490. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7491. get: function () {
  7492. return this._stencilOpStencilFail;
  7493. },
  7494. set: function (value) {
  7495. if (this._stencilOpStencilFail === value) {
  7496. return;
  7497. }
  7498. this._stencilOpStencilFail = value;
  7499. this._isStencilOpDirty = true;
  7500. },
  7501. enumerable: true,
  7502. configurable: true
  7503. });
  7504. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7505. get: function () {
  7506. return this._stencilOpDepthFail;
  7507. },
  7508. set: function (value) {
  7509. if (this._stencilOpDepthFail === value) {
  7510. return;
  7511. }
  7512. this._stencilOpDepthFail = value;
  7513. this._isStencilOpDirty = true;
  7514. },
  7515. enumerable: true,
  7516. configurable: true
  7517. });
  7518. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7519. get: function () {
  7520. return this._stencilOpStencilDepthPass;
  7521. },
  7522. set: function (value) {
  7523. if (this._stencilOpStencilDepthPass === value) {
  7524. return;
  7525. }
  7526. this._stencilOpStencilDepthPass = value;
  7527. this._isStencilOpDirty = true;
  7528. },
  7529. enumerable: true,
  7530. configurable: true
  7531. });
  7532. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7533. get: function () {
  7534. return this._stencilMask;
  7535. },
  7536. set: function (value) {
  7537. if (this._stencilMask === value) {
  7538. return;
  7539. }
  7540. this._stencilMask = value;
  7541. this._isStencilMaskDirty = true;
  7542. },
  7543. enumerable: true,
  7544. configurable: true
  7545. });
  7546. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7547. get: function () {
  7548. return this._stencilTest;
  7549. },
  7550. set: function (value) {
  7551. if (this._stencilTest === value) {
  7552. return;
  7553. }
  7554. this._stencilTest = value;
  7555. this._isStencilTestDirty = true;
  7556. },
  7557. enumerable: true,
  7558. configurable: true
  7559. });
  7560. _StencilState.prototype.reset = function () {
  7561. this._stencilTest = false;
  7562. this._stencilMask = 0xFF;
  7563. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7564. this._stencilFuncRef = 1;
  7565. this._stencilFuncMask = 0xFF;
  7566. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7567. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7568. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7569. this._isStencilTestDirty = true;
  7570. this._isStencilMaskDirty = true;
  7571. this._isStencilFuncDirty = true;
  7572. this._isStencilOpDirty = true;
  7573. };
  7574. _StencilState.prototype.apply = function (gl) {
  7575. if (!this.isDirty) {
  7576. return;
  7577. }
  7578. // Stencil test
  7579. if (this._isStencilTestDirty) {
  7580. if (this.stencilTest) {
  7581. gl.enable(gl.STENCIL_TEST);
  7582. }
  7583. else {
  7584. gl.disable(gl.STENCIL_TEST);
  7585. }
  7586. this._isStencilTestDirty = false;
  7587. }
  7588. // Stencil mask
  7589. if (this._isStencilMaskDirty) {
  7590. gl.stencilMask(this.stencilMask);
  7591. this._isStencilMaskDirty = false;
  7592. }
  7593. // Stencil func
  7594. if (this._isStencilFuncDirty) {
  7595. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7596. this._isStencilFuncDirty = false;
  7597. }
  7598. // Stencil op
  7599. if (this._isStencilOpDirty) {
  7600. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7601. this._isStencilOpDirty = false;
  7602. }
  7603. };
  7604. return _StencilState;
  7605. }());
  7606. Internals._StencilState = _StencilState;
  7607. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7608. })(BABYLON || (BABYLON = {}));
  7609. //# sourceMappingURL=babylon.stencilState.js.map
  7610. var BABYLON;
  7611. (function (BABYLON) {
  7612. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7613. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7614. };
  7615. var compileRawShader = function (gl, source, type) {
  7616. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7617. gl.shaderSource(shader, source);
  7618. gl.compileShader(shader);
  7619. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7620. var log = gl.getShaderInfoLog(shader);
  7621. if (log) {
  7622. throw new Error(log);
  7623. }
  7624. }
  7625. if (!shader) {
  7626. throw new Error("Something went wrong while compile the shader.");
  7627. }
  7628. return shader;
  7629. };
  7630. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7631. var magFilter = gl.NEAREST;
  7632. var minFilter = gl.NEAREST;
  7633. switch (samplingMode) {
  7634. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7635. magFilter = gl.LINEAR;
  7636. if (generateMipMaps) {
  7637. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7638. }
  7639. else {
  7640. minFilter = gl.LINEAR;
  7641. }
  7642. break;
  7643. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7644. magFilter = gl.LINEAR;
  7645. if (generateMipMaps) {
  7646. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7647. }
  7648. else {
  7649. minFilter = gl.LINEAR;
  7650. }
  7651. break;
  7652. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7653. magFilter = gl.NEAREST;
  7654. if (generateMipMaps) {
  7655. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7656. }
  7657. else {
  7658. minFilter = gl.NEAREST;
  7659. }
  7660. break;
  7661. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7662. magFilter = gl.NEAREST;
  7663. if (generateMipMaps) {
  7664. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7665. }
  7666. else {
  7667. minFilter = gl.NEAREST;
  7668. }
  7669. break;
  7670. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7671. magFilter = gl.NEAREST;
  7672. if (generateMipMaps) {
  7673. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7674. }
  7675. else {
  7676. minFilter = gl.LINEAR;
  7677. }
  7678. break;
  7679. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7680. magFilter = gl.NEAREST;
  7681. if (generateMipMaps) {
  7682. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7683. }
  7684. else {
  7685. minFilter = gl.LINEAR;
  7686. }
  7687. break;
  7688. case BABYLON.Texture.NEAREST_LINEAR:
  7689. magFilter = gl.NEAREST;
  7690. minFilter = gl.LINEAR;
  7691. break;
  7692. case BABYLON.Texture.NEAREST_NEAREST:
  7693. magFilter = gl.NEAREST;
  7694. minFilter = gl.NEAREST;
  7695. break;
  7696. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7697. magFilter = gl.LINEAR;
  7698. if (generateMipMaps) {
  7699. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7700. }
  7701. else {
  7702. minFilter = gl.NEAREST;
  7703. }
  7704. break;
  7705. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7706. magFilter = gl.LINEAR;
  7707. if (generateMipMaps) {
  7708. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7709. }
  7710. else {
  7711. minFilter = gl.NEAREST;
  7712. }
  7713. break;
  7714. case BABYLON.Texture.LINEAR_LINEAR:
  7715. magFilter = gl.LINEAR;
  7716. minFilter = gl.LINEAR;
  7717. break;
  7718. case BABYLON.Texture.LINEAR_NEAREST:
  7719. magFilter = gl.LINEAR;
  7720. minFilter = gl.NEAREST;
  7721. break;
  7722. }
  7723. return {
  7724. min: minFilter,
  7725. mag: magFilter
  7726. };
  7727. };
  7728. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7729. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7730. var img;
  7731. var onload = function () {
  7732. loadedImages[index] = img;
  7733. loadedImages._internalCount++;
  7734. if (scene) {
  7735. scene._removePendingData(img);
  7736. }
  7737. if (loadedImages._internalCount === 6) {
  7738. onfinish(loadedImages);
  7739. }
  7740. };
  7741. var onerror = function (message, exception) {
  7742. if (scene) {
  7743. scene._removePendingData(img);
  7744. }
  7745. if (onErrorCallBack) {
  7746. onErrorCallBack(message, exception);
  7747. }
  7748. };
  7749. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7750. if (scene) {
  7751. scene._addPendingData(img);
  7752. }
  7753. };
  7754. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7755. if (onError === void 0) { onError = null; }
  7756. var loadedImages = [];
  7757. loadedImages._internalCount = 0;
  7758. for (var index = 0; index < 6; index++) {
  7759. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7760. }
  7761. };
  7762. var BufferPointer = /** @class */ (function () {
  7763. function BufferPointer() {
  7764. }
  7765. return BufferPointer;
  7766. }());
  7767. var InstancingAttributeInfo = /** @class */ (function () {
  7768. function InstancingAttributeInfo() {
  7769. }
  7770. return InstancingAttributeInfo;
  7771. }());
  7772. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7773. /**
  7774. * Define options used to create a render target texture
  7775. */
  7776. var RenderTargetCreationOptions = /** @class */ (function () {
  7777. function RenderTargetCreationOptions() {
  7778. }
  7779. return RenderTargetCreationOptions;
  7780. }());
  7781. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7782. /**
  7783. * Regroup several parameters relative to the browser in use
  7784. */
  7785. var EngineCapabilities = /** @class */ (function () {
  7786. function EngineCapabilities() {
  7787. }
  7788. return EngineCapabilities;
  7789. }());
  7790. BABYLON.EngineCapabilities = EngineCapabilities;
  7791. /**
  7792. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7793. */
  7794. var Engine = /** @class */ (function () {
  7795. /**
  7796. * @constructor
  7797. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7798. * @param {boolean} [antialias] - enable antialias
  7799. * @param options - further options to be sent to the getContext function
  7800. */
  7801. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7802. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7803. var _this = this;
  7804. // Public members
  7805. this.forcePOTTextures = false;
  7806. this.isFullscreen = false;
  7807. this.isPointerLock = false;
  7808. this.cullBackFaces = true;
  7809. this.renderEvenInBackground = true;
  7810. this.preventCacheWipeBetweenFrames = false;
  7811. // To enable/disable IDB support and avoid XHR on .manifest
  7812. this.enableOfflineSupport = false;
  7813. this.scenes = new Array();
  7814. this.postProcesses = new Array();
  7815. // Observables
  7816. /**
  7817. * Observable event triggered each time the rendering canvas is resized
  7818. */
  7819. this.onResizeObservable = new BABYLON.Observable();
  7820. /**
  7821. * Observable event triggered each time the canvas loses focus
  7822. */
  7823. this.onCanvasBlurObservable = new BABYLON.Observable();
  7824. /**
  7825. * Observable event triggered each time the canvas gains focus
  7826. */
  7827. this.onCanvasFocusObservable = new BABYLON.Observable();
  7828. /**
  7829. * Observable event triggered each time the canvas receives pointerout event
  7830. */
  7831. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7832. /**
  7833. * Observable event triggered before each texture is initialized
  7834. */
  7835. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7836. //WebVR
  7837. this._vrDisplay = undefined;
  7838. this._vrSupported = false;
  7839. this._vrExclusivePointerMode = false;
  7840. // Uniform buffers list
  7841. this.disableUniformBuffers = false;
  7842. this._uniformBuffers = new Array();
  7843. // Observables
  7844. /**
  7845. * Observable raised when the engine begins a new frame
  7846. */
  7847. this.onBeginFrameObservable = new BABYLON.Observable();
  7848. /**
  7849. * Observable raised when the engine ends the current frame
  7850. */
  7851. this.onEndFrameObservable = new BABYLON.Observable();
  7852. /**
  7853. * Observable raised when the engine is about to compile a shader
  7854. */
  7855. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7856. /**
  7857. * Observable raised when the engine has jsut compiled a shader
  7858. */
  7859. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7860. this._windowIsBackground = false;
  7861. this._webGLVersion = 1.0;
  7862. this._badOS = false;
  7863. this._badDesktopOS = false;
  7864. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7865. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7866. this.onVRRequestPresentStart = new BABYLON.Observable();
  7867. this._colorWrite = true;
  7868. this._drawCalls = new BABYLON.PerfCounter();
  7869. this._renderingQueueLaunched = false;
  7870. this._activeRenderLoops = new Array();
  7871. // Deterministic lockstepMaxSteps
  7872. this._deterministicLockstep = false;
  7873. this._lockstepMaxSteps = 4;
  7874. // Lost context
  7875. this.onContextLostObservable = new BABYLON.Observable();
  7876. this.onContextRestoredObservable = new BABYLON.Observable();
  7877. this._contextWasLost = false;
  7878. this._doNotHandleContextLost = false;
  7879. // FPS
  7880. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7881. this._fps = 60;
  7882. this._deltaTime = 0;
  7883. /**
  7884. * Turn this value on if you want to pause FPS computation when in background
  7885. */
  7886. this.disablePerformanceMonitorInBackground = false;
  7887. // States
  7888. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7889. this._stencilState = new BABYLON.Internals._StencilState();
  7890. this._alphaState = new BABYLON.Internals._AlphaState();
  7891. this._alphaMode = Engine.ALPHA_DISABLE;
  7892. // Cache
  7893. this._internalTexturesCache = new Array();
  7894. this._activeTexturesCache = {};
  7895. this._compiledEffects = {};
  7896. this._vertexAttribArraysEnabled = [];
  7897. this._uintIndicesCurrentlySet = false;
  7898. this._currentBoundBuffer = new Array();
  7899. this._currentBufferPointers = new Array();
  7900. this._currentInstanceLocations = new Array();
  7901. this._currentInstanceBuffers = new Array();
  7902. this._vaoRecordInProgress = false;
  7903. this._mustWipeVertexAttributes = false;
  7904. // Hardware supported Compressed Textures
  7905. this._texturesSupported = new Array();
  7906. this._onVRFullScreenTriggered = function () {
  7907. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7908. //get the old size before we change
  7909. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7910. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7911. //get the width and height, change the render size
  7912. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7913. _this.setHardwareScalingLevel(1);
  7914. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7915. }
  7916. else {
  7917. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7918. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7919. }
  7920. };
  7921. var canvas = null;
  7922. Engine.Instances.push(this);
  7923. if (!canvasOrContext) {
  7924. return;
  7925. }
  7926. options = options || {};
  7927. if (canvasOrContext.getContext) {
  7928. canvas = canvasOrContext;
  7929. this._renderingCanvas = canvas;
  7930. if (antialias != null) {
  7931. options.antialias = antialias;
  7932. }
  7933. if (options.deterministicLockstep === undefined) {
  7934. options.deterministicLockstep = false;
  7935. }
  7936. if (options.lockstepMaxSteps === undefined) {
  7937. options.lockstepMaxSteps = 4;
  7938. }
  7939. if (options.preserveDrawingBuffer === undefined) {
  7940. options.preserveDrawingBuffer = false;
  7941. }
  7942. if (options.audioEngine === undefined) {
  7943. options.audioEngine = true;
  7944. }
  7945. if (options.stencil === undefined) {
  7946. options.stencil = true;
  7947. }
  7948. this._deterministicLockstep = options.deterministicLockstep;
  7949. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7950. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  7951. // GL
  7952. if (!options.disableWebGL2Support) {
  7953. try {
  7954. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7955. if (this._gl) {
  7956. this._webGLVersion = 2.0;
  7957. }
  7958. }
  7959. catch (e) {
  7960. // Do nothing
  7961. }
  7962. }
  7963. if (!this._gl) {
  7964. if (!canvas) {
  7965. throw new Error("The provided canvas is null or undefined.");
  7966. }
  7967. try {
  7968. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7969. }
  7970. catch (e) {
  7971. throw new Error("WebGL not supported");
  7972. }
  7973. }
  7974. if (!this._gl) {
  7975. throw new Error("WebGL not supported");
  7976. }
  7977. this._onCanvasFocus = function () {
  7978. _this.onCanvasFocusObservable.notifyObservers(_this);
  7979. };
  7980. this._onCanvasBlur = function () {
  7981. _this.onCanvasBlurObservable.notifyObservers(_this);
  7982. };
  7983. canvas.addEventListener("focus", this._onCanvasFocus);
  7984. canvas.addEventListener("blur", this._onCanvasBlur);
  7985. this._onBlur = function () {
  7986. if (_this.disablePerformanceMonitorInBackground) {
  7987. _this._performanceMonitor.disable();
  7988. }
  7989. _this._windowIsBackground = true;
  7990. };
  7991. this._onFocus = function () {
  7992. if (_this.disablePerformanceMonitorInBackground) {
  7993. _this._performanceMonitor.enable();
  7994. }
  7995. _this._windowIsBackground = false;
  7996. };
  7997. this._onCanvasPointerOut = function () {
  7998. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7999. };
  8000. window.addEventListener("blur", this._onBlur);
  8001. window.addEventListener("focus", this._onFocus);
  8002. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8003. // Context lost
  8004. if (!this._doNotHandleContextLost) {
  8005. this._onContextLost = function (evt) {
  8006. evt.preventDefault();
  8007. _this._contextWasLost = true;
  8008. BABYLON.Tools.Warn("WebGL context lost.");
  8009. _this.onContextLostObservable.notifyObservers(_this);
  8010. };
  8011. this._onContextRestored = function (evt) {
  8012. // Adding a timeout to avoid race condition at browser level
  8013. setTimeout(function () {
  8014. // Rebuild gl context
  8015. _this._initGLContext();
  8016. // Rebuild effects
  8017. _this._rebuildEffects();
  8018. // Rebuild textures
  8019. _this._rebuildInternalTextures();
  8020. // Rebuild buffers
  8021. _this._rebuildBuffers();
  8022. // Cache
  8023. _this.wipeCaches(true);
  8024. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8025. _this.onContextRestoredObservable.notifyObservers(_this);
  8026. _this._contextWasLost = false;
  8027. }, 0);
  8028. };
  8029. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8030. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8031. }
  8032. }
  8033. else {
  8034. this._gl = canvasOrContext;
  8035. this._renderingCanvas = this._gl.canvas;
  8036. if (this._gl.renderbufferStorageMultisample) {
  8037. this._webGLVersion = 2.0;
  8038. }
  8039. options.stencil = this._gl.getContextAttributes().stencil;
  8040. }
  8041. // Viewport
  8042. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8043. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8044. this.resize();
  8045. this._isStencilEnable = options.stencil ? true : false;
  8046. this._initGLContext();
  8047. if (canvas) {
  8048. // Fullscreen
  8049. this._onFullscreenChange = function () {
  8050. if (document.fullscreen !== undefined) {
  8051. _this.isFullscreen = document.fullscreen;
  8052. }
  8053. else if (document.mozFullScreen !== undefined) {
  8054. _this.isFullscreen = document.mozFullScreen;
  8055. }
  8056. else if (document.webkitIsFullScreen !== undefined) {
  8057. _this.isFullscreen = document.webkitIsFullScreen;
  8058. }
  8059. else if (document.msIsFullScreen !== undefined) {
  8060. _this.isFullscreen = document.msIsFullScreen;
  8061. }
  8062. // Pointer lock
  8063. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8064. canvas.requestPointerLock = canvas.requestPointerLock ||
  8065. canvas.msRequestPointerLock ||
  8066. canvas.mozRequestPointerLock ||
  8067. canvas.webkitRequestPointerLock;
  8068. if (canvas.requestPointerLock) {
  8069. canvas.requestPointerLock();
  8070. }
  8071. }
  8072. };
  8073. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8074. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8075. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8076. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8077. // Pointer lock
  8078. this._onPointerLockChange = function () {
  8079. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8080. document.webkitPointerLockElement === canvas ||
  8081. document.msPointerLockElement === canvas ||
  8082. document.pointerLockElement === canvas);
  8083. };
  8084. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8085. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8086. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8087. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8088. this._onVRDisplayPointerRestricted = function () {
  8089. if (canvas) {
  8090. canvas.requestPointerLock();
  8091. }
  8092. };
  8093. this._onVRDisplayPointerUnrestricted = function () {
  8094. document.exitPointerLock();
  8095. };
  8096. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8097. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8098. }
  8099. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8100. Engine.audioEngine = new BABYLON.AudioEngine();
  8101. }
  8102. // Prepare buffer pointers
  8103. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8104. this._currentBufferPointers[i] = new BufferPointer();
  8105. }
  8106. // Load WebVR Devices
  8107. if (options.autoEnableWebVR) {
  8108. this.initWebVR();
  8109. }
  8110. // Detect if we are running on a faulty buggy OS.
  8111. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8112. // Detect if we are running on a faulty buggy desktop OS.
  8113. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8114. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8115. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8116. }
  8117. Object.defineProperty(Engine, "LastCreatedEngine", {
  8118. get: function () {
  8119. if (Engine.Instances.length === 0) {
  8120. return null;
  8121. }
  8122. return Engine.Instances[Engine.Instances.length - 1];
  8123. },
  8124. enumerable: true,
  8125. configurable: true
  8126. });
  8127. Object.defineProperty(Engine, "LastCreatedScene", {
  8128. get: function () {
  8129. var lastCreatedEngine = Engine.LastCreatedEngine;
  8130. if (!lastCreatedEngine) {
  8131. return null;
  8132. }
  8133. if (lastCreatedEngine.scenes.length === 0) {
  8134. return null;
  8135. }
  8136. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8137. },
  8138. enumerable: true,
  8139. configurable: true
  8140. });
  8141. /**
  8142. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8143. */
  8144. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8145. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8146. var engine = Engine.Instances[engineIndex];
  8147. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8148. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8149. }
  8150. }
  8151. };
  8152. Object.defineProperty(Engine, "NEVER", {
  8153. get: function () {
  8154. return Engine._NEVER;
  8155. },
  8156. enumerable: true,
  8157. configurable: true
  8158. });
  8159. Object.defineProperty(Engine, "ALWAYS", {
  8160. get: function () {
  8161. return Engine._ALWAYS;
  8162. },
  8163. enumerable: true,
  8164. configurable: true
  8165. });
  8166. Object.defineProperty(Engine, "LESS", {
  8167. get: function () {
  8168. return Engine._LESS;
  8169. },
  8170. enumerable: true,
  8171. configurable: true
  8172. });
  8173. Object.defineProperty(Engine, "EQUAL", {
  8174. get: function () {
  8175. return Engine._EQUAL;
  8176. },
  8177. enumerable: true,
  8178. configurable: true
  8179. });
  8180. Object.defineProperty(Engine, "LEQUAL", {
  8181. get: function () {
  8182. return Engine._LEQUAL;
  8183. },
  8184. enumerable: true,
  8185. configurable: true
  8186. });
  8187. Object.defineProperty(Engine, "GREATER", {
  8188. get: function () {
  8189. return Engine._GREATER;
  8190. },
  8191. enumerable: true,
  8192. configurable: true
  8193. });
  8194. Object.defineProperty(Engine, "GEQUAL", {
  8195. get: function () {
  8196. return Engine._GEQUAL;
  8197. },
  8198. enumerable: true,
  8199. configurable: true
  8200. });
  8201. Object.defineProperty(Engine, "NOTEQUAL", {
  8202. get: function () {
  8203. return Engine._NOTEQUAL;
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. Object.defineProperty(Engine, "KEEP", {
  8209. get: function () {
  8210. return Engine._KEEP;
  8211. },
  8212. enumerable: true,
  8213. configurable: true
  8214. });
  8215. Object.defineProperty(Engine, "REPLACE", {
  8216. get: function () {
  8217. return Engine._REPLACE;
  8218. },
  8219. enumerable: true,
  8220. configurable: true
  8221. });
  8222. Object.defineProperty(Engine, "INCR", {
  8223. get: function () {
  8224. return Engine._INCR;
  8225. },
  8226. enumerable: true,
  8227. configurable: true
  8228. });
  8229. Object.defineProperty(Engine, "DECR", {
  8230. get: function () {
  8231. return Engine._DECR;
  8232. },
  8233. enumerable: true,
  8234. configurable: true
  8235. });
  8236. Object.defineProperty(Engine, "INVERT", {
  8237. get: function () {
  8238. return Engine._INVERT;
  8239. },
  8240. enumerable: true,
  8241. configurable: true
  8242. });
  8243. Object.defineProperty(Engine, "INCR_WRAP", {
  8244. get: function () {
  8245. return Engine._INCR_WRAP;
  8246. },
  8247. enumerable: true,
  8248. configurable: true
  8249. });
  8250. Object.defineProperty(Engine, "DECR_WRAP", {
  8251. get: function () {
  8252. return Engine._DECR_WRAP;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8258. get: function () {
  8259. return Engine._ALPHA_DISABLE;
  8260. },
  8261. enumerable: true,
  8262. configurable: true
  8263. });
  8264. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8265. get: function () {
  8266. return Engine._ALPHA_ONEONE;
  8267. },
  8268. enumerable: true,
  8269. configurable: true
  8270. });
  8271. Object.defineProperty(Engine, "ALPHA_ADD", {
  8272. get: function () {
  8273. return Engine._ALPHA_ADD;
  8274. },
  8275. enumerable: true,
  8276. configurable: true
  8277. });
  8278. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8279. get: function () {
  8280. return Engine._ALPHA_COMBINE;
  8281. },
  8282. enumerable: true,
  8283. configurable: true
  8284. });
  8285. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8286. get: function () {
  8287. return Engine._ALPHA_SUBTRACT;
  8288. },
  8289. enumerable: true,
  8290. configurable: true
  8291. });
  8292. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8293. get: function () {
  8294. return Engine._ALPHA_MULTIPLY;
  8295. },
  8296. enumerable: true,
  8297. configurable: true
  8298. });
  8299. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8300. get: function () {
  8301. return Engine._ALPHA_MAXIMIZED;
  8302. },
  8303. enumerable: true,
  8304. configurable: true
  8305. });
  8306. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8307. get: function () {
  8308. return Engine._ALPHA_PREMULTIPLIED;
  8309. },
  8310. enumerable: true,
  8311. configurable: true
  8312. });
  8313. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8314. get: function () {
  8315. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8316. },
  8317. enumerable: true,
  8318. configurable: true
  8319. });
  8320. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8321. get: function () {
  8322. return Engine._ALPHA_INTERPOLATE;
  8323. },
  8324. enumerable: true,
  8325. configurable: true
  8326. });
  8327. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8328. get: function () {
  8329. return Engine._ALPHA_SCREENMODE;
  8330. },
  8331. enumerable: true,
  8332. configurable: true
  8333. });
  8334. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8335. get: function () {
  8336. return Engine._DELAYLOADSTATE_NONE;
  8337. },
  8338. enumerable: true,
  8339. configurable: true
  8340. });
  8341. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8342. get: function () {
  8343. return Engine._DELAYLOADSTATE_LOADED;
  8344. },
  8345. enumerable: true,
  8346. configurable: true
  8347. });
  8348. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8349. get: function () {
  8350. return Engine._DELAYLOADSTATE_LOADING;
  8351. },
  8352. enumerable: true,
  8353. configurable: true
  8354. });
  8355. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8356. get: function () {
  8357. return Engine._DELAYLOADSTATE_NOTLOADED;
  8358. },
  8359. enumerable: true,
  8360. configurable: true
  8361. });
  8362. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8363. get: function () {
  8364. return Engine._TEXTUREFORMAT_ALPHA;
  8365. },
  8366. enumerable: true,
  8367. configurable: true
  8368. });
  8369. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8370. get: function () {
  8371. return Engine._TEXTUREFORMAT_LUMINANCE;
  8372. },
  8373. enumerable: true,
  8374. configurable: true
  8375. });
  8376. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8377. get: function () {
  8378. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8379. },
  8380. enumerable: true,
  8381. configurable: true
  8382. });
  8383. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8384. get: function () {
  8385. return Engine._TEXTUREFORMAT_RGB;
  8386. },
  8387. enumerable: true,
  8388. configurable: true
  8389. });
  8390. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8391. get: function () {
  8392. return Engine._TEXTUREFORMAT_RGBA;
  8393. },
  8394. enumerable: true,
  8395. configurable: true
  8396. });
  8397. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8398. get: function () {
  8399. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8400. },
  8401. enumerable: true,
  8402. configurable: true
  8403. });
  8404. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8405. get: function () {
  8406. return Engine._TEXTURETYPE_FLOAT;
  8407. },
  8408. enumerable: true,
  8409. configurable: true
  8410. });
  8411. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8412. get: function () {
  8413. return Engine._TEXTURETYPE_HALF_FLOAT;
  8414. },
  8415. enumerable: true,
  8416. configurable: true
  8417. });
  8418. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8419. get: function () {
  8420. return Engine._SCALEMODE_FLOOR;
  8421. },
  8422. enumerable: true,
  8423. configurable: true
  8424. });
  8425. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8426. get: function () {
  8427. return Engine._SCALEMODE_NEAREST;
  8428. },
  8429. enumerable: true,
  8430. configurable: true
  8431. });
  8432. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8433. get: function () {
  8434. return Engine._SCALEMODE_CEILING;
  8435. },
  8436. enumerable: true,
  8437. configurable: true
  8438. });
  8439. Object.defineProperty(Engine, "Version", {
  8440. get: function () {
  8441. return "3.1-alpha";
  8442. },
  8443. enumerable: true,
  8444. configurable: true
  8445. });
  8446. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8447. get: function () {
  8448. return this._vrExclusivePointerMode;
  8449. },
  8450. enumerable: true,
  8451. configurable: true
  8452. });
  8453. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8454. get: function () {
  8455. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8456. },
  8457. enumerable: true,
  8458. configurable: true
  8459. });
  8460. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8461. get: function () {
  8462. return this._webGLVersion < 2 || this.forcePOTTextures;
  8463. },
  8464. enumerable: true,
  8465. configurable: true
  8466. });
  8467. Object.defineProperty(Engine.prototype, "badOS", {
  8468. get: function () {
  8469. return this._badOS;
  8470. },
  8471. enumerable: true,
  8472. configurable: true
  8473. });
  8474. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8475. get: function () {
  8476. return this._badDesktopOS;
  8477. },
  8478. enumerable: true,
  8479. configurable: true
  8480. });
  8481. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8482. get: function () {
  8483. return this._performanceMonitor;
  8484. },
  8485. enumerable: true,
  8486. configurable: true
  8487. });
  8488. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8489. get: function () {
  8490. return this._texturesSupported;
  8491. },
  8492. enumerable: true,
  8493. configurable: true
  8494. });
  8495. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8496. get: function () {
  8497. return this._textureFormatInUse;
  8498. },
  8499. enumerable: true,
  8500. configurable: true
  8501. });
  8502. Object.defineProperty(Engine.prototype, "currentViewport", {
  8503. get: function () {
  8504. return this._cachedViewport;
  8505. },
  8506. enumerable: true,
  8507. configurable: true
  8508. });
  8509. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8510. // Empty texture
  8511. get: function () {
  8512. if (!this._emptyTexture) {
  8513. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8514. }
  8515. return this._emptyTexture;
  8516. },
  8517. enumerable: true,
  8518. configurable: true
  8519. });
  8520. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8521. get: function () {
  8522. if (!this._emptyTexture3D) {
  8523. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8524. }
  8525. return this._emptyTexture3D;
  8526. },
  8527. enumerable: true,
  8528. configurable: true
  8529. });
  8530. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8531. get: function () {
  8532. if (!this._emptyCubeTexture) {
  8533. var faceData = new Uint8Array(4);
  8534. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8535. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8536. }
  8537. return this._emptyCubeTexture;
  8538. },
  8539. enumerable: true,
  8540. configurable: true
  8541. });
  8542. Engine.prototype._rebuildInternalTextures = function () {
  8543. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8544. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8545. var internalTexture = currentState_1[_i];
  8546. internalTexture._rebuild();
  8547. }
  8548. };
  8549. Engine.prototype._rebuildEffects = function () {
  8550. for (var key in this._compiledEffects) {
  8551. var effect = this._compiledEffects[key];
  8552. effect._prepareEffect();
  8553. }
  8554. BABYLON.Effect.ResetCache();
  8555. };
  8556. Engine.prototype._rebuildBuffers = function () {
  8557. // Index / Vertex
  8558. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8559. var scene = _a[_i];
  8560. scene.resetCachedMaterial();
  8561. scene._rebuildGeometries();
  8562. scene._rebuildTextures();
  8563. }
  8564. // Uniforms
  8565. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8566. var uniformBuffer = _c[_b];
  8567. uniformBuffer._rebuild();
  8568. }
  8569. };
  8570. Engine.prototype._initGLContext = function () {
  8571. // Caps
  8572. this._caps = new EngineCapabilities();
  8573. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8574. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8575. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8576. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8577. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8578. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8579. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8580. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8581. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8582. // Infos
  8583. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8584. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8585. if (rendererInfo != null) {
  8586. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8587. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8588. }
  8589. if (!this._glVendor) {
  8590. this._glVendor = "Unknown vendor";
  8591. }
  8592. if (!this._glRenderer) {
  8593. this._glRenderer = "Unknown renderer";
  8594. }
  8595. // Constants
  8596. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8597. if (this._gl.RGBA16F !== 0x881A) {
  8598. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8599. }
  8600. if (this._gl.RGBA32F !== 0x8814) {
  8601. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8602. }
  8603. this._gl.DEPTH24_STENCIL8 = 35056;
  8604. // Extensions
  8605. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8606. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8607. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8608. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8609. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8610. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8611. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8612. 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');
  8613. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8614. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8615. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8616. this._caps.highPrecisionShaderSupported = true;
  8617. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8618. if (this._caps.timerQuery) {
  8619. if (this._webGLVersion === 1) {
  8620. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8621. }
  8622. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8623. }
  8624. // Checks if some of the format renders first to allow the use of webgl inspector.
  8625. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8626. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8627. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8628. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8629. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8630. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8631. if (this._webGLVersion > 1) {
  8632. this._gl.HALF_FLOAT_OES = 0x140B;
  8633. }
  8634. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8635. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8636. // Draw buffers
  8637. if (this._webGLVersion > 1) {
  8638. this._caps.drawBuffersExtension = true;
  8639. }
  8640. else {
  8641. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8642. if (drawBuffersExtension !== null) {
  8643. this._caps.drawBuffersExtension = true;
  8644. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8645. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8646. for (var i = 0; i < 16; i++) {
  8647. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8648. }
  8649. }
  8650. else {
  8651. this._caps.drawBuffersExtension = false;
  8652. }
  8653. }
  8654. // Depth Texture
  8655. if (this._webGLVersion > 1) {
  8656. this._caps.depthTextureExtension = true;
  8657. }
  8658. else {
  8659. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8660. if (depthTextureExtension != null) {
  8661. this._caps.depthTextureExtension = true;
  8662. }
  8663. }
  8664. // Vertex array object
  8665. if (this._webGLVersion > 1) {
  8666. this._caps.vertexArrayObject = true;
  8667. }
  8668. else {
  8669. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8670. if (vertexArrayObjectExtension != null) {
  8671. this._caps.vertexArrayObject = true;
  8672. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8673. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8674. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8675. }
  8676. else {
  8677. this._caps.vertexArrayObject = false;
  8678. }
  8679. }
  8680. // Instances count
  8681. if (this._webGLVersion > 1) {
  8682. this._caps.instancedArrays = true;
  8683. }
  8684. else {
  8685. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8686. if (instanceExtension != null) {
  8687. this._caps.instancedArrays = true;
  8688. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8689. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8690. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8691. }
  8692. else {
  8693. this._caps.instancedArrays = false;
  8694. }
  8695. }
  8696. // Intelligently add supported compressed formats in order to check for.
  8697. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8698. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8699. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8700. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8701. if (this._caps.astc)
  8702. this.texturesSupported.push('-astc.ktx');
  8703. if (this._caps.s3tc)
  8704. this.texturesSupported.push('-dxt.ktx');
  8705. if (this._caps.pvrtc)
  8706. this.texturesSupported.push('-pvrtc.ktx');
  8707. if (this._caps.etc2)
  8708. this.texturesSupported.push('-etc2.ktx');
  8709. if (this._caps.etc1)
  8710. this.texturesSupported.push('-etc1.ktx');
  8711. if (this._gl.getShaderPrecisionFormat) {
  8712. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8713. if (highp) {
  8714. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8715. }
  8716. }
  8717. // Depth buffer
  8718. this.setDepthBuffer(true);
  8719. this.setDepthFunctionToLessOrEqual();
  8720. this.setDepthWrite(true);
  8721. };
  8722. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8723. get: function () {
  8724. return this._webGLVersion;
  8725. },
  8726. enumerable: true,
  8727. configurable: true
  8728. });
  8729. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8730. /**
  8731. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8732. */
  8733. get: function () {
  8734. return this._isStencilEnable;
  8735. },
  8736. enumerable: true,
  8737. configurable: true
  8738. });
  8739. Engine.prototype._prepareWorkingCanvas = function () {
  8740. if (this._workingCanvas) {
  8741. return;
  8742. }
  8743. this._workingCanvas = document.createElement("canvas");
  8744. var context = this._workingCanvas.getContext("2d");
  8745. if (context) {
  8746. this._workingContext = context;
  8747. }
  8748. };
  8749. Engine.prototype.resetTextureCache = function () {
  8750. for (var key in this._activeTexturesCache) {
  8751. this._activeTexturesCache[key] = null;
  8752. }
  8753. };
  8754. Engine.prototype.isDeterministicLockStep = function () {
  8755. return this._deterministicLockstep;
  8756. };
  8757. Engine.prototype.getLockstepMaxSteps = function () {
  8758. return this._lockstepMaxSteps;
  8759. };
  8760. Engine.prototype.getGlInfo = function () {
  8761. return {
  8762. vendor: this._glVendor,
  8763. renderer: this._glRenderer,
  8764. version: this._glVersion
  8765. };
  8766. };
  8767. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8768. if (useScreen === void 0) { useScreen = false; }
  8769. var viewport = camera.viewport;
  8770. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8771. };
  8772. Engine.prototype.getRenderWidth = function (useScreen) {
  8773. if (useScreen === void 0) { useScreen = false; }
  8774. if (!useScreen && this._currentRenderTarget) {
  8775. return this._currentRenderTarget.width;
  8776. }
  8777. return this._gl.drawingBufferWidth;
  8778. };
  8779. Engine.prototype.getRenderHeight = function (useScreen) {
  8780. if (useScreen === void 0) { useScreen = false; }
  8781. if (!useScreen && this._currentRenderTarget) {
  8782. return this._currentRenderTarget.height;
  8783. }
  8784. return this._gl.drawingBufferHeight;
  8785. };
  8786. Engine.prototype.getRenderingCanvas = function () {
  8787. return this._renderingCanvas;
  8788. };
  8789. Engine.prototype.getRenderingCanvasClientRect = function () {
  8790. if (!this._renderingCanvas) {
  8791. return null;
  8792. }
  8793. return this._renderingCanvas.getBoundingClientRect();
  8794. };
  8795. Engine.prototype.setHardwareScalingLevel = function (level) {
  8796. this._hardwareScalingLevel = level;
  8797. this.resize();
  8798. };
  8799. Engine.prototype.getHardwareScalingLevel = function () {
  8800. return this._hardwareScalingLevel;
  8801. };
  8802. Engine.prototype.getLoadedTexturesCache = function () {
  8803. return this._internalTexturesCache;
  8804. };
  8805. Engine.prototype.getCaps = function () {
  8806. return this._caps;
  8807. };
  8808. Object.defineProperty(Engine.prototype, "drawCalls", {
  8809. /** The number of draw calls submitted last frame */
  8810. get: function () {
  8811. return this._drawCalls.current;
  8812. },
  8813. enumerable: true,
  8814. configurable: true
  8815. });
  8816. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8817. get: function () {
  8818. return this._drawCalls;
  8819. },
  8820. enumerable: true,
  8821. configurable: true
  8822. });
  8823. Engine.prototype.getDepthFunction = function () {
  8824. return this._depthCullingState.depthFunc;
  8825. };
  8826. Engine.prototype.setDepthFunction = function (depthFunc) {
  8827. this._depthCullingState.depthFunc = depthFunc;
  8828. };
  8829. Engine.prototype.setDepthFunctionToGreater = function () {
  8830. this._depthCullingState.depthFunc = this._gl.GREATER;
  8831. };
  8832. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8833. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8834. };
  8835. Engine.prototype.setDepthFunctionToLess = function () {
  8836. this._depthCullingState.depthFunc = this._gl.LESS;
  8837. };
  8838. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8839. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8840. };
  8841. Engine.prototype.getStencilBuffer = function () {
  8842. return this._stencilState.stencilTest;
  8843. };
  8844. Engine.prototype.setStencilBuffer = function (enable) {
  8845. this._stencilState.stencilTest = enable;
  8846. };
  8847. Engine.prototype.getStencilMask = function () {
  8848. return this._stencilState.stencilMask;
  8849. };
  8850. Engine.prototype.setStencilMask = function (mask) {
  8851. this._stencilState.stencilMask = mask;
  8852. };
  8853. Engine.prototype.getStencilFunction = function () {
  8854. return this._stencilState.stencilFunc;
  8855. };
  8856. Engine.prototype.getStencilFunctionReference = function () {
  8857. return this._stencilState.stencilFuncRef;
  8858. };
  8859. Engine.prototype.getStencilFunctionMask = function () {
  8860. return this._stencilState.stencilFuncMask;
  8861. };
  8862. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8863. this._stencilState.stencilFunc = stencilFunc;
  8864. };
  8865. Engine.prototype.setStencilFunctionReference = function (reference) {
  8866. this._stencilState.stencilFuncRef = reference;
  8867. };
  8868. Engine.prototype.setStencilFunctionMask = function (mask) {
  8869. this._stencilState.stencilFuncMask = mask;
  8870. };
  8871. Engine.prototype.getStencilOperationFail = function () {
  8872. return this._stencilState.stencilOpStencilFail;
  8873. };
  8874. Engine.prototype.getStencilOperationDepthFail = function () {
  8875. return this._stencilState.stencilOpDepthFail;
  8876. };
  8877. Engine.prototype.getStencilOperationPass = function () {
  8878. return this._stencilState.stencilOpStencilDepthPass;
  8879. };
  8880. Engine.prototype.setStencilOperationFail = function (operation) {
  8881. this._stencilState.stencilOpStencilFail = operation;
  8882. };
  8883. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8884. this._stencilState.stencilOpDepthFail = operation;
  8885. };
  8886. Engine.prototype.setStencilOperationPass = function (operation) {
  8887. this._stencilState.stencilOpStencilDepthPass = operation;
  8888. };
  8889. Engine.prototype.setDitheringState = function (value) {
  8890. if (value) {
  8891. this._gl.enable(this._gl.DITHER);
  8892. }
  8893. else {
  8894. this._gl.disable(this._gl.DITHER);
  8895. }
  8896. };
  8897. /**
  8898. * stop executing a render loop function and remove it from the execution array
  8899. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8900. */
  8901. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8902. if (!renderFunction) {
  8903. this._activeRenderLoops = [];
  8904. return;
  8905. }
  8906. var index = this._activeRenderLoops.indexOf(renderFunction);
  8907. if (index >= 0) {
  8908. this._activeRenderLoops.splice(index, 1);
  8909. }
  8910. };
  8911. Engine.prototype._renderLoop = function () {
  8912. if (!this._contextWasLost) {
  8913. var shouldRender = true;
  8914. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8915. shouldRender = false;
  8916. }
  8917. if (shouldRender) {
  8918. // Start new frame
  8919. this.beginFrame();
  8920. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8921. var renderFunction = this._activeRenderLoops[index];
  8922. renderFunction();
  8923. }
  8924. // Present
  8925. this.endFrame();
  8926. }
  8927. }
  8928. if (this._activeRenderLoops.length > 0) {
  8929. // Register new frame
  8930. var requester = null;
  8931. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8932. requester = this._vrDisplay;
  8933. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8934. }
  8935. else {
  8936. this._renderingQueueLaunched = false;
  8937. }
  8938. };
  8939. /**
  8940. * Register and execute a render loop. The engine can have more than one render function.
  8941. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8942. * @example
  8943. * engine.runRenderLoop(function () {
  8944. * scene.render()
  8945. * })
  8946. */
  8947. Engine.prototype.runRenderLoop = function (renderFunction) {
  8948. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8949. return;
  8950. }
  8951. this._activeRenderLoops.push(renderFunction);
  8952. if (!this._renderingQueueLaunched) {
  8953. this._renderingQueueLaunched = true;
  8954. this._bindedRenderFunction = this._renderLoop.bind(this);
  8955. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8956. }
  8957. };
  8958. /**
  8959. * Toggle full screen mode.
  8960. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8961. * @param {any} options - an options object to be sent to the requestFullscreen function
  8962. */
  8963. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8964. if (this.isFullscreen) {
  8965. BABYLON.Tools.ExitFullscreen();
  8966. }
  8967. else {
  8968. this._pointerLockRequested = requestPointerLock;
  8969. if (this._renderingCanvas) {
  8970. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8971. }
  8972. }
  8973. };
  8974. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8975. if (stencil === void 0) { stencil = false; }
  8976. this.applyStates();
  8977. var mode = 0;
  8978. if (backBuffer && color) {
  8979. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8980. mode |= this._gl.COLOR_BUFFER_BIT;
  8981. }
  8982. if (depth) {
  8983. this._gl.clearDepth(1.0);
  8984. mode |= this._gl.DEPTH_BUFFER_BIT;
  8985. }
  8986. if (stencil) {
  8987. this._gl.clearStencil(0);
  8988. mode |= this._gl.STENCIL_BUFFER_BIT;
  8989. }
  8990. this._gl.clear(mode);
  8991. };
  8992. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8993. var gl = this._gl;
  8994. // Save state
  8995. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8996. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8997. // Change state
  8998. gl.enable(gl.SCISSOR_TEST);
  8999. gl.scissor(x, y, width, height);
  9000. // Clear
  9001. this.clear(clearColor, true, true, true);
  9002. // Restore state
  9003. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9004. if (curScissor === true) {
  9005. gl.enable(gl.SCISSOR_TEST);
  9006. }
  9007. else {
  9008. gl.disable(gl.SCISSOR_TEST);
  9009. }
  9010. };
  9011. /**
  9012. * Set the WebGL's viewport
  9013. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9014. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9015. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9016. */
  9017. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9018. var width = requiredWidth || this.getRenderWidth();
  9019. var height = requiredHeight || this.getRenderHeight();
  9020. var x = viewport.x || 0;
  9021. var y = viewport.y || 0;
  9022. this._cachedViewport = viewport;
  9023. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9024. };
  9025. /**
  9026. * Directly set the WebGL Viewport
  9027. * The x, y, width & height are directly passed to the WebGL call
  9028. * @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.
  9029. */
  9030. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9031. var currentViewport = this._cachedViewport;
  9032. this._cachedViewport = null;
  9033. this._gl.viewport(x, y, width, height);
  9034. return currentViewport;
  9035. };
  9036. Engine.prototype.beginFrame = function () {
  9037. this.onBeginFrameObservable.notifyObservers(this);
  9038. this._measureFps();
  9039. };
  9040. Engine.prototype.endFrame = function () {
  9041. //force a flush in case we are using a bad OS.
  9042. if (this._badOS) {
  9043. this.flushFramebuffer();
  9044. }
  9045. //submit frame to the vr device, if enabled
  9046. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9047. // TODO: We should only submit the frame if we read frameData successfully.
  9048. this._vrDisplay.submitFrame();
  9049. }
  9050. this.onEndFrameObservable.notifyObservers(this);
  9051. };
  9052. /**
  9053. * resize the view according to the canvas' size.
  9054. * @example
  9055. * window.addEventListener("resize", function () {
  9056. * engine.resize();
  9057. * });
  9058. */
  9059. Engine.prototype.resize = function () {
  9060. // We're not resizing the size of the canvas while in VR mode & presenting
  9061. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9062. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9063. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9064. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9065. }
  9066. };
  9067. /**
  9068. * force a specific size of the canvas
  9069. * @param {number} width - the new canvas' width
  9070. * @param {number} height - the new canvas' height
  9071. */
  9072. Engine.prototype.setSize = function (width, height) {
  9073. if (!this._renderingCanvas) {
  9074. return;
  9075. }
  9076. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9077. return;
  9078. }
  9079. this._renderingCanvas.width = width;
  9080. this._renderingCanvas.height = height;
  9081. for (var index = 0; index < this.scenes.length; index++) {
  9082. var scene = this.scenes[index];
  9083. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9084. var cam = scene.cameras[camIndex];
  9085. cam._currentRenderId = 0;
  9086. }
  9087. }
  9088. if (this.onResizeObservable.hasObservers) {
  9089. this.onResizeObservable.notifyObservers(this);
  9090. }
  9091. };
  9092. // WebVR functions
  9093. Engine.prototype.isVRDevicePresent = function () {
  9094. return !!this._vrDisplay;
  9095. };
  9096. Engine.prototype.getVRDevice = function () {
  9097. return this._vrDisplay;
  9098. };
  9099. Engine.prototype.initWebVR = function () {
  9100. var _this = this;
  9101. var notifyObservers = function () {
  9102. var eventArgs = {
  9103. vrDisplay: _this._vrDisplay,
  9104. vrSupported: _this._vrSupported
  9105. };
  9106. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9107. };
  9108. if (!this._onVrDisplayConnect) {
  9109. this._onVrDisplayConnect = function (event) {
  9110. _this._vrDisplay = event.display;
  9111. notifyObservers();
  9112. };
  9113. this._onVrDisplayDisconnect = function () {
  9114. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9115. _this._vrDisplay = undefined;
  9116. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9117. notifyObservers();
  9118. };
  9119. this._onVrDisplayPresentChange = function () {
  9120. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9121. };
  9122. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9123. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9124. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9125. }
  9126. this._getVRDisplays(notifyObservers);
  9127. return this.onVRDisplayChangedObservable;
  9128. };
  9129. Engine.prototype.enableVR = function () {
  9130. var _this = this;
  9131. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9132. var onResolved = function () {
  9133. _this.onVRRequestPresentComplete.notifyObservers(true);
  9134. _this._onVRFullScreenTriggered();
  9135. };
  9136. var onRejected = function () {
  9137. _this.onVRRequestPresentComplete.notifyObservers(false);
  9138. };
  9139. this.onVRRequestPresentStart.notifyObservers(this);
  9140. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9141. }
  9142. };
  9143. Engine.prototype.disableVR = function () {
  9144. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9145. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9146. }
  9147. };
  9148. Engine.prototype._getVRDisplays = function (callback) {
  9149. var _this = this;
  9150. var getWebVRDevices = function (devices) {
  9151. _this._vrSupported = true;
  9152. // note that devices may actually be an empty array. This is fine;
  9153. // we expect this._vrDisplay to be undefined in this case.
  9154. return _this._vrDisplay = devices[0];
  9155. };
  9156. if (navigator.getVRDisplays) {
  9157. // TODO: Backwards compatible for 1.0?
  9158. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9159. // TODO: System CANNOT support WebVR, despite API presence.
  9160. _this._vrSupported = false;
  9161. callback();
  9162. });
  9163. }
  9164. else {
  9165. // TODO: Browser does not support WebVR
  9166. this._vrDisplay = undefined;
  9167. this._vrSupported = false;
  9168. callback();
  9169. }
  9170. };
  9171. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9172. if (this._currentRenderTarget) {
  9173. this.unBindFramebuffer(this._currentRenderTarget);
  9174. }
  9175. this._currentRenderTarget = texture;
  9176. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9177. var gl = this._gl;
  9178. if (texture.isCube) {
  9179. if (faceIndex === undefined) {
  9180. faceIndex = 0;
  9181. }
  9182. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9183. }
  9184. if (this._cachedViewport && !forceFullscreenViewport) {
  9185. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9186. }
  9187. else {
  9188. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9189. }
  9190. this.wipeCaches();
  9191. };
  9192. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9193. if (this._currentFramebuffer !== framebuffer) {
  9194. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9195. this._currentFramebuffer = framebuffer;
  9196. }
  9197. };
  9198. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9199. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9200. this._currentRenderTarget = null;
  9201. // If MSAA, we need to bitblt back to main texture
  9202. var gl = this._gl;
  9203. if (texture._MSAAFramebuffer) {
  9204. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9205. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9206. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9207. }
  9208. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9209. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9210. gl.generateMipmap(gl.TEXTURE_2D);
  9211. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9212. }
  9213. if (onBeforeUnbind) {
  9214. if (texture._MSAAFramebuffer) {
  9215. // Bind the correct framebuffer
  9216. this.bindUnboundFramebuffer(texture._framebuffer);
  9217. }
  9218. onBeforeUnbind();
  9219. }
  9220. this.bindUnboundFramebuffer(null);
  9221. };
  9222. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9223. if (texture.generateMipMaps) {
  9224. var gl = this._gl;
  9225. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9226. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9227. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9228. }
  9229. };
  9230. Engine.prototype.flushFramebuffer = function () {
  9231. this._gl.flush();
  9232. };
  9233. Engine.prototype.restoreDefaultFramebuffer = function () {
  9234. if (this._currentRenderTarget) {
  9235. this.unBindFramebuffer(this._currentRenderTarget);
  9236. }
  9237. else {
  9238. this.bindUnboundFramebuffer(null);
  9239. }
  9240. if (this._cachedViewport) {
  9241. this.setViewport(this._cachedViewport);
  9242. }
  9243. this.wipeCaches();
  9244. };
  9245. // UBOs
  9246. Engine.prototype.createUniformBuffer = function (elements) {
  9247. var ubo = this._gl.createBuffer();
  9248. if (!ubo) {
  9249. throw new Error("Unable to create uniform buffer");
  9250. }
  9251. this.bindUniformBuffer(ubo);
  9252. if (elements instanceof Float32Array) {
  9253. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9254. }
  9255. else {
  9256. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9257. }
  9258. this.bindUniformBuffer(null);
  9259. ubo.references = 1;
  9260. return ubo;
  9261. };
  9262. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9263. var ubo = this._gl.createBuffer();
  9264. if (!ubo) {
  9265. throw new Error("Unable to create dynamic uniform buffer");
  9266. }
  9267. this.bindUniformBuffer(ubo);
  9268. if (elements instanceof Float32Array) {
  9269. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9270. }
  9271. else {
  9272. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9273. }
  9274. this.bindUniformBuffer(null);
  9275. ubo.references = 1;
  9276. return ubo;
  9277. };
  9278. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9279. this.bindUniformBuffer(uniformBuffer);
  9280. if (offset === undefined) {
  9281. offset = 0;
  9282. }
  9283. if (count === undefined) {
  9284. if (elements instanceof Float32Array) {
  9285. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9286. }
  9287. else {
  9288. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9289. }
  9290. }
  9291. else {
  9292. if (elements instanceof Float32Array) {
  9293. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9294. }
  9295. else {
  9296. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9297. }
  9298. }
  9299. this.bindUniformBuffer(null);
  9300. };
  9301. // VBOs
  9302. Engine.prototype._resetVertexBufferBinding = function () {
  9303. this.bindArrayBuffer(null);
  9304. this._cachedVertexBuffers = null;
  9305. };
  9306. Engine.prototype.createVertexBuffer = function (vertices) {
  9307. var vbo = this._gl.createBuffer();
  9308. if (!vbo) {
  9309. throw new Error("Unable to create vertex buffer");
  9310. }
  9311. this.bindArrayBuffer(vbo);
  9312. if (vertices instanceof Float32Array) {
  9313. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9314. }
  9315. else {
  9316. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9317. }
  9318. this._resetVertexBufferBinding();
  9319. vbo.references = 1;
  9320. return vbo;
  9321. };
  9322. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9323. var vbo = this._gl.createBuffer();
  9324. if (!vbo) {
  9325. throw new Error("Unable to create dynamic vertex buffer");
  9326. }
  9327. this.bindArrayBuffer(vbo);
  9328. if (vertices instanceof Float32Array) {
  9329. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9330. }
  9331. else {
  9332. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9333. }
  9334. this._resetVertexBufferBinding();
  9335. vbo.references = 1;
  9336. return vbo;
  9337. };
  9338. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9339. if (offset === void 0) { offset = 0; }
  9340. // Force cache update
  9341. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9342. this.bindIndexBuffer(indexBuffer);
  9343. var arrayBuffer;
  9344. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9345. arrayBuffer = indices;
  9346. }
  9347. else {
  9348. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9349. }
  9350. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9351. this._resetIndexBufferBinding();
  9352. };
  9353. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9354. this.bindArrayBuffer(vertexBuffer);
  9355. if (offset === undefined) {
  9356. offset = 0;
  9357. }
  9358. if (count === undefined) {
  9359. if (vertices instanceof Float32Array) {
  9360. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9361. }
  9362. else {
  9363. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9364. }
  9365. }
  9366. else {
  9367. if (vertices instanceof Float32Array) {
  9368. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9369. }
  9370. else {
  9371. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9372. }
  9373. }
  9374. this._resetVertexBufferBinding();
  9375. };
  9376. Engine.prototype._resetIndexBufferBinding = function () {
  9377. this.bindIndexBuffer(null);
  9378. this._cachedIndexBuffer = null;
  9379. };
  9380. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9381. var vbo = this._gl.createBuffer();
  9382. if (!vbo) {
  9383. throw new Error("Unable to create index buffer");
  9384. }
  9385. this.bindIndexBuffer(vbo);
  9386. // Check for 32 bits indices
  9387. var arrayBuffer;
  9388. var need32Bits = false;
  9389. if (indices instanceof Uint16Array) {
  9390. arrayBuffer = indices;
  9391. }
  9392. else {
  9393. //check 32 bit support
  9394. if (this._caps.uintIndices) {
  9395. if (indices instanceof Uint32Array) {
  9396. arrayBuffer = indices;
  9397. need32Bits = true;
  9398. }
  9399. else {
  9400. //number[] or Int32Array, check if 32 bit is necessary
  9401. for (var index = 0; index < indices.length; index++) {
  9402. if (indices[index] > 65535) {
  9403. need32Bits = true;
  9404. break;
  9405. }
  9406. }
  9407. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9408. }
  9409. }
  9410. else {
  9411. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9412. arrayBuffer = new Uint16Array(indices);
  9413. }
  9414. }
  9415. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9416. this._resetIndexBufferBinding();
  9417. vbo.references = 1;
  9418. vbo.is32Bits = need32Bits;
  9419. return vbo;
  9420. };
  9421. Engine.prototype.bindArrayBuffer = function (buffer) {
  9422. if (!this._vaoRecordInProgress) {
  9423. this._unbindVertexArrayObject();
  9424. }
  9425. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9426. };
  9427. Engine.prototype.bindUniformBuffer = function (buffer) {
  9428. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9429. };
  9430. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9431. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9432. };
  9433. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9434. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9435. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9436. };
  9437. ;
  9438. Engine.prototype.bindIndexBuffer = function (buffer) {
  9439. if (!this._vaoRecordInProgress) {
  9440. this._unbindVertexArrayObject();
  9441. }
  9442. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9443. };
  9444. Engine.prototype.bindBuffer = function (buffer, target) {
  9445. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9446. this._gl.bindBuffer(target, buffer);
  9447. this._currentBoundBuffer[target] = buffer;
  9448. }
  9449. };
  9450. Engine.prototype.updateArrayBuffer = function (data) {
  9451. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9452. };
  9453. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9454. var pointer = this._currentBufferPointers[indx];
  9455. var changed = false;
  9456. if (!pointer.active) {
  9457. changed = true;
  9458. pointer.active = true;
  9459. pointer.index = indx;
  9460. pointer.size = size;
  9461. pointer.type = type;
  9462. pointer.normalized = normalized;
  9463. pointer.stride = stride;
  9464. pointer.offset = offset;
  9465. pointer.buffer = buffer;
  9466. }
  9467. else {
  9468. if (pointer.buffer !== buffer) {
  9469. pointer.buffer = buffer;
  9470. changed = true;
  9471. }
  9472. if (pointer.size !== size) {
  9473. pointer.size = size;
  9474. changed = true;
  9475. }
  9476. if (pointer.type !== type) {
  9477. pointer.type = type;
  9478. changed = true;
  9479. }
  9480. if (pointer.normalized !== normalized) {
  9481. pointer.normalized = normalized;
  9482. changed = true;
  9483. }
  9484. if (pointer.stride !== stride) {
  9485. pointer.stride = stride;
  9486. changed = true;
  9487. }
  9488. if (pointer.offset !== offset) {
  9489. pointer.offset = offset;
  9490. changed = true;
  9491. }
  9492. }
  9493. if (changed || this._vaoRecordInProgress) {
  9494. this.bindArrayBuffer(buffer);
  9495. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9496. }
  9497. };
  9498. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9499. if (indexBuffer == null) {
  9500. return;
  9501. }
  9502. if (this._cachedIndexBuffer !== indexBuffer) {
  9503. this._cachedIndexBuffer = indexBuffer;
  9504. this.bindIndexBuffer(indexBuffer);
  9505. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9506. }
  9507. };
  9508. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9509. var attributes = effect.getAttributesNames();
  9510. if (!this._vaoRecordInProgress) {
  9511. this._unbindVertexArrayObject();
  9512. }
  9513. this.unbindAllAttributes();
  9514. for (var index = 0; index < attributes.length; index++) {
  9515. var order = effect.getAttributeLocation(index);
  9516. if (order >= 0) {
  9517. var vertexBuffer = vertexBuffers[attributes[index]];
  9518. if (!vertexBuffer) {
  9519. continue;
  9520. }
  9521. this._gl.enableVertexAttribArray(order);
  9522. if (!this._vaoRecordInProgress) {
  9523. this._vertexAttribArraysEnabled[order] = true;
  9524. }
  9525. var buffer = vertexBuffer.getBuffer();
  9526. if (buffer) {
  9527. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9528. if (vertexBuffer.getIsInstanced()) {
  9529. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9530. if (!this._vaoRecordInProgress) {
  9531. this._currentInstanceLocations.push(order);
  9532. this._currentInstanceBuffers.push(buffer);
  9533. }
  9534. }
  9535. }
  9536. }
  9537. }
  9538. };
  9539. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9540. var vao = this._gl.createVertexArray();
  9541. this._vaoRecordInProgress = true;
  9542. this._gl.bindVertexArray(vao);
  9543. this._mustWipeVertexAttributes = true;
  9544. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9545. this.bindIndexBuffer(indexBuffer);
  9546. this._vaoRecordInProgress = false;
  9547. this._gl.bindVertexArray(null);
  9548. return vao;
  9549. };
  9550. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9551. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9552. this._cachedVertexArrayObject = vertexArrayObject;
  9553. this._gl.bindVertexArray(vertexArrayObject);
  9554. this._cachedVertexBuffers = null;
  9555. this._cachedIndexBuffer = null;
  9556. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9557. this._mustWipeVertexAttributes = true;
  9558. }
  9559. };
  9560. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9561. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9562. this._cachedVertexBuffers = vertexBuffer;
  9563. this._cachedEffectForVertexBuffers = effect;
  9564. var attributesCount = effect.getAttributesCount();
  9565. this._unbindVertexArrayObject();
  9566. this.unbindAllAttributes();
  9567. var offset = 0;
  9568. for (var index = 0; index < attributesCount; index++) {
  9569. if (index < vertexDeclaration.length) {
  9570. var order = effect.getAttributeLocation(index);
  9571. if (order >= 0) {
  9572. this._gl.enableVertexAttribArray(order);
  9573. this._vertexAttribArraysEnabled[order] = true;
  9574. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9575. }
  9576. offset += vertexDeclaration[index] * 4;
  9577. }
  9578. }
  9579. }
  9580. this._bindIndexBufferWithCache(indexBuffer);
  9581. };
  9582. Engine.prototype._unbindVertexArrayObject = function () {
  9583. if (!this._cachedVertexArrayObject) {
  9584. return;
  9585. }
  9586. this._cachedVertexArrayObject = null;
  9587. this._gl.bindVertexArray(null);
  9588. };
  9589. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9590. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9591. this._cachedVertexBuffers = vertexBuffers;
  9592. this._cachedEffectForVertexBuffers = effect;
  9593. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9594. }
  9595. this._bindIndexBufferWithCache(indexBuffer);
  9596. };
  9597. Engine.prototype.unbindInstanceAttributes = function () {
  9598. var boundBuffer;
  9599. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9600. var instancesBuffer = this._currentInstanceBuffers[i];
  9601. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9602. boundBuffer = instancesBuffer;
  9603. this.bindArrayBuffer(instancesBuffer);
  9604. }
  9605. var offsetLocation = this._currentInstanceLocations[i];
  9606. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9607. }
  9608. this._currentInstanceBuffers.length = 0;
  9609. this._currentInstanceLocations.length = 0;
  9610. };
  9611. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9612. this._gl.deleteVertexArray(vao);
  9613. };
  9614. Engine.prototype._releaseBuffer = function (buffer) {
  9615. buffer.references--;
  9616. if (buffer.references === 0) {
  9617. this._gl.deleteBuffer(buffer);
  9618. return true;
  9619. }
  9620. return false;
  9621. };
  9622. Engine.prototype.createInstancesBuffer = function (capacity) {
  9623. var buffer = this._gl.createBuffer();
  9624. if (!buffer) {
  9625. throw new Error("Unable to create instance buffer");
  9626. }
  9627. buffer.capacity = capacity;
  9628. this.bindArrayBuffer(buffer);
  9629. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9630. return buffer;
  9631. };
  9632. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9633. this._gl.deleteBuffer(buffer);
  9634. };
  9635. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9636. this.bindArrayBuffer(instancesBuffer);
  9637. if (data) {
  9638. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9639. }
  9640. if (offsetLocations[0].index !== undefined) {
  9641. var stride = 0;
  9642. for (var i = 0; i < offsetLocations.length; i++) {
  9643. var ai = offsetLocations[i];
  9644. stride += ai.attributeSize * 4;
  9645. }
  9646. for (var i = 0; i < offsetLocations.length; i++) {
  9647. var ai = offsetLocations[i];
  9648. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9649. this._gl.enableVertexAttribArray(ai.index);
  9650. this._vertexAttribArraysEnabled[ai.index] = true;
  9651. }
  9652. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9653. this._gl.vertexAttribDivisor(ai.index, 1);
  9654. this._currentInstanceLocations.push(ai.index);
  9655. this._currentInstanceBuffers.push(instancesBuffer);
  9656. }
  9657. }
  9658. else {
  9659. for (var index = 0; index < 4; index++) {
  9660. var offsetLocation = offsetLocations[index];
  9661. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9662. this._gl.enableVertexAttribArray(offsetLocation);
  9663. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9664. }
  9665. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9666. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9667. this._currentInstanceLocations.push(offsetLocation);
  9668. this._currentInstanceBuffers.push(instancesBuffer);
  9669. }
  9670. }
  9671. };
  9672. Engine.prototype.applyStates = function () {
  9673. this._depthCullingState.apply(this._gl);
  9674. this._stencilState.apply(this._gl);
  9675. this._alphaState.apply(this._gl);
  9676. };
  9677. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9678. // Apply states
  9679. this.applyStates();
  9680. this._drawCalls.addCount(1, false);
  9681. // Render
  9682. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9683. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9684. if (instancesCount) {
  9685. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9686. return;
  9687. }
  9688. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9689. };
  9690. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9691. // Apply states
  9692. this.applyStates();
  9693. this._drawCalls.addCount(1, false);
  9694. if (instancesCount) {
  9695. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9696. return;
  9697. }
  9698. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9699. };
  9700. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9701. // Apply states
  9702. this.applyStates();
  9703. this._drawCalls.addCount(1, false);
  9704. if (instancesCount) {
  9705. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9706. return;
  9707. }
  9708. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9709. };
  9710. // Shaders
  9711. Engine.prototype._releaseEffect = function (effect) {
  9712. if (this._compiledEffects[effect._key]) {
  9713. delete this._compiledEffects[effect._key];
  9714. this._deleteProgram(effect.getProgram());
  9715. }
  9716. };
  9717. Engine.prototype._deleteProgram = function (program) {
  9718. if (program) {
  9719. program.__SPECTOR_rebuildProgram = null;
  9720. this._gl.deleteProgram(program);
  9721. }
  9722. };
  9723. /**
  9724. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9725. * @param samplers An array of string used to represent textures
  9726. */
  9727. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9728. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9729. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9730. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9731. if (this._compiledEffects[name]) {
  9732. var compiledEffect = this._compiledEffects[name];
  9733. if (onCompiled && compiledEffect.isReady()) {
  9734. onCompiled(compiledEffect);
  9735. }
  9736. return compiledEffect;
  9737. }
  9738. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9739. effect._key = name;
  9740. this._compiledEffects[name] = effect;
  9741. return effect;
  9742. };
  9743. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9744. if (uniformsNames === void 0) { uniformsNames = []; }
  9745. if (samplers === void 0) { samplers = []; }
  9746. if (defines === void 0) { defines = ""; }
  9747. return this.createEffect({
  9748. vertex: "particles",
  9749. fragmentElement: fragmentName
  9750. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9751. };
  9752. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context) {
  9753. context = context || this._gl;
  9754. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9755. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9756. return this._createShaderProgram(vertexShader, fragmentShader, context);
  9757. };
  9758. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9759. context = context || this._gl;
  9760. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9761. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9762. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9763. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9764. var program = this._createShaderProgram(vertexShader, fragmentShader, context);
  9765. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9766. return program;
  9767. };
  9768. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context) {
  9769. var shaderProgram = context.createProgram();
  9770. if (!shaderProgram) {
  9771. throw new Error("Unable to create program");
  9772. }
  9773. context.attachShader(shaderProgram, vertexShader);
  9774. context.attachShader(shaderProgram, fragmentShader);
  9775. context.linkProgram(shaderProgram);
  9776. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9777. if (!linked) {
  9778. context.validateProgram(shaderProgram);
  9779. var error = context.getProgramInfoLog(shaderProgram);
  9780. if (error) {
  9781. throw new Error(error);
  9782. }
  9783. }
  9784. context.deleteShader(vertexShader);
  9785. context.deleteShader(fragmentShader);
  9786. return shaderProgram;
  9787. };
  9788. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9789. var results = new Array();
  9790. for (var index = 0; index < uniformsNames.length; index++) {
  9791. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9792. }
  9793. return results;
  9794. };
  9795. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9796. var results = [];
  9797. for (var index = 0; index < attributesNames.length; index++) {
  9798. try {
  9799. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9800. }
  9801. catch (e) {
  9802. results.push(-1);
  9803. }
  9804. }
  9805. return results;
  9806. };
  9807. Engine.prototype.enableEffect = function (effect) {
  9808. if (!effect) {
  9809. return;
  9810. }
  9811. // Use program
  9812. this.setProgram(effect.getProgram());
  9813. this._currentEffect = effect;
  9814. if (effect.onBind) {
  9815. effect.onBind(effect);
  9816. }
  9817. effect.onBindObservable.notifyObservers(effect);
  9818. };
  9819. Engine.prototype.setIntArray = function (uniform, array) {
  9820. if (!uniform)
  9821. return;
  9822. this._gl.uniform1iv(uniform, array);
  9823. };
  9824. Engine.prototype.setIntArray2 = function (uniform, array) {
  9825. if (!uniform || array.length % 2 !== 0)
  9826. return;
  9827. this._gl.uniform2iv(uniform, array);
  9828. };
  9829. Engine.prototype.setIntArray3 = function (uniform, array) {
  9830. if (!uniform || array.length % 3 !== 0)
  9831. return;
  9832. this._gl.uniform3iv(uniform, array);
  9833. };
  9834. Engine.prototype.setIntArray4 = function (uniform, array) {
  9835. if (!uniform || array.length % 4 !== 0)
  9836. return;
  9837. this._gl.uniform4iv(uniform, array);
  9838. };
  9839. Engine.prototype.setFloatArray = function (uniform, array) {
  9840. if (!uniform)
  9841. return;
  9842. this._gl.uniform1fv(uniform, array);
  9843. };
  9844. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9845. if (!uniform || array.length % 2 !== 0)
  9846. return;
  9847. this._gl.uniform2fv(uniform, array);
  9848. };
  9849. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9850. if (!uniform || array.length % 3 !== 0)
  9851. return;
  9852. this._gl.uniform3fv(uniform, array);
  9853. };
  9854. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9855. if (!uniform || array.length % 4 !== 0)
  9856. return;
  9857. this._gl.uniform4fv(uniform, array);
  9858. };
  9859. Engine.prototype.setArray = function (uniform, array) {
  9860. if (!uniform)
  9861. return;
  9862. this._gl.uniform1fv(uniform, array);
  9863. };
  9864. Engine.prototype.setArray2 = function (uniform, array) {
  9865. if (!uniform || array.length % 2 !== 0)
  9866. return;
  9867. this._gl.uniform2fv(uniform, array);
  9868. };
  9869. Engine.prototype.setArray3 = function (uniform, array) {
  9870. if (!uniform || array.length % 3 !== 0)
  9871. return;
  9872. this._gl.uniform3fv(uniform, array);
  9873. };
  9874. Engine.prototype.setArray4 = function (uniform, array) {
  9875. if (!uniform || array.length % 4 !== 0)
  9876. return;
  9877. this._gl.uniform4fv(uniform, array);
  9878. };
  9879. Engine.prototype.setMatrices = function (uniform, matrices) {
  9880. if (!uniform)
  9881. return;
  9882. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9883. };
  9884. Engine.prototype.setMatrix = function (uniform, matrix) {
  9885. if (!uniform)
  9886. return;
  9887. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9888. };
  9889. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9890. if (!uniform)
  9891. return;
  9892. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9893. };
  9894. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9895. if (!uniform)
  9896. return;
  9897. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9898. };
  9899. Engine.prototype.setFloat = function (uniform, value) {
  9900. if (!uniform)
  9901. return;
  9902. this._gl.uniform1f(uniform, value);
  9903. };
  9904. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9905. if (!uniform)
  9906. return;
  9907. this._gl.uniform2f(uniform, x, y);
  9908. };
  9909. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9910. if (!uniform)
  9911. return;
  9912. this._gl.uniform3f(uniform, x, y, z);
  9913. };
  9914. Engine.prototype.setBool = function (uniform, bool) {
  9915. if (!uniform)
  9916. return;
  9917. this._gl.uniform1i(uniform, bool);
  9918. };
  9919. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9920. if (!uniform)
  9921. return;
  9922. this._gl.uniform4f(uniform, x, y, z, w);
  9923. };
  9924. Engine.prototype.setColor3 = function (uniform, color3) {
  9925. if (!uniform)
  9926. return;
  9927. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9928. };
  9929. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9930. if (!uniform)
  9931. return;
  9932. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9933. };
  9934. // States
  9935. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9936. if (zOffset === void 0) { zOffset = 0; }
  9937. if (reverseSide === void 0) { reverseSide = false; }
  9938. // Culling
  9939. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9940. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9941. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9942. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9943. if (culling) {
  9944. this._depthCullingState.cullFace = cullFace;
  9945. this._depthCullingState.cull = true;
  9946. }
  9947. else {
  9948. this._depthCullingState.cull = false;
  9949. }
  9950. }
  9951. // Z offset
  9952. this.setZOffset(zOffset);
  9953. };
  9954. Engine.prototype.setZOffset = function (value) {
  9955. this._depthCullingState.zOffset = value;
  9956. };
  9957. Engine.prototype.getZOffset = function () {
  9958. return this._depthCullingState.zOffset;
  9959. };
  9960. Engine.prototype.setDepthBuffer = function (enable) {
  9961. this._depthCullingState.depthTest = enable;
  9962. };
  9963. Engine.prototype.getDepthWrite = function () {
  9964. return this._depthCullingState.depthMask;
  9965. };
  9966. Engine.prototype.setDepthWrite = function (enable) {
  9967. this._depthCullingState.depthMask = enable;
  9968. };
  9969. Engine.prototype.setColorWrite = function (enable) {
  9970. this._gl.colorMask(enable, enable, enable, enable);
  9971. this._colorWrite = enable;
  9972. };
  9973. Engine.prototype.getColorWrite = function () {
  9974. return this._colorWrite;
  9975. };
  9976. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9977. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9978. };
  9979. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9980. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9981. if (this._alphaMode === mode) {
  9982. return;
  9983. }
  9984. switch (mode) {
  9985. case Engine.ALPHA_DISABLE:
  9986. this._alphaState.alphaBlend = false;
  9987. break;
  9988. case Engine.ALPHA_PREMULTIPLIED:
  9989. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9990. this._alphaState.alphaBlend = true;
  9991. break;
  9992. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9993. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9994. this._alphaState.alphaBlend = true;
  9995. break;
  9996. case Engine.ALPHA_COMBINE:
  9997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9998. this._alphaState.alphaBlend = true;
  9999. break;
  10000. case Engine.ALPHA_ONEONE:
  10001. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10002. this._alphaState.alphaBlend = true;
  10003. break;
  10004. case Engine.ALPHA_ADD:
  10005. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10006. this._alphaState.alphaBlend = true;
  10007. break;
  10008. case Engine.ALPHA_SUBTRACT:
  10009. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10010. this._alphaState.alphaBlend = true;
  10011. break;
  10012. case Engine.ALPHA_MULTIPLY:
  10013. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10014. this._alphaState.alphaBlend = true;
  10015. break;
  10016. case Engine.ALPHA_MAXIMIZED:
  10017. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10018. this._alphaState.alphaBlend = true;
  10019. break;
  10020. case Engine.ALPHA_INTERPOLATE:
  10021. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10022. this._alphaState.alphaBlend = true;
  10023. break;
  10024. case Engine.ALPHA_SCREENMODE:
  10025. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10026. this._alphaState.alphaBlend = true;
  10027. break;
  10028. }
  10029. if (!noDepthWriteChange) {
  10030. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10031. }
  10032. this._alphaMode = mode;
  10033. };
  10034. Engine.prototype.getAlphaMode = function () {
  10035. return this._alphaMode;
  10036. };
  10037. Engine.prototype.setAlphaTesting = function (enable) {
  10038. this._alphaTest = enable;
  10039. };
  10040. Engine.prototype.getAlphaTesting = function () {
  10041. return !!this._alphaTest;
  10042. };
  10043. // Textures
  10044. Engine.prototype.wipeCaches = function (bruteForce) {
  10045. if (this.preventCacheWipeBetweenFrames) {
  10046. return;
  10047. }
  10048. this.resetTextureCache();
  10049. this._currentEffect = null;
  10050. // 6/8/2017: deltakosh: Should not be required anymore.
  10051. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10052. if (bruteForce) {
  10053. this._currentProgram = null;
  10054. this._stencilState.reset();
  10055. this._depthCullingState.reset();
  10056. this.setDepthFunctionToLessOrEqual();
  10057. this._alphaState.reset();
  10058. }
  10059. this._cachedVertexBuffers = null;
  10060. this._cachedIndexBuffer = null;
  10061. this._cachedEffectForVertexBuffers = null;
  10062. this._unbindVertexArrayObject();
  10063. this.bindIndexBuffer(null);
  10064. this.bindArrayBuffer(null);
  10065. };
  10066. /**
  10067. * Set the compressed texture format to use, based on the formats you have, and the formats
  10068. * supported by the hardware / browser.
  10069. *
  10070. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10071. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10072. * to API arguments needed to compressed textures. This puts the burden on the container
  10073. * generator to house the arcane code for determining these for current & future formats.
  10074. *
  10075. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10076. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10077. *
  10078. * Note: The result of this call is not taken into account when a texture is base64.
  10079. *
  10080. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10081. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10082. *
  10083. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10084. * @returns The extension selected.
  10085. */
  10086. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10087. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10088. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10089. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10090. return this._textureFormatInUse = this._texturesSupported[i];
  10091. }
  10092. }
  10093. }
  10094. // actively set format to nothing, to allow this to be called more than once
  10095. // and possibly fail the 2nd time
  10096. this._textureFormatInUse = null;
  10097. return null;
  10098. };
  10099. Engine.prototype._createTexture = function () {
  10100. var texture = this._gl.createTexture();
  10101. if (!texture) {
  10102. throw new Error("Unable to create texture");
  10103. }
  10104. return texture;
  10105. };
  10106. /**
  10107. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10108. * @param {string} urlArg- This contains one of the following:
  10109. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10110. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10111. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10112. *
  10113. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10114. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10115. * @param {Scene} scene- Needed for loading to the correct scene.
  10116. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10117. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10118. * @param {callback} onError- Optional callback to be called upon failure.
  10119. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10120. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10121. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10122. *
  10123. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10124. */
  10125. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10126. var _this = this;
  10127. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10128. if (onLoad === void 0) { onLoad = null; }
  10129. if (onError === void 0) { onError = null; }
  10130. if (buffer === void 0) { buffer = null; }
  10131. if (fallBack === void 0) { fallBack = null; }
  10132. if (format === void 0) { format = null; }
  10133. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10134. var fromData = url.substr(0, 5) === "data:";
  10135. var fromBlob = url.substr(0, 5) === "blob:";
  10136. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10137. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10138. // establish the file extension, if possible
  10139. var lastDot = url.lastIndexOf('.');
  10140. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10141. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10142. var isTGA = (extension === ".tga");
  10143. // determine if a ktx file should be substituted
  10144. var isKTX = false;
  10145. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10146. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10147. isKTX = true;
  10148. }
  10149. if (scene) {
  10150. scene._addPendingData(texture);
  10151. }
  10152. texture.url = url;
  10153. texture.generateMipMaps = !noMipmap;
  10154. texture.samplingMode = samplingMode;
  10155. texture.invertY = invertY;
  10156. if (!this._doNotHandleContextLost) {
  10157. // Keep a link to the buffer only if we plan to handle context lost
  10158. texture._buffer = buffer;
  10159. }
  10160. if (onLoad) {
  10161. texture.onLoadedObservable.add(onLoad);
  10162. }
  10163. if (!fallBack)
  10164. this._internalTexturesCache.push(texture);
  10165. var onerror = function () {
  10166. if (scene) {
  10167. scene._removePendingData(texture);
  10168. }
  10169. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10170. if (isKTX) {
  10171. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10172. }
  10173. else if (onError) {
  10174. onError();
  10175. }
  10176. };
  10177. var callback = null;
  10178. // processing for non-image formats
  10179. if (isKTX || isTGA || isDDS) {
  10180. if (isKTX) {
  10181. callback = function (data) {
  10182. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10183. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10184. ktx.uploadLevels(_this._gl, !noMipmap);
  10185. return false;
  10186. }, samplingMode);
  10187. };
  10188. }
  10189. else if (isTGA) {
  10190. callback = function (arrayBuffer) {
  10191. var data = new Uint8Array(arrayBuffer);
  10192. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10193. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10194. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10195. return false;
  10196. }, samplingMode);
  10197. };
  10198. }
  10199. else if (isDDS) {
  10200. callback = function (data) {
  10201. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10202. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10203. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10204. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10205. return false;
  10206. }, samplingMode);
  10207. };
  10208. }
  10209. if (!buffer) {
  10210. BABYLON.Tools.LoadFile(url, function (data) {
  10211. if (callback) {
  10212. callback(data);
  10213. }
  10214. }, undefined, scene ? scene.database : undefined, true, onerror);
  10215. }
  10216. else {
  10217. if (callback) {
  10218. callback(buffer);
  10219. }
  10220. }
  10221. // image format processing
  10222. }
  10223. else {
  10224. var onload = function (img) {
  10225. if (fromBlob && !_this._doNotHandleContextLost) {
  10226. // We need to store the image if we need to rebuild the texture
  10227. // in case of a webgl context lost
  10228. texture._buffer = img;
  10229. }
  10230. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10231. var gl = _this._gl;
  10232. var isPot = (img.width === potWidth && img.height === potHeight);
  10233. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10234. if (isPot) {
  10235. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10236. return false;
  10237. }
  10238. // Using shaders to rescale because canvas.drawImage is lossy
  10239. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10240. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10241. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10243. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10244. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10245. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10246. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10247. _this._releaseTexture(source);
  10248. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10249. continuationCallback();
  10250. });
  10251. return true;
  10252. }, samplingMode);
  10253. };
  10254. if (!fromData || isBase64)
  10255. if (buffer instanceof HTMLImageElement) {
  10256. onload(buffer);
  10257. }
  10258. else {
  10259. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10260. }
  10261. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10262. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10263. else
  10264. onload(buffer);
  10265. }
  10266. return texture;
  10267. };
  10268. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10269. var _this = this;
  10270. var rtt = this.createRenderTargetTexture({
  10271. width: destination.width,
  10272. height: destination.height,
  10273. }, {
  10274. generateMipMaps: false,
  10275. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10276. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10277. generateDepthBuffer: false,
  10278. generateStencilBuffer: false
  10279. });
  10280. if (!this._rescalePostProcess) {
  10281. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10282. }
  10283. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10284. _this._rescalePostProcess.onApply = function (effect) {
  10285. effect._bindTexture("textureSampler", source);
  10286. };
  10287. var hostingScene = scene;
  10288. if (!hostingScene) {
  10289. hostingScene = _this.scenes[_this.scenes.length - 1];
  10290. }
  10291. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10292. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10293. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10294. _this.unBindFramebuffer(rtt);
  10295. _this._releaseTexture(rtt);
  10296. if (onComplete) {
  10297. onComplete();
  10298. }
  10299. });
  10300. };
  10301. Engine.prototype._getInternalFormat = function (format) {
  10302. var internalFormat = this._gl.RGBA;
  10303. switch (format) {
  10304. case Engine.TEXTUREFORMAT_ALPHA:
  10305. internalFormat = this._gl.ALPHA;
  10306. break;
  10307. case Engine.TEXTUREFORMAT_LUMINANCE:
  10308. internalFormat = this._gl.LUMINANCE;
  10309. break;
  10310. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10311. internalFormat = this._gl.LUMINANCE_ALPHA;
  10312. break;
  10313. case Engine.TEXTUREFORMAT_RGB:
  10314. internalFormat = this._gl.RGB;
  10315. break;
  10316. case Engine.TEXTUREFORMAT_RGBA:
  10317. internalFormat = this._gl.RGBA;
  10318. break;
  10319. }
  10320. return internalFormat;
  10321. };
  10322. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10323. if (compression === void 0) { compression = null; }
  10324. if (!texture) {
  10325. return;
  10326. }
  10327. var internalFormat = this._getInternalFormat(format);
  10328. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10329. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10330. if (!this._doNotHandleContextLost) {
  10331. texture._bufferView = data;
  10332. texture.format = format;
  10333. texture.invertY = invertY;
  10334. texture._compression = compression;
  10335. }
  10336. if (texture.width % 4 !== 0) {
  10337. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10338. }
  10339. if (compression && data) {
  10340. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10341. }
  10342. else {
  10343. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10344. }
  10345. if (texture.generateMipMaps) {
  10346. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10347. }
  10348. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10349. this.resetTextureCache();
  10350. texture.isReady = true;
  10351. };
  10352. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10353. if (compression === void 0) { compression = null; }
  10354. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10355. texture.baseWidth = width;
  10356. texture.baseHeight = height;
  10357. texture.width = width;
  10358. texture.height = height;
  10359. texture.format = format;
  10360. texture.generateMipMaps = generateMipMaps;
  10361. texture.samplingMode = samplingMode;
  10362. texture.invertY = invertY;
  10363. texture._compression = compression;
  10364. if (!this._doNotHandleContextLost) {
  10365. texture._bufferView = data;
  10366. }
  10367. this.updateRawTexture(texture, data, format, invertY, compression);
  10368. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10369. // Filters
  10370. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10371. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10372. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10373. if (generateMipMaps) {
  10374. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10375. }
  10376. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10377. this._internalTexturesCache.push(texture);
  10378. return texture;
  10379. };
  10380. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10381. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10382. texture.baseWidth = width;
  10383. texture.baseHeight = height;
  10384. if (generateMipMaps) {
  10385. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10386. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10387. }
  10388. this.resetTextureCache();
  10389. texture.width = width;
  10390. texture.height = height;
  10391. texture.isReady = false;
  10392. texture.generateMipMaps = generateMipMaps;
  10393. texture.samplingMode = samplingMode;
  10394. this.updateTextureSamplingMode(samplingMode, texture);
  10395. this._internalTexturesCache.push(texture);
  10396. return texture;
  10397. };
  10398. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10399. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10400. if (texture.isCube) {
  10401. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10402. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10403. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10404. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10405. }
  10406. else if (texture.is3D) {
  10407. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10408. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10409. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10410. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10411. }
  10412. else {
  10413. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10414. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10415. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10416. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10417. }
  10418. texture.samplingMode = samplingMode;
  10419. };
  10420. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10421. if (premulAlpha === void 0) { premulAlpha = false; }
  10422. if (!texture) {
  10423. return;
  10424. }
  10425. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10426. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10427. if (premulAlpha) {
  10428. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10429. }
  10430. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10431. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10432. if (texture.generateMipMaps) {
  10433. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10434. }
  10435. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10436. if (premulAlpha) {
  10437. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10438. }
  10439. this.resetTextureCache();
  10440. texture.isReady = true;
  10441. };
  10442. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10443. if (!texture || texture._isDisabled) {
  10444. return;
  10445. }
  10446. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10447. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10448. try {
  10449. // Testing video texture support
  10450. if (this._videoTextureSupported === undefined) {
  10451. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10452. if (this._gl.getError() !== 0) {
  10453. this._videoTextureSupported = false;
  10454. }
  10455. else {
  10456. this._videoTextureSupported = true;
  10457. }
  10458. }
  10459. // Copy video through the current working canvas if video texture is not supported
  10460. if (!this._videoTextureSupported) {
  10461. if (!texture._workingCanvas) {
  10462. texture._workingCanvas = document.createElement("canvas");
  10463. var context = texture._workingCanvas.getContext("2d");
  10464. if (!context) {
  10465. throw new Error("Unable to get 2d context");
  10466. }
  10467. texture._workingContext = context;
  10468. texture._workingCanvas.width = texture.width;
  10469. texture._workingCanvas.height = texture.height;
  10470. }
  10471. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10472. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10473. }
  10474. else {
  10475. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10476. }
  10477. if (texture.generateMipMaps) {
  10478. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10479. }
  10480. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10481. this.resetTextureCache();
  10482. texture.isReady = true;
  10483. }
  10484. catch (ex) {
  10485. // Something unexpected
  10486. // Let's disable the texture
  10487. texture._isDisabled = true;
  10488. }
  10489. };
  10490. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10491. var fullOptions = new RenderTargetCreationOptions();
  10492. if (options !== undefined && typeof options === "object") {
  10493. fullOptions.generateMipMaps = options.generateMipMaps;
  10494. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10495. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10496. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10497. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10498. }
  10499. else {
  10500. fullOptions.generateMipMaps = options;
  10501. fullOptions.generateDepthBuffer = true;
  10502. fullOptions.generateStencilBuffer = false;
  10503. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10504. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10505. }
  10506. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10507. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10508. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10509. }
  10510. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10511. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10512. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10513. }
  10514. var gl = this._gl;
  10515. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10516. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10517. var width = size.width || size;
  10518. var height = size.height || size;
  10519. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10520. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10521. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10522. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10523. }
  10524. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10525. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10526. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10527. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10528. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10529. // Create the framebuffer
  10530. var framebuffer = gl.createFramebuffer();
  10531. this.bindUnboundFramebuffer(framebuffer);
  10532. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10533. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10534. if (fullOptions.generateMipMaps) {
  10535. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10536. }
  10537. // Unbind
  10538. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10539. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10540. this.bindUnboundFramebuffer(null);
  10541. texture._framebuffer = framebuffer;
  10542. texture.baseWidth = width;
  10543. texture.baseHeight = height;
  10544. texture.width = width;
  10545. texture.height = height;
  10546. texture.isReady = true;
  10547. texture.samples = 1;
  10548. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10549. texture.samplingMode = fullOptions.samplingMode;
  10550. texture.type = fullOptions.type;
  10551. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10552. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10553. this.resetTextureCache();
  10554. this._internalTexturesCache.push(texture);
  10555. return texture;
  10556. };
  10557. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10558. var generateMipMaps = false;
  10559. var generateDepthBuffer = true;
  10560. var generateStencilBuffer = false;
  10561. var generateDepthTexture = false;
  10562. var textureCount = 1;
  10563. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10564. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10565. var types = [], samplingModes = [];
  10566. if (options !== undefined) {
  10567. generateMipMaps = options.generateMipMaps;
  10568. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10569. generateStencilBuffer = options.generateStencilBuffer;
  10570. generateDepthTexture = options.generateDepthTexture;
  10571. textureCount = options.textureCount || 1;
  10572. if (options.types) {
  10573. types = options.types;
  10574. }
  10575. if (options.samplingModes) {
  10576. samplingModes = options.samplingModes;
  10577. }
  10578. }
  10579. var gl = this._gl;
  10580. // Create the framebuffer
  10581. var framebuffer = gl.createFramebuffer();
  10582. this.bindUnboundFramebuffer(framebuffer);
  10583. var width = size.width || size;
  10584. var height = size.height || size;
  10585. var textures = [];
  10586. var attachments = [];
  10587. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10588. for (var i = 0; i < textureCount; i++) {
  10589. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10590. var type = types[i] || defaultType;
  10591. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10592. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10593. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10594. }
  10595. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10596. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10597. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10598. }
  10599. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10600. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10601. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10602. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10603. }
  10604. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10605. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10606. textures.push(texture);
  10607. attachments.push(attachment);
  10608. gl.activeTexture(gl["TEXTURE" + i]);
  10609. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10610. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10611. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10612. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10613. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10614. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10615. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10616. if (generateMipMaps) {
  10617. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10618. }
  10619. // Unbind
  10620. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10621. texture._framebuffer = framebuffer;
  10622. texture._depthStencilBuffer = depthStencilBuffer;
  10623. texture.baseWidth = width;
  10624. texture.baseHeight = height;
  10625. texture.width = width;
  10626. texture.height = height;
  10627. texture.isReady = true;
  10628. texture.samples = 1;
  10629. texture.generateMipMaps = generateMipMaps;
  10630. texture.samplingMode = samplingMode;
  10631. texture.type = type;
  10632. texture._generateDepthBuffer = generateDepthBuffer;
  10633. texture._generateStencilBuffer = generateStencilBuffer;
  10634. this._internalTexturesCache.push(texture);
  10635. }
  10636. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10637. // Depth texture
  10638. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10639. gl.activeTexture(gl.TEXTURE0);
  10640. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10641. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10642. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10643. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10644. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10645. 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);
  10646. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10647. depthTexture._framebuffer = framebuffer;
  10648. depthTexture.baseWidth = width;
  10649. depthTexture.baseHeight = height;
  10650. depthTexture.width = width;
  10651. depthTexture.height = height;
  10652. depthTexture.isReady = true;
  10653. depthTexture.samples = 1;
  10654. depthTexture.generateMipMaps = generateMipMaps;
  10655. depthTexture.samplingMode = gl.NEAREST;
  10656. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10657. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10658. textures.push(depthTexture);
  10659. this._internalTexturesCache.push(depthTexture);
  10660. }
  10661. gl.drawBuffers(attachments);
  10662. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10663. this.bindUnboundFramebuffer(null);
  10664. this.resetTextureCache();
  10665. return textures;
  10666. };
  10667. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10668. if (samples === void 0) { samples = 1; }
  10669. var depthStencilBuffer = null;
  10670. var gl = this._gl;
  10671. // Create the depth/stencil buffer
  10672. if (generateStencilBuffer) {
  10673. depthStencilBuffer = gl.createRenderbuffer();
  10674. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10675. if (samples > 1) {
  10676. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10677. }
  10678. else {
  10679. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10680. }
  10681. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10682. }
  10683. else if (generateDepthBuffer) {
  10684. depthStencilBuffer = gl.createRenderbuffer();
  10685. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10686. if (samples > 1) {
  10687. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10688. }
  10689. else {
  10690. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10691. }
  10692. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10693. }
  10694. return depthStencilBuffer;
  10695. };
  10696. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10697. if (this.webGLVersion < 2 || !texture) {
  10698. return 1;
  10699. }
  10700. if (texture.samples === samples) {
  10701. return samples;
  10702. }
  10703. var gl = this._gl;
  10704. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10705. // Dispose previous render buffers
  10706. if (texture._depthStencilBuffer) {
  10707. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10708. }
  10709. if (texture._MSAAFramebuffer) {
  10710. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10711. }
  10712. if (texture._MSAARenderBuffer) {
  10713. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10714. }
  10715. if (samples > 1) {
  10716. var framebuffer = gl.createFramebuffer();
  10717. if (!framebuffer) {
  10718. throw new Error("Unable to create multi sampled framebuffer");
  10719. }
  10720. texture._MSAAFramebuffer = framebuffer;
  10721. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10722. var colorRenderbuffer = gl.createRenderbuffer();
  10723. if (!colorRenderbuffer) {
  10724. throw new Error("Unable to create multi sampled framebuffer");
  10725. }
  10726. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10727. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10728. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10729. texture._MSAARenderBuffer = colorRenderbuffer;
  10730. }
  10731. else {
  10732. this.bindUnboundFramebuffer(texture._framebuffer);
  10733. }
  10734. texture.samples = samples;
  10735. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10736. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10737. this.bindUnboundFramebuffer(null);
  10738. return samples;
  10739. };
  10740. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10741. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10742. };
  10743. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10744. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10745. };
  10746. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10747. var gl = this._gl;
  10748. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10749. var generateMipMaps = true;
  10750. var generateDepthBuffer = true;
  10751. var generateStencilBuffer = false;
  10752. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10753. if (options !== undefined) {
  10754. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10755. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10756. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10757. if (options.samplingMode !== undefined) {
  10758. samplingMode = options.samplingMode;
  10759. }
  10760. }
  10761. texture.isCube = true;
  10762. texture.generateMipMaps = generateMipMaps;
  10763. texture.samples = 1;
  10764. texture.samplingMode = samplingMode;
  10765. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10766. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10767. for (var face = 0; face < 6; face++) {
  10768. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10769. }
  10770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10771. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10772. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10774. // Create the framebuffer
  10775. var framebuffer = gl.createFramebuffer();
  10776. this.bindUnboundFramebuffer(framebuffer);
  10777. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10778. // Mipmaps
  10779. if (texture.generateMipMaps) {
  10780. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10781. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10782. }
  10783. // Unbind
  10784. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10785. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10786. this.bindUnboundFramebuffer(null);
  10787. texture._framebuffer = framebuffer;
  10788. texture.width = size;
  10789. texture.height = size;
  10790. texture.isReady = true;
  10791. this.resetTextureCache();
  10792. this._internalTexturesCache.push(texture);
  10793. return texture;
  10794. };
  10795. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10796. var _this = this;
  10797. if (onLoad === void 0) { onLoad = null; }
  10798. if (onError === void 0) { onError = null; }
  10799. if (forcedExtension === void 0) { forcedExtension = null; }
  10800. var callback = function (loadData) {
  10801. if (!loadData) {
  10802. if (onLoad) {
  10803. onLoad(null);
  10804. }
  10805. return;
  10806. }
  10807. var texture = loadData.texture;
  10808. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10809. texture._lodGenerationScale = scale;
  10810. texture._lodGenerationOffset = offset;
  10811. if (_this._caps.textureLOD) {
  10812. // Do not add extra process if texture lod is supported.
  10813. if (onLoad) {
  10814. onLoad(texture);
  10815. }
  10816. return;
  10817. }
  10818. var mipSlices = 3;
  10819. var gl = _this._gl;
  10820. var width = loadData.width;
  10821. if (!width) {
  10822. return;
  10823. }
  10824. var textures = [];
  10825. for (var i = 0; i < mipSlices; i++) {
  10826. //compute LOD from even spacing in smoothness (matching shader calculation)
  10827. var smoothness = i / (mipSlices - 1);
  10828. var roughness = 1 - smoothness;
  10829. var minLODIndex = offset; // roughness = 0
  10830. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10831. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10832. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10833. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10834. glTextureFromLod.isCube = true;
  10835. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10837. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10838. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10839. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10840. if (loadData.isDDS) {
  10841. var info = loadData.info;
  10842. var data = loadData.data;
  10843. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10844. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10845. }
  10846. else {
  10847. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10848. }
  10849. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10850. // Wrap in a base texture for easy binding.
  10851. var lodTexture = new BABYLON.BaseTexture(scene);
  10852. lodTexture.isCube = true;
  10853. lodTexture._texture = glTextureFromLod;
  10854. glTextureFromLod.isReady = true;
  10855. textures.push(lodTexture);
  10856. }
  10857. texture._lodTextureHigh = textures[2];
  10858. texture._lodTextureMid = textures[1];
  10859. texture._lodTextureLow = textures[0];
  10860. if (onLoad) {
  10861. onLoad(texture);
  10862. }
  10863. };
  10864. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10865. };
  10866. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10867. var _this = this;
  10868. if (onLoad === void 0) { onLoad = null; }
  10869. if (onError === void 0) { onError = null; }
  10870. if (forcedExtension === void 0) { forcedExtension = null; }
  10871. var gl = this._gl;
  10872. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10873. texture.isCube = true;
  10874. texture.url = rootUrl;
  10875. texture.generateMipMaps = !noMipmap;
  10876. if (!this._doNotHandleContextLost) {
  10877. texture._extension = forcedExtension;
  10878. texture._files = files;
  10879. }
  10880. var isKTX = false;
  10881. var isDDS = false;
  10882. var lastDot = rootUrl.lastIndexOf('.');
  10883. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  10884. if (this._textureFormatInUse) {
  10885. extension = this._textureFormatInUse;
  10886. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  10887. isKTX = true;
  10888. }
  10889. else {
  10890. isDDS = (extension === ".dds");
  10891. }
  10892. var onerror = function (request, exception) {
  10893. if (onError) {
  10894. onError(request.status + " " + request.statusText, exception);
  10895. }
  10896. };
  10897. if (isKTX) {
  10898. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10899. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10900. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10901. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10902. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10903. ktx.uploadLevels(_this._gl, !noMipmap);
  10904. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10908. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10909. _this.resetTextureCache();
  10910. texture.width = ktx.pixelWidth;
  10911. texture.height = ktx.pixelHeight;
  10912. texture.isReady = true;
  10913. }, undefined, undefined, true, onerror);
  10914. }
  10915. else if (isDDS) {
  10916. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10917. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10918. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10919. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10920. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10921. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10922. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10923. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10924. }
  10925. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10926. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10929. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10930. _this.resetTextureCache();
  10931. texture.width = info.width;
  10932. texture.height = info.height;
  10933. texture.isReady = true;
  10934. texture.type = info.textureType;
  10935. if (onLoad) {
  10936. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10937. }
  10938. }, undefined, undefined, true, onerror);
  10939. }
  10940. else {
  10941. if (!files) {
  10942. throw new Error("Cannot load cubemap because files were not defined");
  10943. }
  10944. cascadeLoad(rootUrl, scene, function (imgs) {
  10945. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10946. var height = width;
  10947. _this._prepareWorkingCanvas();
  10948. if (!_this._workingCanvas || !_this._workingContext) {
  10949. return;
  10950. }
  10951. _this._workingCanvas.width = width;
  10952. _this._workingCanvas.height = height;
  10953. var faces = [
  10954. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10955. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10956. ];
  10957. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10958. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10959. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10960. for (var index = 0; index < faces.length; index++) {
  10961. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10962. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10963. }
  10964. if (!noMipmap) {
  10965. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10966. }
  10967. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10968. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10969. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10970. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10971. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10972. _this.resetTextureCache();
  10973. texture.width = width;
  10974. texture.height = height;
  10975. texture.isReady = true;
  10976. if (format) {
  10977. texture.format = format;
  10978. }
  10979. texture.onLoadedObservable.notifyObservers(texture);
  10980. texture.onLoadedObservable.clear();
  10981. if (onLoad) {
  10982. onLoad();
  10983. }
  10984. }, files, onError);
  10985. }
  10986. this._internalTexturesCache.push(texture);
  10987. return texture;
  10988. };
  10989. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10990. if (compression === void 0) { compression = null; }
  10991. if (level === void 0) { level = 0; }
  10992. texture._bufferViewArray = data;
  10993. texture.format = format;
  10994. texture.type = type;
  10995. texture.invertY = invertY;
  10996. texture._compression = compression;
  10997. var gl = this._gl;
  10998. var textureType = this._getWebGLTextureType(type);
  10999. var internalFormat = this._getInternalFormat(format);
  11000. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11001. var needConversion = false;
  11002. if (internalFormat === gl.RGB) {
  11003. internalFormat = gl.RGBA;
  11004. needConversion = true;
  11005. }
  11006. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11007. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11008. if (texture.width % 4 !== 0) {
  11009. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11010. }
  11011. // Data are known to be in +X +Y +Z -X -Y -Z
  11012. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11013. var faceData = data[faceIndex];
  11014. if (compression) {
  11015. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11016. }
  11017. else {
  11018. if (needConversion) {
  11019. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11020. }
  11021. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11022. }
  11023. }
  11024. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11025. if (isPot && texture.generateMipMaps && level === 0) {
  11026. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11027. }
  11028. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11029. this.resetTextureCache();
  11030. texture.isReady = true;
  11031. };
  11032. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11033. if (compression === void 0) { compression = null; }
  11034. var gl = this._gl;
  11035. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11036. texture.isCube = true;
  11037. texture.generateMipMaps = generateMipMaps;
  11038. texture.format = format;
  11039. texture.type = type;
  11040. if (!this._doNotHandleContextLost) {
  11041. texture._bufferViewArray = data;
  11042. }
  11043. var textureType = this._getWebGLTextureType(type);
  11044. var internalFormat = this._getInternalFormat(format);
  11045. var needConversion = false;
  11046. if (internalFormat === gl.RGB) {
  11047. internalFormat = gl.RGBA;
  11048. needConversion = true;
  11049. }
  11050. var width = size;
  11051. var height = width;
  11052. texture.width = width;
  11053. texture.height = height;
  11054. // Double check on POT to generate Mips.
  11055. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11056. if (!isPot) {
  11057. generateMipMaps = false;
  11058. }
  11059. // Upload data if needed. The texture won't be ready until then.
  11060. if (data) {
  11061. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11062. }
  11063. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11064. // Filters
  11065. if (data && generateMipMaps) {
  11066. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11067. }
  11068. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  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 if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11073. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11075. }
  11076. else {
  11077. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11078. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11080. }
  11081. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11082. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11083. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11084. return texture;
  11085. };
  11086. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11087. var _this = this;
  11088. if (onLoad === void 0) { onLoad = null; }
  11089. if (onError === void 0) { onError = null; }
  11090. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11091. if (invertY === void 0) { invertY = false; }
  11092. var gl = this._gl;
  11093. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11094. scene._addPendingData(texture);
  11095. texture.url = url;
  11096. this._internalTexturesCache.push(texture);
  11097. var onerror = function (request, exception) {
  11098. scene._removePendingData(texture);
  11099. if (onError) {
  11100. onError(request.status + " " + request.statusText, exception);
  11101. }
  11102. };
  11103. var internalCallback = function (data) {
  11104. var width = texture.width;
  11105. var faceDataArrays = callback(data);
  11106. if (!faceDataArrays) {
  11107. return;
  11108. }
  11109. if (mipmmapGenerator) {
  11110. var textureType = _this._getWebGLTextureType(type);
  11111. var internalFormat = _this._getInternalFormat(format);
  11112. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11113. var needConversion = false;
  11114. if (internalFormat === gl.RGB) {
  11115. internalFormat = gl.RGBA;
  11116. needConversion = true;
  11117. }
  11118. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11119. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11120. var mipData = mipmmapGenerator(faceDataArrays);
  11121. for (var level = 0; level < mipData.length; level++) {
  11122. var mipSize = width >> level;
  11123. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11124. var mipFaceData = mipData[level][faceIndex];
  11125. if (needConversion) {
  11126. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11127. }
  11128. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11129. }
  11130. }
  11131. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11132. }
  11133. else {
  11134. texture.generateMipMaps = !noMipmap;
  11135. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11136. }
  11137. texture.isReady = true;
  11138. _this.resetTextureCache();
  11139. scene._removePendingData(texture);
  11140. if (onLoad) {
  11141. onLoad();
  11142. }
  11143. };
  11144. BABYLON.Tools.LoadFile(url, function (data) {
  11145. internalCallback(data);
  11146. }, undefined, scene.database, true, onerror);
  11147. return texture;
  11148. };
  11149. ;
  11150. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11151. if (compression === void 0) { compression = null; }
  11152. var internalFormat = this._getInternalFormat(format);
  11153. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11154. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11155. if (!this._doNotHandleContextLost) {
  11156. texture._bufferView = data;
  11157. texture.format = format;
  11158. texture.invertY = invertY;
  11159. texture._compression = compression;
  11160. }
  11161. if (texture.width % 4 !== 0) {
  11162. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11163. }
  11164. if (compression && data) {
  11165. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11166. }
  11167. else {
  11168. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11169. }
  11170. if (texture.generateMipMaps) {
  11171. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11172. }
  11173. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11174. this.resetTextureCache();
  11175. texture.isReady = true;
  11176. };
  11177. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11178. if (compression === void 0) { compression = null; }
  11179. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11180. texture.baseWidth = width;
  11181. texture.baseHeight = height;
  11182. texture.baseDepth = depth;
  11183. texture.width = width;
  11184. texture.height = height;
  11185. texture.depth = depth;
  11186. texture.format = format;
  11187. texture.generateMipMaps = generateMipMaps;
  11188. texture.samplingMode = samplingMode;
  11189. texture.is3D = true;
  11190. if (!this._doNotHandleContextLost) {
  11191. texture._bufferView = data;
  11192. }
  11193. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11194. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11195. // Filters
  11196. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11197. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11198. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11199. if (generateMipMaps) {
  11200. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11201. }
  11202. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11203. this._internalTexturesCache.push(texture);
  11204. return texture;
  11205. };
  11206. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11207. var gl = this._gl;
  11208. if (!gl) {
  11209. return;
  11210. }
  11211. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11212. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11213. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11214. if (!noMipmap && !isCompressed) {
  11215. gl.generateMipmap(gl.TEXTURE_2D);
  11216. }
  11217. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11218. this.resetTextureCache();
  11219. if (scene) {
  11220. scene._removePendingData(texture);
  11221. }
  11222. texture.onLoadedObservable.notifyObservers(texture);
  11223. texture.onLoadedObservable.clear();
  11224. };
  11225. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11226. var _this = this;
  11227. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11228. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11229. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11230. var gl = this._gl;
  11231. if (!gl) {
  11232. return;
  11233. }
  11234. if (!texture._webGLTexture) {
  11235. this.resetTextureCache();
  11236. if (scene) {
  11237. scene._removePendingData(texture);
  11238. }
  11239. return;
  11240. }
  11241. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11242. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11243. texture.baseWidth = width;
  11244. texture.baseHeight = height;
  11245. texture.width = potWidth;
  11246. texture.height = potHeight;
  11247. texture.isReady = true;
  11248. if (processFunction(potWidth, potHeight, function () {
  11249. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11250. })) {
  11251. // Returning as texture needs extra async steps
  11252. return;
  11253. }
  11254. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11255. };
  11256. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11257. // Create new RGBA data container.
  11258. var rgbaData;
  11259. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11260. rgbaData = new Float32Array(width * height * 4);
  11261. }
  11262. else {
  11263. rgbaData = new Uint32Array(width * height * 4);
  11264. }
  11265. // Convert each pixel.
  11266. for (var x = 0; x < width; x++) {
  11267. for (var y = 0; y < height; y++) {
  11268. var index = (y * width + x) * 3;
  11269. var newIndex = (y * width + x) * 4;
  11270. // Map Old Value to new value.
  11271. rgbaData[newIndex + 0] = rgbData[index + 0];
  11272. rgbaData[newIndex + 1] = rgbData[index + 1];
  11273. rgbaData[newIndex + 2] = rgbData[index + 2];
  11274. // Add fully opaque alpha channel.
  11275. rgbaData[newIndex + 3] = 1;
  11276. }
  11277. }
  11278. return rgbaData;
  11279. };
  11280. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11281. var gl = this._gl;
  11282. if (texture._framebuffer) {
  11283. gl.deleteFramebuffer(texture._framebuffer);
  11284. texture._framebuffer = null;
  11285. }
  11286. if (texture._depthStencilBuffer) {
  11287. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11288. texture._depthStencilBuffer = null;
  11289. }
  11290. if (texture._MSAAFramebuffer) {
  11291. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11292. texture._MSAAFramebuffer = null;
  11293. }
  11294. if (texture._MSAARenderBuffer) {
  11295. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11296. texture._MSAARenderBuffer = null;
  11297. }
  11298. };
  11299. Engine.prototype._releaseTexture = function (texture) {
  11300. var gl = this._gl;
  11301. this._releaseFramebufferObjects(texture);
  11302. gl.deleteTexture(texture._webGLTexture);
  11303. // Unbind channels
  11304. this.unbindAllTextures();
  11305. var index = this._internalTexturesCache.indexOf(texture);
  11306. if (index !== -1) {
  11307. this._internalTexturesCache.splice(index, 1);
  11308. }
  11309. // Integrated fixed lod samplers.
  11310. if (texture._lodTextureHigh) {
  11311. texture._lodTextureHigh.dispose();
  11312. }
  11313. if (texture._lodTextureMid) {
  11314. texture._lodTextureMid.dispose();
  11315. }
  11316. if (texture._lodTextureLow) {
  11317. texture._lodTextureLow.dispose();
  11318. }
  11319. };
  11320. Engine.prototype.setProgram = function (program) {
  11321. if (this._currentProgram !== program) {
  11322. this._gl.useProgram(program);
  11323. this._currentProgram = program;
  11324. }
  11325. };
  11326. Engine.prototype.bindSamplers = function (effect) {
  11327. this.setProgram(effect.getProgram());
  11328. var samplers = effect.getSamplers();
  11329. for (var index = 0; index < samplers.length; index++) {
  11330. var uniform = effect.getUniform(samplers[index]);
  11331. this._gl.uniform1i(uniform, index);
  11332. }
  11333. this._currentEffect = null;
  11334. };
  11335. Engine.prototype.activateTexture = function (texture) {
  11336. if (this._activeTexture !== texture) {
  11337. this._gl.activeTexture(texture);
  11338. this._activeTexture = texture;
  11339. }
  11340. };
  11341. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11342. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  11343. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11344. this._activeTexturesCache[this._activeTexture] = texture;
  11345. }
  11346. };
  11347. Engine.prototype._bindTexture = function (channel, texture) {
  11348. if (channel < 0) {
  11349. return;
  11350. }
  11351. this.activateTexture(this._gl.TEXTURE0 + channel);
  11352. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11353. };
  11354. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11355. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11356. };
  11357. Engine.prototype.unbindAllTextures = function () {
  11358. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11359. this.activateTexture(this._gl["TEXTURE" + channel]);
  11360. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11361. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11362. if (this.webGLVersion > 1) {
  11363. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11364. }
  11365. }
  11366. };
  11367. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11368. if (channel < 0) {
  11369. return;
  11370. }
  11371. this._gl.uniform1i(uniform, channel);
  11372. this._setTexture(channel, texture);
  11373. };
  11374. Engine.prototype._setTexture = function (channel, texture) {
  11375. // Not ready?
  11376. if (!texture) {
  11377. if (this._activeTexturesCache[channel] != null) {
  11378. this.activateTexture(this._gl["TEXTURE" + channel]);
  11379. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11380. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11381. if (this.webGLVersion > 1) {
  11382. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11383. }
  11384. }
  11385. return;
  11386. }
  11387. // Video
  11388. var alreadyActivated = false;
  11389. if (texture.video) {
  11390. this.activateTexture(this._gl["TEXTURE" + channel]);
  11391. alreadyActivated = true;
  11392. texture.update();
  11393. }
  11394. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11395. texture.delayLoad();
  11396. return;
  11397. }
  11398. var internalTexture;
  11399. if (texture.isReady()) {
  11400. internalTexture = texture.getInternalTexture();
  11401. }
  11402. else if (texture.isCube) {
  11403. internalTexture = this.emptyCubeTexture;
  11404. }
  11405. else if (texture.is3D) {
  11406. internalTexture = this.emptyTexture3D;
  11407. }
  11408. else {
  11409. internalTexture = this.emptyTexture;
  11410. }
  11411. if (this._activeTexturesCache[channel] === internalTexture) {
  11412. return;
  11413. }
  11414. if (!alreadyActivated) {
  11415. this.activateTexture(this._gl["TEXTURE" + channel]);
  11416. }
  11417. if (internalTexture && internalTexture.is3D) {
  11418. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11419. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11420. internalTexture._cachedWrapU = texture.wrapU;
  11421. switch (texture.wrapU) {
  11422. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11423. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11424. break;
  11425. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11426. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11427. break;
  11428. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11429. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11430. break;
  11431. }
  11432. }
  11433. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11434. internalTexture._cachedWrapV = texture.wrapV;
  11435. switch (texture.wrapV) {
  11436. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11437. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11438. break;
  11439. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11440. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11441. break;
  11442. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11443. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11444. break;
  11445. }
  11446. }
  11447. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11448. internalTexture._cachedWrapR = texture.wrapR;
  11449. switch (texture.wrapV) {
  11450. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11451. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11452. break;
  11453. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11454. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11455. break;
  11456. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11457. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11458. break;
  11459. }
  11460. }
  11461. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11462. }
  11463. else if (internalTexture && internalTexture.isCube) {
  11464. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11465. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11466. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11467. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11468. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11469. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11470. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11471. }
  11472. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11473. }
  11474. else {
  11475. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11476. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11477. internalTexture._cachedWrapU = texture.wrapU;
  11478. switch (texture.wrapU) {
  11479. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11480. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11481. break;
  11482. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11483. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11484. break;
  11485. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11486. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11487. break;
  11488. }
  11489. }
  11490. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11491. internalTexture._cachedWrapV = texture.wrapV;
  11492. switch (texture.wrapV) {
  11493. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11494. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11495. break;
  11496. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11497. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11498. break;
  11499. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11500. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11501. break;
  11502. }
  11503. }
  11504. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11505. }
  11506. };
  11507. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11508. if (channel < 0 || !uniform) {
  11509. return;
  11510. }
  11511. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11512. this._textureUnits = new Int32Array(textures.length);
  11513. }
  11514. for (var i = 0; i < textures.length; i++) {
  11515. this._textureUnits[i] = channel + i;
  11516. }
  11517. this._gl.uniform1iv(uniform, this._textureUnits);
  11518. for (var index = 0; index < textures.length; index++) {
  11519. this._setTexture(channel + index, textures[index]);
  11520. }
  11521. };
  11522. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11523. var internalTexture = texture.getInternalTexture();
  11524. if (!internalTexture) {
  11525. return;
  11526. }
  11527. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11528. var value = texture.anisotropicFilteringLevel;
  11529. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11530. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11531. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11532. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11533. }
  11534. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11535. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11536. internalTexture._cachedAnisotropicFilteringLevel = value;
  11537. }
  11538. };
  11539. Engine.prototype.readPixels = function (x, y, width, height) {
  11540. var data = new Uint8Array(height * width * 4);
  11541. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11542. return data;
  11543. };
  11544. /**
  11545. * Add an externaly attached data from its key.
  11546. * This method call will fail and return false, if such key already exists.
  11547. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11548. * @param key the unique key that identifies the data
  11549. * @param data the data object to associate to the key for this Engine instance
  11550. * @return true if no such key were already present and the data was added successfully, false otherwise
  11551. */
  11552. Engine.prototype.addExternalData = function (key, data) {
  11553. if (!this._externalData) {
  11554. this._externalData = new BABYLON.StringDictionary();
  11555. }
  11556. return this._externalData.add(key, data);
  11557. };
  11558. /**
  11559. * Get an externaly attached data from its key
  11560. * @param key the unique key that identifies the data
  11561. * @return the associated data, if present (can be null), or undefined if not present
  11562. */
  11563. Engine.prototype.getExternalData = function (key) {
  11564. if (!this._externalData) {
  11565. this._externalData = new BABYLON.StringDictionary();
  11566. }
  11567. return this._externalData.get(key);
  11568. };
  11569. /**
  11570. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11571. * @param key the unique key that identifies the data
  11572. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11573. * @return the associated data, can be null if the factory returned null.
  11574. */
  11575. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11576. if (!this._externalData) {
  11577. this._externalData = new BABYLON.StringDictionary();
  11578. }
  11579. return this._externalData.getOrAddWithFactory(key, factory);
  11580. };
  11581. /**
  11582. * Remove an externaly attached data from the Engine instance
  11583. * @param key the unique key that identifies the data
  11584. * @return true if the data was successfully removed, false if it doesn't exist
  11585. */
  11586. Engine.prototype.removeExternalData = function (key) {
  11587. if (!this._externalData) {
  11588. this._externalData = new BABYLON.StringDictionary();
  11589. }
  11590. return this._externalData.remove(key);
  11591. };
  11592. Engine.prototype.unbindAllAttributes = function () {
  11593. if (this._mustWipeVertexAttributes) {
  11594. this._mustWipeVertexAttributes = false;
  11595. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11596. this._gl.disableVertexAttribArray(i);
  11597. this._vertexAttribArraysEnabled[i] = false;
  11598. this._currentBufferPointers[i].active = false;
  11599. }
  11600. return;
  11601. }
  11602. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11603. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11604. continue;
  11605. }
  11606. this._gl.disableVertexAttribArray(i);
  11607. this._vertexAttribArraysEnabled[i] = false;
  11608. this._currentBufferPointers[i].active = false;
  11609. }
  11610. };
  11611. Engine.prototype.releaseEffects = function () {
  11612. for (var name in this._compiledEffects) {
  11613. this._deleteProgram(this._compiledEffects[name]._program);
  11614. }
  11615. this._compiledEffects = {};
  11616. };
  11617. // Dispose
  11618. Engine.prototype.dispose = function () {
  11619. this.hideLoadingUI();
  11620. this.stopRenderLoop();
  11621. // Release postProcesses
  11622. while (this.postProcesses.length) {
  11623. this.postProcesses[0].dispose();
  11624. }
  11625. // Empty texture
  11626. if (this._emptyTexture) {
  11627. this._releaseTexture(this._emptyTexture);
  11628. this._emptyTexture = null;
  11629. }
  11630. if (this._emptyCubeTexture) {
  11631. this._releaseTexture(this._emptyCubeTexture);
  11632. this._emptyCubeTexture = null;
  11633. }
  11634. // Rescale PP
  11635. if (this._rescalePostProcess) {
  11636. this._rescalePostProcess.dispose();
  11637. }
  11638. // Release scenes
  11639. while (this.scenes.length) {
  11640. this.scenes[0].dispose();
  11641. }
  11642. // Release audio engine
  11643. if (Engine.audioEngine) {
  11644. Engine.audioEngine.dispose();
  11645. }
  11646. // Release effects
  11647. this.releaseEffects();
  11648. // Unbind
  11649. this.unbindAllAttributes();
  11650. if (this._dummyFramebuffer) {
  11651. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11652. }
  11653. //WebVR
  11654. this.disableVR();
  11655. // Events
  11656. window.removeEventListener("blur", this._onBlur);
  11657. window.removeEventListener("focus", this._onFocus);
  11658. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11659. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11660. if (this._renderingCanvas) {
  11661. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11662. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11663. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11664. if (!this._doNotHandleContextLost) {
  11665. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11666. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11667. }
  11668. }
  11669. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11670. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11671. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11672. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11673. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11674. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11675. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11676. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11677. if (this._onVrDisplayConnect) {
  11678. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11679. if (this._onVrDisplayDisconnect) {
  11680. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11681. }
  11682. if (this._onVrDisplayPresentChange) {
  11683. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11684. }
  11685. this._onVrDisplayConnect = null;
  11686. this._onVrDisplayDisconnect = null;
  11687. }
  11688. // Remove from Instances
  11689. var index = Engine.Instances.indexOf(this);
  11690. if (index >= 0) {
  11691. Engine.Instances.splice(index, 1);
  11692. }
  11693. this._workingCanvas = null;
  11694. this._workingContext = null;
  11695. this._currentBufferPointers = [];
  11696. this._renderingCanvas = null;
  11697. this._currentProgram = null;
  11698. this.onResizeObservable.clear();
  11699. this.onCanvasBlurObservable.clear();
  11700. this.onCanvasFocusObservable.clear();
  11701. this.onCanvasPointerOutObservable.clear();
  11702. this.onBeginFrameObservable.clear();
  11703. this.onEndFrameObservable.clear();
  11704. BABYLON.Effect.ResetCache();
  11705. };
  11706. // Loading screen
  11707. Engine.prototype.displayLoadingUI = function () {
  11708. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11709. return;
  11710. }
  11711. var loadingScreen = this.loadingScreen;
  11712. if (loadingScreen) {
  11713. loadingScreen.displayLoadingUI();
  11714. }
  11715. };
  11716. Engine.prototype.hideLoadingUI = function () {
  11717. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11718. return;
  11719. }
  11720. var loadingScreen = this.loadingScreen;
  11721. if (loadingScreen) {
  11722. loadingScreen.hideLoadingUI();
  11723. }
  11724. };
  11725. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11726. get: function () {
  11727. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11728. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11729. return this._loadingScreen;
  11730. },
  11731. set: function (loadingScreen) {
  11732. this._loadingScreen = loadingScreen;
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11738. set: function (text) {
  11739. this.loadingScreen.loadingUIText = text;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11745. set: function (color) {
  11746. this.loadingScreen.loadingUIBackgroundColor = color;
  11747. },
  11748. enumerable: true,
  11749. configurable: true
  11750. });
  11751. Engine.prototype.attachContextLostEvent = function (callback) {
  11752. if (this._renderingCanvas) {
  11753. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11754. }
  11755. };
  11756. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11757. if (this._renderingCanvas) {
  11758. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11759. }
  11760. };
  11761. Engine.prototype.getVertexShaderSource = function (program) {
  11762. var shaders = this._gl.getAttachedShaders(program);
  11763. if (!shaders) {
  11764. return null;
  11765. }
  11766. return this._gl.getShaderSource(shaders[0]);
  11767. };
  11768. Engine.prototype.getFragmentShaderSource = function (program) {
  11769. var shaders = this._gl.getAttachedShaders(program);
  11770. if (!shaders) {
  11771. return null;
  11772. }
  11773. return this._gl.getShaderSource(shaders[1]);
  11774. };
  11775. Engine.prototype.getError = function () {
  11776. return this._gl.getError();
  11777. };
  11778. // FPS
  11779. Engine.prototype.getFps = function () {
  11780. return this._fps;
  11781. };
  11782. Engine.prototype.getDeltaTime = function () {
  11783. return this._deltaTime;
  11784. };
  11785. Engine.prototype._measureFps = function () {
  11786. this._performanceMonitor.sampleFrame();
  11787. this._fps = this._performanceMonitor.averageFPS;
  11788. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11789. };
  11790. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11791. if (faceIndex === void 0) { faceIndex = -1; }
  11792. var gl = this._gl;
  11793. if (!this._dummyFramebuffer) {
  11794. var dummy = gl.createFramebuffer();
  11795. if (!dummy) {
  11796. throw new Error("Unable to create dummy framebuffer");
  11797. }
  11798. this._dummyFramebuffer = dummy;
  11799. }
  11800. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11801. if (faceIndex > -1) {
  11802. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11803. }
  11804. else {
  11805. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11806. }
  11807. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11808. var buffer;
  11809. switch (readType) {
  11810. case gl.UNSIGNED_BYTE:
  11811. buffer = new Uint8Array(4 * width * height);
  11812. readType = gl.UNSIGNED_BYTE;
  11813. break;
  11814. default:
  11815. buffer = new Float32Array(4 * width * height);
  11816. readType = gl.FLOAT;
  11817. break;
  11818. }
  11819. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11820. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11821. return buffer;
  11822. };
  11823. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11824. if (this._webGLVersion > 1) {
  11825. return this._caps.colorBufferFloat;
  11826. }
  11827. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11828. };
  11829. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11830. if (this._webGLVersion > 1) {
  11831. return this._caps.colorBufferFloat;
  11832. }
  11833. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11834. };
  11835. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11836. Engine.prototype._canRenderToFramebuffer = function (type) {
  11837. var gl = this._gl;
  11838. //clear existing errors
  11839. while (gl.getError() !== gl.NO_ERROR) { }
  11840. var successful = true;
  11841. var texture = gl.createTexture();
  11842. gl.bindTexture(gl.TEXTURE_2D, texture);
  11843. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11844. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11845. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11846. var fb = gl.createFramebuffer();
  11847. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11848. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11849. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11850. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11851. successful = successful && (gl.getError() === gl.NO_ERROR);
  11852. //try render by clearing frame buffer's color buffer
  11853. if (successful) {
  11854. gl.clear(gl.COLOR_BUFFER_BIT);
  11855. successful = successful && (gl.getError() === gl.NO_ERROR);
  11856. }
  11857. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11858. if (successful) {
  11859. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11860. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11861. var readFormat = gl.RGBA;
  11862. var readType = gl.UNSIGNED_BYTE;
  11863. var buffer = new Uint8Array(4);
  11864. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11865. successful = successful && (gl.getError() === gl.NO_ERROR);
  11866. }
  11867. //clean up
  11868. gl.deleteTexture(texture);
  11869. gl.deleteFramebuffer(fb);
  11870. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11871. //clear accumulated errors
  11872. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11873. return successful;
  11874. };
  11875. Engine.prototype._getWebGLTextureType = function (type) {
  11876. if (type === Engine.TEXTURETYPE_FLOAT) {
  11877. return this._gl.FLOAT;
  11878. }
  11879. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11880. // Add Half Float Constant.
  11881. return this._gl.HALF_FLOAT_OES;
  11882. }
  11883. return this._gl.UNSIGNED_BYTE;
  11884. };
  11885. ;
  11886. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11887. if (this._webGLVersion === 1) {
  11888. return this._gl.RGBA;
  11889. }
  11890. if (type === Engine.TEXTURETYPE_FLOAT) {
  11891. return this._gl.RGBA32F;
  11892. }
  11893. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11894. return this._gl.RGBA16F;
  11895. }
  11896. return this._gl.RGBA;
  11897. };
  11898. ;
  11899. Engine.prototype.createQuery = function () {
  11900. return this._gl.createQuery();
  11901. };
  11902. Engine.prototype.deleteQuery = function (query) {
  11903. this._gl.deleteQuery(query);
  11904. return this;
  11905. };
  11906. Engine.prototype.isQueryResultAvailable = function (query) {
  11907. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11908. };
  11909. Engine.prototype.getQueryResult = function (query) {
  11910. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11911. };
  11912. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  11913. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11914. this._gl.beginQuery(glAlgorithm, query);
  11915. return this;
  11916. };
  11917. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  11918. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11919. this._gl.endQuery(glAlgorithm);
  11920. return this;
  11921. };
  11922. /* Time queries */
  11923. Engine.prototype._createTimeQuery = function () {
  11924. var timerQuery = this._caps.timerQuery;
  11925. if (timerQuery.createQueryEXT) {
  11926. return timerQuery.createQueryEXT();
  11927. }
  11928. return this.createQuery();
  11929. };
  11930. Engine.prototype._deleteTimeQuery = function (query) {
  11931. var timerQuery = this._caps.timerQuery;
  11932. if (timerQuery.deleteQueryEXT) {
  11933. timerQuery.deleteQueryEXT(query);
  11934. return;
  11935. }
  11936. this.deleteQuery(query);
  11937. };
  11938. Engine.prototype._getTimeQueryResult = function (query) {
  11939. var timerQuery = this._caps.timerQuery;
  11940. if (timerQuery.getQueryObjectEXT) {
  11941. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  11942. }
  11943. return this.getQueryResult(query);
  11944. };
  11945. Engine.prototype._getTimeQueryAvailability = function (query) {
  11946. var timerQuery = this._caps.timerQuery;
  11947. if (timerQuery.getQueryObjectEXT) {
  11948. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  11949. }
  11950. return this.isQueryResultAvailable(query);
  11951. };
  11952. Engine.prototype.startTimeQuery = function () {
  11953. var timerQuery = this._caps.timerQuery;
  11954. if (!timerQuery) {
  11955. return null;
  11956. }
  11957. var token = new BABYLON._TimeToken();
  11958. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  11959. if (this._caps.canUseTimestampForTimerQuery) {
  11960. token._startTimeQuery = this._createTimeQuery();
  11961. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  11962. }
  11963. else {
  11964. token._timeElapsedQuery = this._createTimeQuery();
  11965. if (timerQuery.beginQueryEXT) {
  11966. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  11967. }
  11968. else {
  11969. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  11970. }
  11971. }
  11972. return token;
  11973. };
  11974. Engine.prototype.endTimeQuery = function (token) {
  11975. var timerQuery = this._caps.timerQuery;
  11976. if (!timerQuery || !token) {
  11977. return -1;
  11978. }
  11979. if (this._caps.canUseTimestampForTimerQuery) {
  11980. if (!token._startTimeQuery) {
  11981. return -1;
  11982. }
  11983. if (!token._endTimeQuery) {
  11984. token._endTimeQuery = this._createTimeQuery();
  11985. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  11986. }
  11987. }
  11988. else if (!token._timeElapsedQueryEnded) {
  11989. if (!token._timeElapsedQuery) {
  11990. return -1;
  11991. }
  11992. if (timerQuery.endQueryEXT) {
  11993. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  11994. }
  11995. else {
  11996. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  11997. }
  11998. token._timeElapsedQueryEnded = true;
  11999. }
  12000. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12001. var available = false;
  12002. if (token._endTimeQuery) {
  12003. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12004. }
  12005. else if (token._timeElapsedQuery) {
  12006. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12007. }
  12008. if (available && !disjoint) {
  12009. var result = 0;
  12010. if (this._caps.canUseTimestampForTimerQuery) {
  12011. if (!token._startTimeQuery || !token._endTimeQuery) {
  12012. return -1;
  12013. }
  12014. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12015. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12016. result = timeEnd - timeStart;
  12017. this._deleteTimeQuery(token._startTimeQuery);
  12018. this._deleteTimeQuery(token._endTimeQuery);
  12019. token._startTimeQuery = null;
  12020. token._endTimeQuery = null;
  12021. }
  12022. else {
  12023. if (!token._timeElapsedQuery) {
  12024. return -1;
  12025. }
  12026. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12027. this._deleteTimeQuery(token._timeElapsedQuery);
  12028. token._timeElapsedQuery = null;
  12029. token._timeElapsedQueryEnded = false;
  12030. }
  12031. return result;
  12032. }
  12033. return -1;
  12034. };
  12035. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12036. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12037. };
  12038. // Statics
  12039. Engine.isSupported = function () {
  12040. try {
  12041. var tempcanvas = document.createElement("canvas");
  12042. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12043. return gl != null && !!window.WebGLRenderingContext;
  12044. }
  12045. catch (e) {
  12046. return false;
  12047. }
  12048. };
  12049. Engine.Instances = new Array();
  12050. // Const statics
  12051. Engine._ALPHA_DISABLE = 0;
  12052. Engine._ALPHA_ADD = 1;
  12053. Engine._ALPHA_COMBINE = 2;
  12054. Engine._ALPHA_SUBTRACT = 3;
  12055. Engine._ALPHA_MULTIPLY = 4;
  12056. Engine._ALPHA_MAXIMIZED = 5;
  12057. Engine._ALPHA_ONEONE = 6;
  12058. Engine._ALPHA_PREMULTIPLIED = 7;
  12059. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12060. Engine._ALPHA_INTERPOLATE = 9;
  12061. Engine._ALPHA_SCREENMODE = 10;
  12062. Engine._DELAYLOADSTATE_NONE = 0;
  12063. Engine._DELAYLOADSTATE_LOADED = 1;
  12064. Engine._DELAYLOADSTATE_LOADING = 2;
  12065. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12066. Engine._TEXTUREFORMAT_ALPHA = 0;
  12067. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12068. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12069. Engine._TEXTUREFORMAT_RGB = 4;
  12070. Engine._TEXTUREFORMAT_RGBA = 5;
  12071. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12072. Engine._TEXTURETYPE_FLOAT = 1;
  12073. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12074. // Depht or Stencil test Constants.
  12075. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12076. 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.
  12077. 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.
  12078. 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.
  12079. 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.
  12080. 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.
  12081. 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.
  12082. 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.
  12083. // Stencil Actions Constants.
  12084. Engine._KEEP = 0x1E00;
  12085. Engine._REPLACE = 0x1E01;
  12086. Engine._INCR = 0x1E02;
  12087. Engine._DECR = 0x1E03;
  12088. Engine._INVERT = 0x150A;
  12089. Engine._INCR_WRAP = 0x8507;
  12090. Engine._DECR_WRAP = 0x8508;
  12091. // Texture rescaling mode
  12092. Engine._SCALEMODE_FLOOR = 1;
  12093. Engine._SCALEMODE_NEAREST = 2;
  12094. Engine._SCALEMODE_CEILING = 3;
  12095. // Updatable statics so stick with vars here
  12096. Engine.CollisionsEpsilon = 0.001;
  12097. Engine.CodeRepository = "src/";
  12098. Engine.ShadersRepository = "src/Shaders/";
  12099. return Engine;
  12100. }());
  12101. BABYLON.Engine = Engine;
  12102. })(BABYLON || (BABYLON = {}));
  12103. //# sourceMappingURL=babylon.engine.js.map
  12104. var BABYLON;
  12105. (function (BABYLON) {
  12106. /**
  12107. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12108. */
  12109. var Node = /** @class */ (function () {
  12110. /**
  12111. * @constructor
  12112. * @param {string} name - the name and id to be given to this node
  12113. * @param {BABYLON.Scene} the scene this node will be added to
  12114. */
  12115. function Node(name, scene) {
  12116. if (scene === void 0) { scene = null; }
  12117. this.state = "";
  12118. this.metadata = null;
  12119. this.doNotSerialize = false;
  12120. this.animations = new Array();
  12121. this._ranges = {};
  12122. this._isEnabled = true;
  12123. this._isReady = true;
  12124. this._currentRenderId = -1;
  12125. this._parentRenderId = -1;
  12126. /**
  12127. * An event triggered when the mesh is disposed.
  12128. * @type {BABYLON.Observable}
  12129. */
  12130. this.onDisposeObservable = new BABYLON.Observable();
  12131. // Behaviors
  12132. this._behaviors = new Array();
  12133. this.name = name;
  12134. this.id = name;
  12135. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12136. this.uniqueId = this._scene.getUniqueId();
  12137. this._initCache();
  12138. }
  12139. Object.defineProperty(Node.prototype, "parent", {
  12140. get: function () {
  12141. return this._parentNode;
  12142. },
  12143. set: function (parent) {
  12144. if (this._parentNode === parent) {
  12145. return;
  12146. }
  12147. if (this._parentNode) {
  12148. var index = this._parentNode._children.indexOf(this);
  12149. if (index !== -1) {
  12150. this._parentNode._children.splice(index, 1);
  12151. }
  12152. }
  12153. this._parentNode = parent;
  12154. if (this._parentNode) {
  12155. if (!this._parentNode._children) {
  12156. this._parentNode._children = new Array();
  12157. }
  12158. this._parentNode._children.push(this);
  12159. }
  12160. },
  12161. enumerable: true,
  12162. configurable: true
  12163. });
  12164. Node.prototype.getClassName = function () {
  12165. return "Node";
  12166. };
  12167. Object.defineProperty(Node.prototype, "onDispose", {
  12168. set: function (callback) {
  12169. if (this._onDisposeObserver) {
  12170. this.onDisposeObservable.remove(this._onDisposeObserver);
  12171. }
  12172. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12173. },
  12174. enumerable: true,
  12175. configurable: true
  12176. });
  12177. Node.prototype.getScene = function () {
  12178. return this._scene;
  12179. };
  12180. Node.prototype.getEngine = function () {
  12181. return this._scene.getEngine();
  12182. };
  12183. Node.prototype.addBehavior = function (behavior) {
  12184. var index = this._behaviors.indexOf(behavior);
  12185. if (index !== -1) {
  12186. return this;
  12187. }
  12188. behavior.attach(this);
  12189. this._behaviors.push(behavior);
  12190. return this;
  12191. };
  12192. Node.prototype.removeBehavior = function (behavior) {
  12193. var index = this._behaviors.indexOf(behavior);
  12194. if (index === -1) {
  12195. return this;
  12196. }
  12197. this._behaviors[index].detach();
  12198. this._behaviors.splice(index, 1);
  12199. return this;
  12200. };
  12201. Object.defineProperty(Node.prototype, "behaviors", {
  12202. get: function () {
  12203. return this._behaviors;
  12204. },
  12205. enumerable: true,
  12206. configurable: true
  12207. });
  12208. Node.prototype.getBehaviorByName = function (name) {
  12209. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12210. var behavior = _a[_i];
  12211. if (behavior.name === name) {
  12212. return behavior;
  12213. }
  12214. }
  12215. return null;
  12216. };
  12217. // override it in derived class
  12218. Node.prototype.getWorldMatrix = function () {
  12219. return BABYLON.Matrix.Identity();
  12220. };
  12221. // override it in derived class if you add new variables to the cache
  12222. // and call the parent class method
  12223. Node.prototype._initCache = function () {
  12224. this._cache = {};
  12225. this._cache.parent = undefined;
  12226. };
  12227. Node.prototype.updateCache = function (force) {
  12228. if (!force && this.isSynchronized())
  12229. return;
  12230. this._cache.parent = this.parent;
  12231. this._updateCache();
  12232. };
  12233. // override it in derived class if you add new variables to the cache
  12234. // and call the parent class method if !ignoreParentClass
  12235. Node.prototype._updateCache = function (ignoreParentClass) {
  12236. };
  12237. // override it in derived class if you add new variables to the cache
  12238. Node.prototype._isSynchronized = function () {
  12239. return true;
  12240. };
  12241. Node.prototype._markSyncedWithParent = function () {
  12242. if (this.parent) {
  12243. this._parentRenderId = this.parent._currentRenderId;
  12244. }
  12245. };
  12246. Node.prototype.isSynchronizedWithParent = function () {
  12247. if (!this.parent) {
  12248. return true;
  12249. }
  12250. if (this._parentRenderId !== this.parent._currentRenderId) {
  12251. return false;
  12252. }
  12253. return this.parent.isSynchronized();
  12254. };
  12255. Node.prototype.isSynchronized = function (updateCache) {
  12256. var check = this.hasNewParent();
  12257. check = check || !this.isSynchronizedWithParent();
  12258. check = check || !this._isSynchronized();
  12259. if (updateCache)
  12260. this.updateCache(true);
  12261. return !check;
  12262. };
  12263. Node.prototype.hasNewParent = function (update) {
  12264. if (this._cache.parent === this.parent)
  12265. return false;
  12266. if (update)
  12267. this._cache.parent = this.parent;
  12268. return true;
  12269. };
  12270. /**
  12271. * Is this node ready to be used/rendered
  12272. * @return {boolean} is it ready
  12273. */
  12274. Node.prototype.isReady = function () {
  12275. return this._isReady;
  12276. };
  12277. /**
  12278. * Is this node enabled.
  12279. * If the node has a parent and is enabled, the parent will be inspected as well.
  12280. * @return {boolean} whether this node (and its parent) is enabled.
  12281. * @see setEnabled
  12282. */
  12283. Node.prototype.isEnabled = function () {
  12284. if (!this._isEnabled) {
  12285. return false;
  12286. }
  12287. if (this.parent) {
  12288. return this.parent.isEnabled();
  12289. }
  12290. return true;
  12291. };
  12292. /**
  12293. * Set the enabled state of this node.
  12294. * @param {boolean} value - the new enabled state
  12295. * @see isEnabled
  12296. */
  12297. Node.prototype.setEnabled = function (value) {
  12298. this._isEnabled = value;
  12299. };
  12300. /**
  12301. * Is this node a descendant of the given node.
  12302. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12303. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12304. * @see parent
  12305. */
  12306. Node.prototype.isDescendantOf = function (ancestor) {
  12307. if (this.parent) {
  12308. if (this.parent === ancestor) {
  12309. return true;
  12310. }
  12311. return this.parent.isDescendantOf(ancestor);
  12312. }
  12313. return false;
  12314. };
  12315. /**
  12316. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12317. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12318. * @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.
  12319. * @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.
  12320. */
  12321. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12322. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12323. if (!this._children) {
  12324. return;
  12325. }
  12326. for (var index = 0; index < this._children.length; index++) {
  12327. var item = this._children[index];
  12328. if (!predicate || predicate(item)) {
  12329. results.push(item);
  12330. }
  12331. if (!directDescendantsOnly) {
  12332. item._getDescendants(results, false, predicate);
  12333. }
  12334. }
  12335. };
  12336. /**
  12337. * Will return all nodes that have this node as ascendant.
  12338. * @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.
  12339. * @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.
  12340. * @return {BABYLON.Node[]} all children nodes of all types.
  12341. */
  12342. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12343. var results = new Array();
  12344. this._getDescendants(results, directDescendantsOnly, predicate);
  12345. return results;
  12346. };
  12347. /**
  12348. * Get all child-meshes of this node.
  12349. */
  12350. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12351. var results = [];
  12352. this._getDescendants(results, directDecendantsOnly, function (node) {
  12353. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12354. });
  12355. return results;
  12356. };
  12357. /**
  12358. * Get all direct children of this node.
  12359. */
  12360. Node.prototype.getChildren = function (predicate) {
  12361. return this.getDescendants(true, predicate);
  12362. };
  12363. Node.prototype._setReady = function (state) {
  12364. if (state === this._isReady) {
  12365. return;
  12366. }
  12367. if (!state) {
  12368. this._isReady = false;
  12369. return;
  12370. }
  12371. this._isReady = true;
  12372. if (this.onReady) {
  12373. this.onReady(this);
  12374. }
  12375. };
  12376. Node.prototype.getAnimationByName = function (name) {
  12377. for (var i = 0; i < this.animations.length; i++) {
  12378. var animation = this.animations[i];
  12379. if (animation.name === name) {
  12380. return animation;
  12381. }
  12382. }
  12383. return null;
  12384. };
  12385. Node.prototype.createAnimationRange = function (name, from, to) {
  12386. // check name not already in use
  12387. if (!this._ranges[name]) {
  12388. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12389. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12390. if (this.animations[i]) {
  12391. this.animations[i].createRange(name, from, to);
  12392. }
  12393. }
  12394. }
  12395. };
  12396. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12397. if (deleteFrames === void 0) { deleteFrames = true; }
  12398. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12399. if (this.animations[i]) {
  12400. this.animations[i].deleteRange(name, deleteFrames);
  12401. }
  12402. }
  12403. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12404. };
  12405. Node.prototype.getAnimationRange = function (name) {
  12406. return this._ranges[name];
  12407. };
  12408. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12409. var range = this.getAnimationRange(name);
  12410. if (!range) {
  12411. return;
  12412. }
  12413. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12414. };
  12415. Node.prototype.serializeAnimationRanges = function () {
  12416. var serializationRanges = [];
  12417. for (var name in this._ranges) {
  12418. var localRange = this._ranges[name];
  12419. if (!localRange) {
  12420. continue;
  12421. }
  12422. var range = {};
  12423. range.name = name;
  12424. range.from = localRange.from;
  12425. range.to = localRange.to;
  12426. serializationRanges.push(range);
  12427. }
  12428. return serializationRanges;
  12429. };
  12430. Node.prototype.dispose = function () {
  12431. this.parent = null;
  12432. // Callback
  12433. this.onDisposeObservable.notifyObservers(this);
  12434. this.onDisposeObservable.clear();
  12435. // Behaviors
  12436. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12437. var behavior = _a[_i];
  12438. behavior.detach();
  12439. }
  12440. this._behaviors = [];
  12441. };
  12442. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12443. if (parsedNode.ranges) {
  12444. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12445. var data = parsedNode.ranges[index];
  12446. node.createAnimationRange(data.name, data.from, data.to);
  12447. }
  12448. }
  12449. };
  12450. __decorate([
  12451. BABYLON.serialize()
  12452. ], Node.prototype, "name", void 0);
  12453. __decorate([
  12454. BABYLON.serialize()
  12455. ], Node.prototype, "id", void 0);
  12456. __decorate([
  12457. BABYLON.serialize()
  12458. ], Node.prototype, "uniqueId", void 0);
  12459. __decorate([
  12460. BABYLON.serialize()
  12461. ], Node.prototype, "state", void 0);
  12462. __decorate([
  12463. BABYLON.serialize()
  12464. ], Node.prototype, "metadata", void 0);
  12465. return Node;
  12466. }());
  12467. BABYLON.Node = Node;
  12468. })(BABYLON || (BABYLON = {}));
  12469. //# sourceMappingURL=babylon.node.js.map
  12470. var BABYLON;
  12471. (function (BABYLON) {
  12472. var BoundingSphere = /** @class */ (function () {
  12473. function BoundingSphere(minimum, maximum) {
  12474. this.minimum = minimum;
  12475. this.maximum = maximum;
  12476. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12477. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12478. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12479. this.radius = distance * 0.5;
  12480. this.centerWorld = BABYLON.Vector3.Zero();
  12481. this._update(BABYLON.Matrix.Identity());
  12482. }
  12483. // Methods
  12484. BoundingSphere.prototype._update = function (world) {
  12485. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12486. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12487. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12488. };
  12489. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12490. for (var i = 0; i < 6; i++) {
  12491. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12492. return false;
  12493. }
  12494. return true;
  12495. };
  12496. BoundingSphere.prototype.intersectsPoint = function (point) {
  12497. var x = this.centerWorld.x - point.x;
  12498. var y = this.centerWorld.y - point.y;
  12499. var z = this.centerWorld.z - point.z;
  12500. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12501. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12502. return false;
  12503. return true;
  12504. };
  12505. // Statics
  12506. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12507. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12508. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12509. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12510. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12511. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12512. return false;
  12513. return true;
  12514. };
  12515. return BoundingSphere;
  12516. }());
  12517. BABYLON.BoundingSphere = BoundingSphere;
  12518. })(BABYLON || (BABYLON = {}));
  12519. //# sourceMappingURL=babylon.boundingSphere.js.map
  12520. var BABYLON;
  12521. (function (BABYLON) {
  12522. var BoundingBox = /** @class */ (function () {
  12523. function BoundingBox(minimum, maximum) {
  12524. this.minimum = minimum;
  12525. this.maximum = maximum;
  12526. this.vectors = new Array();
  12527. this.vectorsWorld = new Array();
  12528. // Bounding vectors
  12529. this.vectors.push(this.minimum.clone());
  12530. this.vectors.push(this.maximum.clone());
  12531. this.vectors.push(this.minimum.clone());
  12532. this.vectors[2].x = this.maximum.x;
  12533. this.vectors.push(this.minimum.clone());
  12534. this.vectors[3].y = this.maximum.y;
  12535. this.vectors.push(this.minimum.clone());
  12536. this.vectors[4].z = this.maximum.z;
  12537. this.vectors.push(this.maximum.clone());
  12538. this.vectors[5].z = this.minimum.z;
  12539. this.vectors.push(this.maximum.clone());
  12540. this.vectors[6].x = this.minimum.x;
  12541. this.vectors.push(this.maximum.clone());
  12542. this.vectors[7].y = this.minimum.y;
  12543. // OBB
  12544. this.center = this.maximum.add(this.minimum).scale(0.5);
  12545. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12546. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12547. // World
  12548. for (var index = 0; index < this.vectors.length; index++) {
  12549. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12550. }
  12551. this.minimumWorld = BABYLON.Vector3.Zero();
  12552. this.maximumWorld = BABYLON.Vector3.Zero();
  12553. this.centerWorld = BABYLON.Vector3.Zero();
  12554. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12555. this._update(BABYLON.Matrix.Identity());
  12556. }
  12557. // Methods
  12558. BoundingBox.prototype.getWorldMatrix = function () {
  12559. return this._worldMatrix;
  12560. };
  12561. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12562. this._worldMatrix.copyFrom(matrix);
  12563. return this;
  12564. };
  12565. BoundingBox.prototype._update = function (world) {
  12566. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12567. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12568. for (var index = 0; index < this.vectors.length; index++) {
  12569. var v = this.vectorsWorld[index];
  12570. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12571. if (v.x < this.minimumWorld.x)
  12572. this.minimumWorld.x = v.x;
  12573. if (v.y < this.minimumWorld.y)
  12574. this.minimumWorld.y = v.y;
  12575. if (v.z < this.minimumWorld.z)
  12576. this.minimumWorld.z = v.z;
  12577. if (v.x > this.maximumWorld.x)
  12578. this.maximumWorld.x = v.x;
  12579. if (v.y > this.maximumWorld.y)
  12580. this.maximumWorld.y = v.y;
  12581. if (v.z > this.maximumWorld.z)
  12582. this.maximumWorld.z = v.z;
  12583. }
  12584. // Extend
  12585. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12586. this.extendSizeWorld.scaleInPlace(0.5);
  12587. // OBB
  12588. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12589. this.centerWorld.scaleInPlace(0.5);
  12590. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12591. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12592. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12593. this._worldMatrix = world;
  12594. };
  12595. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12596. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12597. };
  12598. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12599. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12600. };
  12601. BoundingBox.prototype.intersectsPoint = function (point) {
  12602. var delta = -BABYLON.Epsilon;
  12603. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12604. return false;
  12605. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12606. return false;
  12607. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12608. return false;
  12609. return true;
  12610. };
  12611. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12612. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12613. };
  12614. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12615. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12616. return false;
  12617. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12618. return false;
  12619. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12620. return false;
  12621. return true;
  12622. };
  12623. // Statics
  12624. BoundingBox.Intersects = function (box0, box1) {
  12625. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12626. return false;
  12627. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12628. return false;
  12629. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12630. return false;
  12631. return true;
  12632. };
  12633. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12634. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12635. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12636. return (num <= (sphereRadius * sphereRadius));
  12637. };
  12638. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12639. for (var p = 0; p < 6; p++) {
  12640. for (var i = 0; i < 8; i++) {
  12641. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12642. return false;
  12643. }
  12644. }
  12645. }
  12646. return true;
  12647. };
  12648. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12649. for (var p = 0; p < 6; p++) {
  12650. var inCount = 8;
  12651. for (var i = 0; i < 8; i++) {
  12652. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12653. --inCount;
  12654. }
  12655. else {
  12656. break;
  12657. }
  12658. }
  12659. if (inCount === 0)
  12660. return false;
  12661. }
  12662. return true;
  12663. };
  12664. return BoundingBox;
  12665. }());
  12666. BABYLON.BoundingBox = BoundingBox;
  12667. })(BABYLON || (BABYLON = {}));
  12668. //# sourceMappingURL=babylon.boundingBox.js.map
  12669. var BABYLON;
  12670. (function (BABYLON) {
  12671. var computeBoxExtents = function (axis, box) {
  12672. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12673. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12674. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12675. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12676. var r = r0 + r1 + r2;
  12677. return {
  12678. min: p - r,
  12679. max: p + r
  12680. };
  12681. };
  12682. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12683. var axisOverlap = function (axis, box0, box1) {
  12684. var result0 = computeBoxExtents(axis, box0);
  12685. var result1 = computeBoxExtents(axis, box1);
  12686. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12687. };
  12688. var BoundingInfo = /** @class */ (function () {
  12689. function BoundingInfo(minimum, maximum) {
  12690. this.minimum = minimum;
  12691. this.maximum = maximum;
  12692. this._isLocked = false;
  12693. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12694. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12695. }
  12696. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12697. get: function () {
  12698. return this._isLocked;
  12699. },
  12700. set: function (value) {
  12701. this._isLocked = value;
  12702. },
  12703. enumerable: true,
  12704. configurable: true
  12705. });
  12706. // Methods
  12707. BoundingInfo.prototype.update = function (world) {
  12708. if (this._isLocked) {
  12709. return;
  12710. }
  12711. this.boundingBox._update(world);
  12712. this.boundingSphere._update(world);
  12713. };
  12714. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12715. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12716. return false;
  12717. return this.boundingBox.isInFrustum(frustumPlanes);
  12718. };
  12719. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12720. /**
  12721. * Gets the world distance between the min and max points of the bounding box
  12722. */
  12723. get: function () {
  12724. var boundingBox = this.boundingBox;
  12725. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12726. return size.length();
  12727. },
  12728. enumerable: true,
  12729. configurable: true
  12730. });
  12731. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12732. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12733. };
  12734. BoundingInfo.prototype._checkCollision = function (collider) {
  12735. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12736. };
  12737. BoundingInfo.prototype.intersectsPoint = function (point) {
  12738. if (!this.boundingSphere.centerWorld) {
  12739. return false;
  12740. }
  12741. if (!this.boundingSphere.intersectsPoint(point)) {
  12742. return false;
  12743. }
  12744. if (!this.boundingBox.intersectsPoint(point)) {
  12745. return false;
  12746. }
  12747. return true;
  12748. };
  12749. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12750. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12751. return false;
  12752. }
  12753. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12754. return false;
  12755. }
  12756. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12757. return false;
  12758. }
  12759. if (!precise) {
  12760. return true;
  12761. }
  12762. var box0 = this.boundingBox;
  12763. var box1 = boundingInfo.boundingBox;
  12764. if (!axisOverlap(box0.directions[0], box0, box1))
  12765. return false;
  12766. if (!axisOverlap(box0.directions[1], box0, box1))
  12767. return false;
  12768. if (!axisOverlap(box0.directions[2], box0, box1))
  12769. return false;
  12770. if (!axisOverlap(box1.directions[0], box0, box1))
  12771. return false;
  12772. if (!axisOverlap(box1.directions[1], box0, box1))
  12773. return false;
  12774. if (!axisOverlap(box1.directions[2], box0, box1))
  12775. return false;
  12776. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12777. return false;
  12778. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12779. return false;
  12780. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12781. return false;
  12782. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12783. return false;
  12784. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12785. return false;
  12786. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12787. return false;
  12788. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12789. return false;
  12790. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12791. return false;
  12792. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12793. return false;
  12794. return true;
  12795. };
  12796. return BoundingInfo;
  12797. }());
  12798. BABYLON.BoundingInfo = BoundingInfo;
  12799. })(BABYLON || (BABYLON = {}));
  12800. //# sourceMappingURL=babylon.boundingInfo.js.map
  12801. var BABYLON;
  12802. (function (BABYLON) {
  12803. var AbstractMesh = /** @class */ (function (_super) {
  12804. __extends(AbstractMesh, _super);
  12805. // Constructor
  12806. function AbstractMesh(name, scene) {
  12807. if (scene === void 0) { scene = null; }
  12808. var _this = _super.call(this, name, scene) || this;
  12809. _this._facetNb = 0; // facet number
  12810. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12811. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12812. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12813. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12814. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12815. _this._subDiv = {
  12816. max: 1,
  12817. X: 1,
  12818. Y: 1,
  12819. Z: 1
  12820. };
  12821. // Normal matrix
  12822. _this._nonUniformScaling = false;
  12823. // Events
  12824. /**
  12825. * An event triggered when this mesh collides with another one
  12826. * @type {BABYLON.Observable}
  12827. */
  12828. _this.onCollideObservable = new BABYLON.Observable();
  12829. /**
  12830. * An event triggered when the collision's position changes
  12831. * @type {BABYLON.Observable}
  12832. */
  12833. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12834. /**
  12835. * An event triggered after the world matrix is updated
  12836. * @type {BABYLON.Observable}
  12837. */
  12838. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12839. /**
  12840. * An event triggered when material is changed
  12841. * @type {BABYLON.Observable}
  12842. */
  12843. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12844. // Properties
  12845. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12846. _this.position = BABYLON.Vector3.Zero();
  12847. /**
  12848. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12849. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12850. * or
  12851. * 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.
  12852. * for more info check WebGl documentations
  12853. */
  12854. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12855. /**
  12856. * 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:
  12857. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12858. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12859. * 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.
  12860. */
  12861. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12862. /**
  12863. * 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.
  12864. * The default value is -1 which means don't break the query and wait till the result.
  12865. */
  12866. _this.occlusionRetryCount = -1;
  12867. _this._occlusionInternalRetryCounter = 0;
  12868. _this._isOccluded = false;
  12869. _this._isOcclusionQueryInProgress = false;
  12870. _this._rotation = BABYLON.Vector3.Zero();
  12871. _this._scaling = BABYLON.Vector3.One();
  12872. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12873. _this.visibility = 1.0;
  12874. _this.alphaIndex = Number.MAX_VALUE;
  12875. _this.infiniteDistance = false;
  12876. _this.isVisible = true;
  12877. _this.isPickable = true;
  12878. _this.showBoundingBox = false;
  12879. _this.showSubMeshesBoundingBox = false;
  12880. _this.isBlocker = false;
  12881. _this.enablePointerMoveEvents = false;
  12882. _this.renderingGroupId = 0;
  12883. _this._receiveShadows = false;
  12884. _this.renderOutline = false;
  12885. _this.outlineColor = BABYLON.Color3.Red();
  12886. _this.outlineWidth = 0.02;
  12887. _this.renderOverlay = false;
  12888. _this.overlayColor = BABYLON.Color3.Red();
  12889. _this.overlayAlpha = 0.5;
  12890. _this._hasVertexAlpha = false;
  12891. _this._useVertexColors = true;
  12892. _this._computeBonesUsingShaders = true;
  12893. _this._numBoneInfluencers = 4;
  12894. _this._applyFog = true;
  12895. _this.scalingDeterminant = 1;
  12896. _this.useOctreeForRenderingSelection = true;
  12897. _this.useOctreeForPicking = true;
  12898. _this.useOctreeForCollisions = true;
  12899. _this._layerMask = 0x0FFFFFFF;
  12900. /**
  12901. * True if the mesh must be rendered in any case.
  12902. */
  12903. _this.alwaysSelectAsActiveMesh = false;
  12904. // Collisions
  12905. _this._checkCollisions = false;
  12906. _this._collisionMask = -1;
  12907. _this._collisionGroup = -1;
  12908. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12909. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12910. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12911. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12912. // Edges
  12913. _this.edgesWidth = 1;
  12914. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12915. // Cache
  12916. _this._localWorld = BABYLON.Matrix.Zero();
  12917. _this._worldMatrix = BABYLON.Matrix.Zero();
  12918. _this._absolutePosition = BABYLON.Vector3.Zero();
  12919. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12920. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12921. _this._isDirty = false;
  12922. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12923. _this._postMultiplyPivotMatrix = false;
  12924. _this._isDisposed = false;
  12925. _this._renderId = 0;
  12926. _this._intersectionsInProgress = new Array();
  12927. _this._isWorldMatrixFrozen = false;
  12928. _this._unIndexed = false;
  12929. _this._lightSources = new Array();
  12930. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12931. if (collidedMesh === void 0) { collidedMesh = null; }
  12932. //TODO move this to the collision coordinator!
  12933. if (_this.getScene().workerCollisions)
  12934. newPosition.multiplyInPlace(_this._collider.radius);
  12935. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12936. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12937. _this.position.addInPlace(_this._diffPositionForCollisions);
  12938. }
  12939. if (collidedMesh) {
  12940. _this.onCollideObservable.notifyObservers(collidedMesh);
  12941. }
  12942. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12943. };
  12944. _this.getScene().addMesh(_this);
  12945. _this._resyncLightSources();
  12946. return _this;
  12947. }
  12948. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12949. get: function () {
  12950. return AbstractMesh._BILLBOARDMODE_NONE;
  12951. },
  12952. enumerable: true,
  12953. configurable: true
  12954. });
  12955. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12956. get: function () {
  12957. return AbstractMesh._BILLBOARDMODE_X;
  12958. },
  12959. enumerable: true,
  12960. configurable: true
  12961. });
  12962. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12963. get: function () {
  12964. return AbstractMesh._BILLBOARDMODE_Y;
  12965. },
  12966. enumerable: true,
  12967. configurable: true
  12968. });
  12969. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12970. get: function () {
  12971. return AbstractMesh._BILLBOARDMODE_Z;
  12972. },
  12973. enumerable: true,
  12974. configurable: true
  12975. });
  12976. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12977. get: function () {
  12978. return AbstractMesh._BILLBOARDMODE_ALL;
  12979. },
  12980. enumerable: true,
  12981. configurable: true
  12982. });
  12983. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12984. /**
  12985. * Read-only : the number of facets in the mesh
  12986. */
  12987. get: function () {
  12988. return this._facetNb;
  12989. },
  12990. enumerable: true,
  12991. configurable: true
  12992. });
  12993. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12994. /**
  12995. * The number (integer) of subdivisions per axis in the partioning space
  12996. */
  12997. get: function () {
  12998. return this._partitioningSubdivisions;
  12999. },
  13000. set: function (nb) {
  13001. this._partitioningSubdivisions = nb;
  13002. },
  13003. enumerable: true,
  13004. configurable: true
  13005. });
  13006. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  13007. /**
  13008. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  13009. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  13010. */
  13011. get: function () {
  13012. return this._partitioningBBoxRatio;
  13013. },
  13014. set: function (ratio) {
  13015. this._partitioningBBoxRatio = ratio;
  13016. },
  13017. enumerable: true,
  13018. configurable: true
  13019. });
  13020. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  13021. /**
  13022. * Read-only boolean : is the feature facetData enabled ?
  13023. */
  13024. get: function () {
  13025. return this._facetDataEnabled;
  13026. },
  13027. enumerable: true,
  13028. configurable: true
  13029. });
  13030. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  13031. get: function () {
  13032. return this._nonUniformScaling;
  13033. },
  13034. set: function (value) {
  13035. if (this._nonUniformScaling === value) {
  13036. return;
  13037. }
  13038. this._nonUniformScaling = true;
  13039. this._markSubMeshesAsMiscDirty();
  13040. },
  13041. enumerable: true,
  13042. configurable: true
  13043. });
  13044. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  13045. set: function (callback) {
  13046. if (this._onCollideObserver) {
  13047. this.onCollideObservable.remove(this._onCollideObserver);
  13048. }
  13049. this._onCollideObserver = this.onCollideObservable.add(callback);
  13050. },
  13051. enumerable: true,
  13052. configurable: true
  13053. });
  13054. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  13055. set: function (callback) {
  13056. if (this._onCollisionPositionChangeObserver) {
  13057. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  13058. }
  13059. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  13060. },
  13061. enumerable: true,
  13062. configurable: true
  13063. });
  13064. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  13065. /**
  13066. * 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.
  13067. */
  13068. get: function () {
  13069. return this._isOccluded;
  13070. },
  13071. set: function (value) {
  13072. this._isOccluded = value;
  13073. },
  13074. enumerable: true,
  13075. configurable: true
  13076. });
  13077. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  13078. /**
  13079. * Flag to check the progress status of the query
  13080. */
  13081. get: function () {
  13082. return this._isOcclusionQueryInProgress;
  13083. },
  13084. enumerable: true,
  13085. configurable: true
  13086. });
  13087. Object.defineProperty(AbstractMesh.prototype, "material", {
  13088. get: function () {
  13089. return this._material;
  13090. },
  13091. set: function (value) {
  13092. if (this._material === value) {
  13093. return;
  13094. }
  13095. this._material = value;
  13096. if (this.onMaterialChangedObservable.hasObservers) {
  13097. this.onMaterialChangedObservable.notifyObservers(this);
  13098. }
  13099. if (!this.subMeshes) {
  13100. return;
  13101. }
  13102. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13103. var subMesh = _a[_i];
  13104. subMesh.setEffect(null);
  13105. }
  13106. },
  13107. enumerable: true,
  13108. configurable: true
  13109. });
  13110. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  13111. get: function () {
  13112. return this._receiveShadows;
  13113. },
  13114. set: function (value) {
  13115. if (this._receiveShadows === value) {
  13116. return;
  13117. }
  13118. this._receiveShadows = value;
  13119. this._markSubMeshesAsLightDirty();
  13120. },
  13121. enumerable: true,
  13122. configurable: true
  13123. });
  13124. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  13125. get: function () {
  13126. return this._hasVertexAlpha;
  13127. },
  13128. set: function (value) {
  13129. if (this._hasVertexAlpha === value) {
  13130. return;
  13131. }
  13132. this._hasVertexAlpha = value;
  13133. this._markSubMeshesAsAttributesDirty();
  13134. },
  13135. enumerable: true,
  13136. configurable: true
  13137. });
  13138. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  13139. get: function () {
  13140. return this._useVertexColors;
  13141. },
  13142. set: function (value) {
  13143. if (this._useVertexColors === value) {
  13144. return;
  13145. }
  13146. this._useVertexColors = value;
  13147. this._markSubMeshesAsAttributesDirty();
  13148. },
  13149. enumerable: true,
  13150. configurable: true
  13151. });
  13152. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  13153. get: function () {
  13154. return this._computeBonesUsingShaders;
  13155. },
  13156. set: function (value) {
  13157. if (this._computeBonesUsingShaders === value) {
  13158. return;
  13159. }
  13160. this._computeBonesUsingShaders = value;
  13161. this._markSubMeshesAsAttributesDirty();
  13162. },
  13163. enumerable: true,
  13164. configurable: true
  13165. });
  13166. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  13167. get: function () {
  13168. return this._numBoneInfluencers;
  13169. },
  13170. set: function (value) {
  13171. if (this._numBoneInfluencers === value) {
  13172. return;
  13173. }
  13174. this._numBoneInfluencers = value;
  13175. this._markSubMeshesAsAttributesDirty();
  13176. },
  13177. enumerable: true,
  13178. configurable: true
  13179. });
  13180. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  13181. get: function () {
  13182. return this._applyFog;
  13183. },
  13184. set: function (value) {
  13185. if (this._applyFog === value) {
  13186. return;
  13187. }
  13188. this._applyFog = value;
  13189. this._markSubMeshesAsMiscDirty();
  13190. },
  13191. enumerable: true,
  13192. configurable: true
  13193. });
  13194. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  13195. get: function () {
  13196. return this._layerMask;
  13197. },
  13198. set: function (value) {
  13199. if (value === this._layerMask) {
  13200. return;
  13201. }
  13202. this._layerMask = value;
  13203. this._resyncLightSources();
  13204. },
  13205. enumerable: true,
  13206. configurable: true
  13207. });
  13208. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  13209. get: function () {
  13210. return this._collisionMask;
  13211. },
  13212. set: function (mask) {
  13213. this._collisionMask = !isNaN(mask) ? mask : -1;
  13214. },
  13215. enumerable: true,
  13216. configurable: true
  13217. });
  13218. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  13219. get: function () {
  13220. return this._collisionGroup;
  13221. },
  13222. set: function (mask) {
  13223. this._collisionGroup = !isNaN(mask) ? mask : -1;
  13224. },
  13225. enumerable: true,
  13226. configurable: true
  13227. });
  13228. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  13229. get: function () {
  13230. return null;
  13231. },
  13232. enumerable: true,
  13233. configurable: true
  13234. });
  13235. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  13236. get: function () {
  13237. return this._skeleton;
  13238. },
  13239. set: function (value) {
  13240. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  13241. this._skeleton._unregisterMeshWithPoseMatrix(this);
  13242. }
  13243. if (value && value.needInitialSkinMatrix) {
  13244. value._registerMeshWithPoseMatrix(this);
  13245. }
  13246. this._skeleton = value;
  13247. if (!this._skeleton) {
  13248. this._bonesTransformMatrices = null;
  13249. }
  13250. this._markSubMeshesAsAttributesDirty();
  13251. },
  13252. enumerable: true,
  13253. configurable: true
  13254. });
  13255. /**
  13256. * Boolean : true if the mesh has been disposed.
  13257. */
  13258. AbstractMesh.prototype.isDisposed = function () {
  13259. return this._isDisposed;
  13260. };
  13261. /**
  13262. * Returns the string "AbstractMesh"
  13263. */
  13264. AbstractMesh.prototype.getClassName = function () {
  13265. return "AbstractMesh";
  13266. };
  13267. /**
  13268. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13269. */
  13270. AbstractMesh.prototype.toString = function (fullDetails) {
  13271. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  13272. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  13273. if (this._skeleton) {
  13274. ret += ", skeleton: " + this._skeleton.name;
  13275. }
  13276. if (fullDetails) {
  13277. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  13278. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  13279. }
  13280. return ret;
  13281. };
  13282. AbstractMesh.prototype._rebuild = function () {
  13283. if (this._occlusionQuery) {
  13284. this._occlusionQuery = null;
  13285. }
  13286. if (this._edgesRenderer) {
  13287. this._edgesRenderer._rebuild();
  13288. }
  13289. if (!this.subMeshes) {
  13290. return;
  13291. }
  13292. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13293. var subMesh = _a[_i];
  13294. subMesh._rebuild();
  13295. }
  13296. };
  13297. AbstractMesh.prototype._resyncLightSources = function () {
  13298. this._lightSources.length = 0;
  13299. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  13300. var light = _a[_i];
  13301. if (!light.isEnabled()) {
  13302. continue;
  13303. }
  13304. if (light.canAffectMesh(this)) {
  13305. this._lightSources.push(light);
  13306. }
  13307. }
  13308. this._markSubMeshesAsLightDirty();
  13309. };
  13310. AbstractMesh.prototype._resyncLighSource = function (light) {
  13311. var isIn = light.isEnabled() && light.canAffectMesh(this);
  13312. var index = this._lightSources.indexOf(light);
  13313. if (index === -1) {
  13314. if (!isIn) {
  13315. return;
  13316. }
  13317. this._lightSources.push(light);
  13318. }
  13319. else {
  13320. if (isIn) {
  13321. return;
  13322. }
  13323. this._lightSources.splice(index, 1);
  13324. }
  13325. this._markSubMeshesAsLightDirty();
  13326. };
  13327. AbstractMesh.prototype._removeLightSource = function (light) {
  13328. var index = this._lightSources.indexOf(light);
  13329. if (index === -1) {
  13330. return;
  13331. }
  13332. this._lightSources.splice(index, 1);
  13333. };
  13334. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  13335. if (!this.subMeshes) {
  13336. return;
  13337. }
  13338. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13339. var subMesh = _a[_i];
  13340. if (subMesh._materialDefines) {
  13341. func(subMesh._materialDefines);
  13342. }
  13343. }
  13344. };
  13345. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13346. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13347. };
  13348. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13349. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13350. };
  13351. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13352. if (!this.subMeshes) {
  13353. return;
  13354. }
  13355. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13356. var subMesh = _a[_i];
  13357. var material = subMesh.getMaterial();
  13358. if (material) {
  13359. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13360. }
  13361. }
  13362. };
  13363. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13364. /**
  13365. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13366. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13367. * Default : (0.0, 0.0, 0.0)
  13368. */
  13369. get: function () {
  13370. return this._rotation;
  13371. },
  13372. set: function (newRotation) {
  13373. this._rotation = newRotation;
  13374. },
  13375. enumerable: true,
  13376. configurable: true
  13377. });
  13378. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13379. /**
  13380. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13381. * Default : (1.0, 1.0, 1.0)
  13382. */
  13383. get: function () {
  13384. return this._scaling;
  13385. },
  13386. set: function (newScaling) {
  13387. this._scaling = newScaling;
  13388. if (this.physicsImpostor) {
  13389. this.physicsImpostor.forceUpdate();
  13390. }
  13391. },
  13392. enumerable: true,
  13393. configurable: true
  13394. });
  13395. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13396. /**
  13397. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13398. * It's null by default.
  13399. * 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)
  13400. */
  13401. get: function () {
  13402. return this._rotationQuaternion;
  13403. },
  13404. set: function (quaternion) {
  13405. this._rotationQuaternion = quaternion;
  13406. //reset the rotation vector.
  13407. if (quaternion && this.rotation.length()) {
  13408. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13409. }
  13410. },
  13411. enumerable: true,
  13412. configurable: true
  13413. });
  13414. // Methods
  13415. /**
  13416. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13417. * Returns the AbstractMesh.
  13418. */
  13419. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13420. this._poseMatrix.copyFrom(matrix);
  13421. return this;
  13422. };
  13423. /**
  13424. * Returns the mesh Pose matrix.
  13425. * Returned object : Matrix
  13426. */
  13427. AbstractMesh.prototype.getPoseMatrix = function () {
  13428. return this._poseMatrix;
  13429. };
  13430. /**
  13431. * Disables the mesh edger rendering mode.
  13432. * Returns the AbstractMesh.
  13433. */
  13434. AbstractMesh.prototype.disableEdgesRendering = function () {
  13435. if (this._edgesRenderer) {
  13436. this._edgesRenderer.dispose();
  13437. this._edgesRenderer = null;
  13438. }
  13439. return this;
  13440. };
  13441. /**
  13442. * Enables the edge rendering mode on the mesh.
  13443. * This mode makes the mesh edges visible.
  13444. * Returns the AbstractMesh.
  13445. */
  13446. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13447. if (epsilon === void 0) { epsilon = 0.95; }
  13448. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13449. this.disableEdgesRendering();
  13450. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13451. return this;
  13452. };
  13453. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13454. /**
  13455. * Returns true if the mesh is blocked. Used by the class Mesh.
  13456. * Returns the boolean `false` by default.
  13457. */
  13458. get: function () {
  13459. return false;
  13460. },
  13461. enumerable: true,
  13462. configurable: true
  13463. });
  13464. /**
  13465. * Returns the mesh itself by default, used by the class Mesh.
  13466. * Returned type : AbstractMesh
  13467. */
  13468. AbstractMesh.prototype.getLOD = function (camera) {
  13469. return this;
  13470. };
  13471. /**
  13472. * Returns 0 by default, used by the class Mesh.
  13473. * Returns an integer.
  13474. */
  13475. AbstractMesh.prototype.getTotalVertices = function () {
  13476. return 0;
  13477. };
  13478. /**
  13479. * Returns null by default, used by the class Mesh.
  13480. * Returned type : integer array
  13481. */
  13482. AbstractMesh.prototype.getIndices = function () {
  13483. return null;
  13484. };
  13485. /**
  13486. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13487. * Returned type : float array or Float32Array
  13488. */
  13489. AbstractMesh.prototype.getVerticesData = function (kind) {
  13490. return null;
  13491. };
  13492. /**
  13493. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13494. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13495. * The `data` are either a numeric array either a Float32Array.
  13496. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13497. * 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).
  13498. * Note that a new underlying VertexBuffer object is created each call.
  13499. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13500. *
  13501. * Possible `kind` values :
  13502. * - BABYLON.VertexBuffer.PositionKind
  13503. * - BABYLON.VertexBuffer.UVKind
  13504. * - BABYLON.VertexBuffer.UV2Kind
  13505. * - BABYLON.VertexBuffer.UV3Kind
  13506. * - BABYLON.VertexBuffer.UV4Kind
  13507. * - BABYLON.VertexBuffer.UV5Kind
  13508. * - BABYLON.VertexBuffer.UV6Kind
  13509. * - BABYLON.VertexBuffer.ColorKind
  13510. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13511. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13512. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13513. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13514. *
  13515. * Returns the Mesh.
  13516. */
  13517. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13518. return this;
  13519. };
  13520. /**
  13521. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13522. * If the mesh has no geometry, it is simply returned as it is.
  13523. * The `data` are either a numeric array either a Float32Array.
  13524. * No new underlying VertexBuffer object is created.
  13525. * 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.
  13526. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13527. *
  13528. * Possible `kind` values :
  13529. * - BABYLON.VertexBuffer.PositionKind
  13530. * - BABYLON.VertexBuffer.UVKind
  13531. * - BABYLON.VertexBuffer.UV2Kind
  13532. * - BABYLON.VertexBuffer.UV3Kind
  13533. * - BABYLON.VertexBuffer.UV4Kind
  13534. * - BABYLON.VertexBuffer.UV5Kind
  13535. * - BABYLON.VertexBuffer.UV6Kind
  13536. * - BABYLON.VertexBuffer.ColorKind
  13537. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13538. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13539. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13540. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13541. *
  13542. * Returns the Mesh.
  13543. */
  13544. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13545. return this;
  13546. };
  13547. /**
  13548. * Sets the mesh indices.
  13549. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13550. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13551. * This method creates a new index buffer each call.
  13552. * Returns the Mesh.
  13553. */
  13554. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13555. return this;
  13556. };
  13557. /** Returns false by default, used by the class Mesh.
  13558. * Returns a boolean
  13559. */
  13560. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13561. return false;
  13562. };
  13563. /**
  13564. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13565. * Returns a BoundingInfo
  13566. */
  13567. AbstractMesh.prototype.getBoundingInfo = function () {
  13568. if (this._masterMesh) {
  13569. return this._masterMesh.getBoundingInfo();
  13570. }
  13571. if (!this._boundingInfo) {
  13572. this._updateBoundingInfo();
  13573. }
  13574. return this._boundingInfo;
  13575. };
  13576. /**
  13577. * Sets a mesh new object BoundingInfo.
  13578. * Returns the AbstractMesh.
  13579. */
  13580. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13581. this._boundingInfo = boundingInfo;
  13582. return this;
  13583. };
  13584. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13585. get: function () {
  13586. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13587. },
  13588. enumerable: true,
  13589. configurable: true
  13590. });
  13591. AbstractMesh.prototype._preActivate = function () {
  13592. };
  13593. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13594. };
  13595. AbstractMesh.prototype._activate = function (renderId) {
  13596. this._renderId = renderId;
  13597. };
  13598. /**
  13599. * Returns the last update of the World matrix
  13600. * Returns a Matrix.
  13601. */
  13602. AbstractMesh.prototype.getWorldMatrix = function () {
  13603. if (this._masterMesh) {
  13604. return this._masterMesh.getWorldMatrix();
  13605. }
  13606. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  13607. this.computeWorldMatrix();
  13608. }
  13609. return this._worldMatrix;
  13610. };
  13611. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13612. /**
  13613. * Returns directly the last state of the mesh World matrix.
  13614. * A Matrix is returned.
  13615. */
  13616. get: function () {
  13617. return this._worldMatrix;
  13618. },
  13619. enumerable: true,
  13620. configurable: true
  13621. });
  13622. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13623. /**
  13624. * Returns the current mesh absolute position.
  13625. * Retuns a Vector3.
  13626. */
  13627. get: function () {
  13628. return this._absolutePosition;
  13629. },
  13630. enumerable: true,
  13631. configurable: true
  13632. });
  13633. /**
  13634. * Prevents the World matrix to be computed any longer.
  13635. * Returns the AbstractMesh.
  13636. */
  13637. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13638. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13639. this.computeWorldMatrix(true);
  13640. this._isWorldMatrixFrozen = true;
  13641. return this;
  13642. };
  13643. /**
  13644. * Allows back the World matrix computation.
  13645. * Returns the AbstractMesh.
  13646. */
  13647. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13648. this._isWorldMatrixFrozen = false;
  13649. this.computeWorldMatrix(true);
  13650. return this;
  13651. };
  13652. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13653. /**
  13654. * True if the World matrix has been frozen.
  13655. * Returns a boolean.
  13656. */
  13657. get: function () {
  13658. return this._isWorldMatrixFrozen;
  13659. },
  13660. enumerable: true,
  13661. configurable: true
  13662. });
  13663. /**
  13664. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13665. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13666. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13667. * The passed axis is also normalized.
  13668. * Returns the AbstractMesh.
  13669. */
  13670. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13671. axis.normalize();
  13672. if (!this.rotationQuaternion) {
  13673. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13674. this.rotation = BABYLON.Vector3.Zero();
  13675. }
  13676. var rotationQuaternion;
  13677. if (!space || space === BABYLON.Space.LOCAL) {
  13678. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13679. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13680. }
  13681. else {
  13682. if (this.parent) {
  13683. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13684. invertParentWorldMatrix.invert();
  13685. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13686. }
  13687. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13688. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13689. }
  13690. return this;
  13691. };
  13692. /**
  13693. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13694. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13695. * The passed axis is also normalized.
  13696. * Returns the AbstractMesh.
  13697. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13698. */
  13699. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13700. axis.normalize();
  13701. if (!this.rotationQuaternion) {
  13702. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13703. this.rotation.copyFromFloats(0, 0, 0);
  13704. }
  13705. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13706. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13707. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13708. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13709. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13710. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13711. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13712. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13713. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13714. return this;
  13715. };
  13716. /**
  13717. * Translates the mesh along the axis vector for the passed distance in the given space.
  13718. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13719. * Returns the AbstractMesh.
  13720. */
  13721. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13722. var displacementVector = axis.scale(distance);
  13723. if (!space || space === BABYLON.Space.LOCAL) {
  13724. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13725. this.setPositionWithLocalVector(tempV3);
  13726. }
  13727. else {
  13728. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13729. }
  13730. return this;
  13731. };
  13732. /**
  13733. * Adds a rotation step to the mesh current rotation.
  13734. * x, y, z are Euler angles expressed in radians.
  13735. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13736. * This means this rotation is made in the mesh local space only.
  13737. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13738. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13739. * ```javascript
  13740. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13741. * ```
  13742. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13743. * 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.
  13744. * Returns the AbstractMesh.
  13745. */
  13746. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13747. var rotationQuaternion;
  13748. if (this.rotationQuaternion) {
  13749. rotationQuaternion = this.rotationQuaternion;
  13750. }
  13751. else {
  13752. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13753. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13754. }
  13755. var accumulation = BABYLON.Tmp.Quaternion[0];
  13756. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13757. rotationQuaternion.multiplyInPlace(accumulation);
  13758. if (!this.rotationQuaternion) {
  13759. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13760. }
  13761. return this;
  13762. };
  13763. /**
  13764. * Retuns the mesh absolute position in the World.
  13765. * Returns a Vector3.
  13766. */
  13767. AbstractMesh.prototype.getAbsolutePosition = function () {
  13768. this.computeWorldMatrix();
  13769. return this._absolutePosition;
  13770. };
  13771. /**
  13772. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13773. * Returns the AbstractMesh.
  13774. */
  13775. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13776. if (!absolutePosition) {
  13777. return this;
  13778. }
  13779. var absolutePositionX;
  13780. var absolutePositionY;
  13781. var absolutePositionZ;
  13782. if (absolutePosition.x === undefined) {
  13783. if (arguments.length < 3) {
  13784. return this;
  13785. }
  13786. absolutePositionX = arguments[0];
  13787. absolutePositionY = arguments[1];
  13788. absolutePositionZ = arguments[2];
  13789. }
  13790. else {
  13791. absolutePositionX = absolutePosition.x;
  13792. absolutePositionY = absolutePosition.y;
  13793. absolutePositionZ = absolutePosition.z;
  13794. }
  13795. if (this.parent) {
  13796. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13797. invertParentWorldMatrix.invert();
  13798. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13799. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13800. }
  13801. else {
  13802. this.position.x = absolutePositionX;
  13803. this.position.y = absolutePositionY;
  13804. this.position.z = absolutePositionZ;
  13805. }
  13806. return this;
  13807. };
  13808. // ================================== Point of View Movement =================================
  13809. /**
  13810. * Perform relative position change from the point of view of behind the front of the mesh.
  13811. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13812. * Supports definition of mesh facing forward or backward.
  13813. * @param {number} amountRight
  13814. * @param {number} amountUp
  13815. * @param {number} amountForward
  13816. *
  13817. * Returns the AbstractMesh.
  13818. */
  13819. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13820. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13821. return this;
  13822. };
  13823. /**
  13824. * Calculate relative position change from the point of view of behind the front of the mesh.
  13825. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13826. * Supports definition of mesh facing forward or backward.
  13827. * @param {number} amountRight
  13828. * @param {number} amountUp
  13829. * @param {number} amountForward
  13830. *
  13831. * Returns a new Vector3.
  13832. */
  13833. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13834. var rotMatrix = new BABYLON.Matrix();
  13835. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13836. rotQuaternion.toRotationMatrix(rotMatrix);
  13837. var translationDelta = BABYLON.Vector3.Zero();
  13838. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13839. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13840. return translationDelta;
  13841. };
  13842. // ================================== Point of View Rotation =================================
  13843. /**
  13844. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13845. * Supports definition of mesh facing forward or backward.
  13846. * @param {number} flipBack
  13847. * @param {number} twirlClockwise
  13848. * @param {number} tiltRight
  13849. *
  13850. * Returns the AbstractMesh.
  13851. */
  13852. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13853. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13854. return this;
  13855. };
  13856. /**
  13857. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13858. * Supports definition of mesh facing forward or backward.
  13859. * @param {number} flipBack
  13860. * @param {number} twirlClockwise
  13861. * @param {number} tiltRight
  13862. *
  13863. * Returns a new Vector3.
  13864. */
  13865. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13866. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13867. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13868. };
  13869. /**
  13870. * Sets a new pivot matrix to the mesh.
  13871. * Returns the AbstractMesh.
  13872. */
  13873. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13874. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13875. this._pivotMatrix = matrix.clone();
  13876. this._cache.pivotMatrixUpdated = true;
  13877. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13878. if (this._postMultiplyPivotMatrix) {
  13879. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13880. }
  13881. return this;
  13882. };
  13883. /**
  13884. * Returns the mesh pivot matrix.
  13885. * Default : Identity.
  13886. * A Matrix is returned.
  13887. */
  13888. AbstractMesh.prototype.getPivotMatrix = function () {
  13889. return this._pivotMatrix;
  13890. };
  13891. AbstractMesh.prototype._isSynchronized = function () {
  13892. if (this._isDirty) {
  13893. return false;
  13894. }
  13895. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13896. return false;
  13897. if (this._cache.pivotMatrixUpdated) {
  13898. return false;
  13899. }
  13900. if (this.infiniteDistance) {
  13901. return false;
  13902. }
  13903. if (!this._cache.position.equals(this.position))
  13904. return false;
  13905. if (this.rotationQuaternion) {
  13906. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13907. return false;
  13908. }
  13909. if (!this._cache.rotation.equals(this.rotation))
  13910. return false;
  13911. if (!this._cache.scaling.equals(this.scaling))
  13912. return false;
  13913. return true;
  13914. };
  13915. AbstractMesh.prototype._initCache = function () {
  13916. _super.prototype._initCache.call(this);
  13917. this._cache.localMatrixUpdated = false;
  13918. this._cache.position = BABYLON.Vector3.Zero();
  13919. this._cache.scaling = BABYLON.Vector3.Zero();
  13920. this._cache.rotation = BABYLON.Vector3.Zero();
  13921. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13922. this._cache.billboardMode = -1;
  13923. };
  13924. AbstractMesh.prototype.markAsDirty = function (property) {
  13925. if (property === "rotation") {
  13926. this.rotationQuaternion = null;
  13927. }
  13928. this._currentRenderId = Number.MAX_VALUE;
  13929. this._isDirty = true;
  13930. return this;
  13931. };
  13932. /**
  13933. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13934. */
  13935. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13936. this.computeWorldMatrix(true);
  13937. var min;
  13938. var max;
  13939. var boundingInfo = this.getBoundingInfo();
  13940. if (!this.subMeshes || !boundingInfo) {
  13941. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13942. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13943. }
  13944. else {
  13945. min = boundingInfo.boundingBox.minimumWorld;
  13946. max = boundingInfo.boundingBox.maximumWorld;
  13947. }
  13948. var descendants = this.getDescendants(false);
  13949. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13950. var descendant = descendants_1[_i];
  13951. var childMesh = descendant;
  13952. childMesh.computeWorldMatrix(true);
  13953. var childBoundingInfo = childMesh.getBoundingInfo();
  13954. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  13955. continue;
  13956. }
  13957. var boundingBox = childBoundingInfo.boundingBox;
  13958. var minBox = boundingBox.minimumWorld;
  13959. var maxBox = boundingBox.maximumWorld;
  13960. BABYLON.Tools.CheckExtends(minBox, min, max);
  13961. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13962. }
  13963. return {
  13964. min: min,
  13965. max: max
  13966. };
  13967. };
  13968. /**
  13969. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13970. * Returns the AbstractMesh.
  13971. */
  13972. AbstractMesh.prototype._updateBoundingInfo = function () {
  13973. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13974. this._boundingInfo.update(this.worldMatrixFromCache);
  13975. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13976. return this;
  13977. };
  13978. /**
  13979. * Update a mesh's children BoundingInfo objects only.
  13980. * Returns the AbstractMesh.
  13981. */
  13982. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13983. if (!this.subMeshes) {
  13984. return this;
  13985. }
  13986. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13987. var subMesh = this.subMeshes[subIndex];
  13988. if (!subMesh.IsGlobal) {
  13989. subMesh.updateBoundingInfo(matrix);
  13990. }
  13991. }
  13992. return this;
  13993. };
  13994. /**
  13995. * Computes the mesh World matrix and returns it.
  13996. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13997. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13998. * If the parameter `force`is set to `true`, the actual computation is done.
  13999. * Returns the mesh World Matrix.
  14000. */
  14001. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  14002. if (this._isWorldMatrixFrozen) {
  14003. return this._worldMatrix;
  14004. }
  14005. if (!force && this.isSynchronized(true)) {
  14006. this._currentRenderId = this.getScene().getRenderId();
  14007. return this._worldMatrix;
  14008. }
  14009. this._cache.position.copyFrom(this.position);
  14010. this._cache.scaling.copyFrom(this.scaling);
  14011. this._cache.pivotMatrixUpdated = false;
  14012. this._cache.billboardMode = this.billboardMode;
  14013. this._currentRenderId = this.getScene().getRenderId();
  14014. this._isDirty = false;
  14015. // Scaling
  14016. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14017. // Rotation
  14018. //rotate, if quaternion is set and rotation was used
  14019. if (this.rotationQuaternion) {
  14020. var len = this.rotation.length();
  14021. if (len) {
  14022. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14023. this.rotation.copyFromFloats(0, 0, 0);
  14024. }
  14025. }
  14026. if (this.rotationQuaternion) {
  14027. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14028. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14029. }
  14030. else {
  14031. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14032. this._cache.rotation.copyFrom(this.rotation);
  14033. }
  14034. // Translation
  14035. var camera = this.getScene().activeCamera;
  14036. if (this.infiniteDistance && !this.parent && camera) {
  14037. var cameraWorldMatrix = camera.getWorldMatrix();
  14038. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14039. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14040. }
  14041. else {
  14042. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14043. }
  14044. // Composing transformations
  14045. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14046. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14047. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14048. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14049. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  14050. // Need to decompose each rotation here
  14051. var currentPosition = BABYLON.Tmp.Vector3[3];
  14052. if (this.parent && this.parent.getWorldMatrix) {
  14053. if (this._meshToBoneReferal) {
  14054. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14055. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14056. }
  14057. else {
  14058. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14059. }
  14060. }
  14061. else {
  14062. currentPosition.copyFrom(this.position);
  14063. }
  14064. currentPosition.subtractInPlace(camera.globalPosition);
  14065. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14066. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  14067. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14068. }
  14069. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  14070. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14071. }
  14072. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  14073. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14074. }
  14075. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14076. }
  14077. else {
  14078. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14079. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14080. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14081. }
  14082. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14083. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14084. }
  14085. // Local world
  14086. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14087. // Parent
  14088. if (this.parent && this.parent.getWorldMatrix) {
  14089. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  14090. if (this._meshToBoneReferal) {
  14091. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14092. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14093. }
  14094. else {
  14095. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14096. }
  14097. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14098. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14099. this._worldMatrix.copyFrom(this._localWorld);
  14100. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14101. }
  14102. else {
  14103. if (this._meshToBoneReferal) {
  14104. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14105. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14106. }
  14107. else {
  14108. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14109. }
  14110. }
  14111. this._markSyncedWithParent();
  14112. }
  14113. else {
  14114. this._worldMatrix.copyFrom(this._localWorld);
  14115. }
  14116. // Post multiply inverse of pivotMatrix
  14117. if (this._postMultiplyPivotMatrix) {
  14118. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14119. }
  14120. // Normal matrix
  14121. if (this.scaling.isNonUniform) {
  14122. this.nonUniformScaling = true;
  14123. }
  14124. else if (this.parent && this.parent._nonUniformScaling) {
  14125. this.nonUniformScaling = this.parent._nonUniformScaling;
  14126. }
  14127. else {
  14128. this.nonUniformScaling = false;
  14129. }
  14130. // Bounding info
  14131. this._updateBoundingInfo();
  14132. // Absolute position
  14133. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14134. // Callbacks
  14135. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14136. if (!this._poseMatrix) {
  14137. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14138. }
  14139. return this._worldMatrix;
  14140. };
  14141. /**
  14142. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14143. * @param func: callback function to add
  14144. *
  14145. * Returns the AbstractMesh.
  14146. */
  14147. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14148. this.onAfterWorldMatrixUpdateObservable.add(func);
  14149. return this;
  14150. };
  14151. /**
  14152. * Removes a registered callback function.
  14153. * Returns the AbstractMesh.
  14154. */
  14155. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14156. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14157. return this;
  14158. };
  14159. /**
  14160. * Sets the mesh position in its local space.
  14161. * Returns the AbstractMesh.
  14162. */
  14163. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  14164. this.computeWorldMatrix();
  14165. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14166. return this;
  14167. };
  14168. /**
  14169. * Returns the mesh position in the local space from the current World matrix values.
  14170. * Returns a new Vector3.
  14171. */
  14172. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  14173. this.computeWorldMatrix();
  14174. var invLocalWorldMatrix = this._localWorld.clone();
  14175. invLocalWorldMatrix.invert();
  14176. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14177. };
  14178. /**
  14179. * Translates the mesh along the passed Vector3 in its local space.
  14180. * Returns the AbstractMesh.
  14181. */
  14182. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  14183. this.computeWorldMatrix(true);
  14184. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14185. return this;
  14186. };
  14187. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14188. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  14189. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  14190. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  14191. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  14192. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  14193. /// <returns>Mesh oriented towards targetMesh</returns>
  14194. if (yawCor === void 0) { yawCor = 0; }
  14195. if (pitchCor === void 0) { pitchCor = 0; }
  14196. if (rollCor === void 0) { rollCor = 0; }
  14197. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14198. var dv = AbstractMesh._lookAtVectorCache;
  14199. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14200. targetPoint.subtractToRef(pos, dv);
  14201. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14202. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14203. var pitch = Math.atan2(dv.y, len);
  14204. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  14205. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14206. return this;
  14207. };
  14208. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  14209. this._meshToBoneReferal = affectedMesh;
  14210. this.parent = bone;
  14211. if (bone.getWorldMatrix().determinant() < 0) {
  14212. this.scalingDeterminant *= -1;
  14213. }
  14214. return this;
  14215. };
  14216. AbstractMesh.prototype.detachFromBone = function () {
  14217. if (!this.parent) {
  14218. return this;
  14219. }
  14220. if (this.parent.getWorldMatrix().determinant() < 0) {
  14221. this.scalingDeterminant *= -1;
  14222. }
  14223. this._meshToBoneReferal = null;
  14224. this.parent = null;
  14225. return this;
  14226. };
  14227. /**
  14228. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14229. * A mesh is in the frustum if its bounding box intersects the frustum.
  14230. * Boolean returned.
  14231. */
  14232. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14233. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14234. };
  14235. /**
  14236. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14237. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14238. * Boolean returned.
  14239. */
  14240. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14241. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14242. ;
  14243. };
  14244. /**
  14245. * True if the mesh intersects another mesh or a SolidParticle object.
  14246. * 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)
  14247. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14248. * Returns a boolean.
  14249. */
  14250. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14251. if (precise === void 0) { precise = false; }
  14252. if (!this._boundingInfo || !mesh._boundingInfo) {
  14253. return false;
  14254. }
  14255. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14256. return true;
  14257. }
  14258. if (includeDescendants) {
  14259. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14260. var child = _a[_i];
  14261. if (child.intersectsMesh(mesh, precise, true)) {
  14262. return true;
  14263. }
  14264. }
  14265. }
  14266. return false;
  14267. };
  14268. /**
  14269. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14270. * Returns a boolean.
  14271. */
  14272. AbstractMesh.prototype.intersectsPoint = function (point) {
  14273. if (!this._boundingInfo) {
  14274. return false;
  14275. }
  14276. return this._boundingInfo.intersectsPoint(point);
  14277. };
  14278. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14279. return this.physicsImpostor;
  14280. };
  14281. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14282. if (camera === void 0) { camera = null; }
  14283. if (!camera) {
  14284. camera = this.getScene().activeCamera;
  14285. }
  14286. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14287. };
  14288. /**
  14289. * Returns the distance from the mesh to the active camera.
  14290. * Returns a float.
  14291. */
  14292. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14293. if (camera === void 0) { camera = null; }
  14294. if (!camera) {
  14295. camera = this.getScene().activeCamera;
  14296. }
  14297. return this.absolutePosition.subtract(camera.position).length();
  14298. };
  14299. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14300. if (!this.physicsImpostor) {
  14301. return this;
  14302. }
  14303. this.physicsImpostor.applyImpulse(force, contactPoint);
  14304. return this;
  14305. };
  14306. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14307. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14308. return this;
  14309. }
  14310. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14311. mainPivot: pivot1,
  14312. connectedPivot: pivot2,
  14313. nativeParams: options
  14314. });
  14315. return this;
  14316. };
  14317. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14318. // Collisions
  14319. /**
  14320. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14321. * Default `false`.
  14322. */
  14323. get: function () {
  14324. return this._checkCollisions;
  14325. },
  14326. set: function (collisionEnabled) {
  14327. this._checkCollisions = collisionEnabled;
  14328. if (this.getScene().workerCollisions) {
  14329. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14330. }
  14331. },
  14332. enumerable: true,
  14333. configurable: true
  14334. });
  14335. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14336. var globalPosition = this.getAbsolutePosition();
  14337. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14338. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14339. if (!this._collider) {
  14340. this._collider = new BABYLON.Collider();
  14341. }
  14342. this._collider.radius = this.ellipsoid;
  14343. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14344. return this;
  14345. };
  14346. // Submeshes octree
  14347. /**
  14348. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14349. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14350. * Returns an Octree of submeshes.
  14351. */
  14352. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14353. if (maxCapacity === void 0) { maxCapacity = 64; }
  14354. if (maxDepth === void 0) { maxDepth = 2; }
  14355. if (!this._submeshesOctree) {
  14356. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14357. }
  14358. this.computeWorldMatrix(true);
  14359. var boundingInfo = this.getBoundingInfo();
  14360. // Update octree
  14361. if (boundingInfo) {
  14362. var bbox = boundingInfo.boundingBox;
  14363. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14364. }
  14365. return this._submeshesOctree;
  14366. };
  14367. // Collisions
  14368. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14369. this._generatePointsArray();
  14370. if (!this._positions) {
  14371. return this;
  14372. }
  14373. // Transformation
  14374. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14375. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14376. subMesh._lastColliderWorldVertices = [];
  14377. subMesh._trianglePlanes = [];
  14378. var start = subMesh.verticesStart;
  14379. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14380. for (var i = start; i < end; i++) {
  14381. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14382. }
  14383. }
  14384. // Collide
  14385. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14386. if (collider.collisionFound) {
  14387. collider.collidedMesh = this;
  14388. }
  14389. return this;
  14390. };
  14391. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14392. var subMeshes;
  14393. var len;
  14394. // Octrees
  14395. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14396. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14397. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14398. len = intersections.length;
  14399. subMeshes = intersections.data;
  14400. }
  14401. else {
  14402. subMeshes = this.subMeshes;
  14403. len = subMeshes.length;
  14404. }
  14405. for (var index = 0; index < len; index++) {
  14406. var subMesh = subMeshes[index];
  14407. // Bounding test
  14408. if (len > 1 && !subMesh._checkCollision(collider))
  14409. continue;
  14410. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14411. }
  14412. return this;
  14413. };
  14414. AbstractMesh.prototype._checkCollision = function (collider) {
  14415. // Bounding box test
  14416. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14417. return this;
  14418. // Transformation matrix
  14419. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14420. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14421. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14422. return this;
  14423. };
  14424. // Picking
  14425. AbstractMesh.prototype._generatePointsArray = function () {
  14426. return false;
  14427. };
  14428. /**
  14429. * Checks if the passed Ray intersects with the mesh.
  14430. * Returns an object PickingInfo.
  14431. */
  14432. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14433. var pickingInfo = new BABYLON.PickingInfo();
  14434. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14435. return pickingInfo;
  14436. }
  14437. if (!this._generatePointsArray()) {
  14438. return pickingInfo;
  14439. }
  14440. var intersectInfo = null;
  14441. // Octrees
  14442. var subMeshes;
  14443. var len;
  14444. if (this._submeshesOctree && this.useOctreeForPicking) {
  14445. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14446. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14447. len = intersections.length;
  14448. subMeshes = intersections.data;
  14449. }
  14450. else {
  14451. subMeshes = this.subMeshes;
  14452. len = subMeshes.length;
  14453. }
  14454. for (var index = 0; index < len; index++) {
  14455. var subMesh = subMeshes[index];
  14456. // Bounding test
  14457. if (len > 1 && !subMesh.canIntersects(ray))
  14458. continue;
  14459. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14460. if (currentIntersectInfo) {
  14461. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14462. intersectInfo = currentIntersectInfo;
  14463. intersectInfo.subMeshId = index;
  14464. if (fastCheck) {
  14465. break;
  14466. }
  14467. }
  14468. }
  14469. }
  14470. if (intersectInfo) {
  14471. // Get picked point
  14472. var world = this.getWorldMatrix();
  14473. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14474. var direction = ray.direction.clone();
  14475. direction = direction.scale(intersectInfo.distance);
  14476. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14477. var pickedPoint = worldOrigin.add(worldDirection);
  14478. // Return result
  14479. pickingInfo.hit = true;
  14480. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14481. pickingInfo.pickedPoint = pickedPoint;
  14482. pickingInfo.pickedMesh = this;
  14483. pickingInfo.bu = intersectInfo.bu || 0;
  14484. pickingInfo.bv = intersectInfo.bv || 0;
  14485. pickingInfo.faceId = intersectInfo.faceId;
  14486. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14487. return pickingInfo;
  14488. }
  14489. return pickingInfo;
  14490. };
  14491. /**
  14492. * Clones the mesh, used by the class Mesh.
  14493. * Just returns `null` for an AbstractMesh.
  14494. */
  14495. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14496. return null;
  14497. };
  14498. /**
  14499. * Disposes all the mesh submeshes.
  14500. * Returns the AbstractMesh.
  14501. */
  14502. AbstractMesh.prototype.releaseSubMeshes = function () {
  14503. if (this.subMeshes) {
  14504. while (this.subMeshes.length) {
  14505. this.subMeshes[0].dispose();
  14506. }
  14507. }
  14508. else {
  14509. this.subMeshes = new Array();
  14510. }
  14511. return this;
  14512. };
  14513. /**
  14514. * Disposes the AbstractMesh.
  14515. * Some internal references are kept for further use.
  14516. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14517. * Returns nothing.
  14518. */
  14519. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14520. var _this = this;
  14521. var index;
  14522. // Action manager
  14523. if (this.actionManager) {
  14524. this.actionManager.dispose();
  14525. this.actionManager = null;
  14526. }
  14527. // Skeleton
  14528. this.skeleton = null;
  14529. // Animations
  14530. this.getScene().stopAnimation(this);
  14531. // Physics
  14532. if (this.physicsImpostor) {
  14533. this.physicsImpostor.dispose();
  14534. }
  14535. // Intersections in progress
  14536. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14537. var other = this._intersectionsInProgress[index];
  14538. var pos = other._intersectionsInProgress.indexOf(this);
  14539. other._intersectionsInProgress.splice(pos, 1);
  14540. }
  14541. this._intersectionsInProgress = [];
  14542. // Lights
  14543. var lights = this.getScene().lights;
  14544. lights.forEach(function (light) {
  14545. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14546. if (meshIndex !== -1) {
  14547. light.includedOnlyMeshes.splice(meshIndex, 1);
  14548. }
  14549. meshIndex = light.excludedMeshes.indexOf(_this);
  14550. if (meshIndex !== -1) {
  14551. light.excludedMeshes.splice(meshIndex, 1);
  14552. }
  14553. // Shadow generators
  14554. var generator = light.getShadowGenerator();
  14555. if (generator) {
  14556. var shadowMap = generator.getShadowMap();
  14557. if (shadowMap && shadowMap.renderList) {
  14558. meshIndex = shadowMap.renderList.indexOf(_this);
  14559. if (meshIndex !== -1) {
  14560. shadowMap.renderList.splice(meshIndex, 1);
  14561. }
  14562. }
  14563. }
  14564. });
  14565. // Edges
  14566. if (this._edgesRenderer) {
  14567. this._edgesRenderer.dispose();
  14568. this._edgesRenderer = null;
  14569. }
  14570. // SubMeshes
  14571. if (this.getClassName() !== "InstancedMesh") {
  14572. this.releaseSubMeshes();
  14573. }
  14574. // Octree
  14575. var sceneOctree = this.getScene().selectionOctree;
  14576. if (sceneOctree) {
  14577. var index = sceneOctree.dynamicContent.indexOf(this);
  14578. if (index !== -1) {
  14579. sceneOctree.dynamicContent.splice(index, 1);
  14580. }
  14581. }
  14582. // Query
  14583. var engine = this.getScene().getEngine();
  14584. if (this._occlusionQuery) {
  14585. this._isOcclusionQueryInProgress = false;
  14586. engine.deleteQuery(this._occlusionQuery);
  14587. this._occlusionQuery = null;
  14588. }
  14589. // Engine
  14590. engine.wipeCaches();
  14591. // Remove from scene
  14592. this.getScene().removeMesh(this);
  14593. if (!doNotRecurse) {
  14594. // Particles
  14595. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14596. if (this.getScene().particleSystems[index].emitter === this) {
  14597. this.getScene().particleSystems[index].dispose();
  14598. index--;
  14599. }
  14600. }
  14601. // Children
  14602. var objects = this.getDescendants(true);
  14603. for (index = 0; index < objects.length; index++) {
  14604. objects[index].dispose();
  14605. }
  14606. }
  14607. else {
  14608. var childMeshes = this.getChildMeshes(true);
  14609. for (index = 0; index < childMeshes.length; index++) {
  14610. var child = childMeshes[index];
  14611. child.parent = null;
  14612. child.computeWorldMatrix(true);
  14613. }
  14614. }
  14615. // facet data
  14616. if (this._facetDataEnabled) {
  14617. this.disableFacetData();
  14618. }
  14619. this.onAfterWorldMatrixUpdateObservable.clear();
  14620. this.onCollideObservable.clear();
  14621. this.onCollisionPositionChangeObservable.clear();
  14622. this._isDisposed = true;
  14623. _super.prototype.dispose.call(this);
  14624. };
  14625. /**
  14626. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14627. * This Vector3 is expressed in the World space.
  14628. */
  14629. AbstractMesh.prototype.getDirection = function (localAxis) {
  14630. var result = BABYLON.Vector3.Zero();
  14631. this.getDirectionToRef(localAxis, result);
  14632. return result;
  14633. };
  14634. /**
  14635. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14636. * localAxis is expressed in the mesh local space.
  14637. * result is computed in the Wordl space from the mesh World matrix.
  14638. * Returns the AbstractMesh.
  14639. */
  14640. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14641. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14642. return this;
  14643. };
  14644. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14645. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14646. if (this.getScene().getRenderId() == 0) {
  14647. this.computeWorldMatrix(true);
  14648. }
  14649. var wm = this.getWorldMatrix();
  14650. if (space == BABYLON.Space.WORLD) {
  14651. var tmat = BABYLON.Tmp.Matrix[0];
  14652. wm.invertToRef(tmat);
  14653. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14654. }
  14655. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14656. this._pivotMatrix.m[12] = -point.x;
  14657. this._pivotMatrix.m[13] = -point.y;
  14658. this._pivotMatrix.m[14] = -point.z;
  14659. this._cache.pivotMatrixUpdated = true;
  14660. return this;
  14661. };
  14662. /**
  14663. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14664. */
  14665. AbstractMesh.prototype.getPivotPoint = function () {
  14666. var point = BABYLON.Vector3.Zero();
  14667. this.getPivotPointToRef(point);
  14668. return point;
  14669. };
  14670. /**
  14671. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14672. * Returns the AbstractMesh.
  14673. */
  14674. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14675. result.x = -this._pivotMatrix.m[12];
  14676. result.y = -this._pivotMatrix.m[13];
  14677. result.z = -this._pivotMatrix.m[14];
  14678. return this;
  14679. };
  14680. /**
  14681. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14682. */
  14683. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14684. var point = BABYLON.Vector3.Zero();
  14685. this.getAbsolutePivotPointToRef(point);
  14686. return point;
  14687. };
  14688. /**
  14689. * Defines the passed mesh as the parent of the current mesh.
  14690. * Returns the AbstractMesh.
  14691. */
  14692. AbstractMesh.prototype.setParent = function (mesh) {
  14693. var parent = mesh;
  14694. if (mesh == null) {
  14695. var rotation = BABYLON.Tmp.Quaternion[0];
  14696. var position = BABYLON.Tmp.Vector3[0];
  14697. var scale = BABYLON.Tmp.Vector3[1];
  14698. this.getWorldMatrix().decompose(scale, rotation, position);
  14699. if (this.rotationQuaternion) {
  14700. this.rotationQuaternion.copyFrom(rotation);
  14701. }
  14702. else {
  14703. rotation.toEulerAnglesToRef(this.rotation);
  14704. }
  14705. this.position.x = position.x;
  14706. this.position.y = position.y;
  14707. this.position.z = position.z;
  14708. }
  14709. else {
  14710. var position = BABYLON.Tmp.Vector3[0];
  14711. var m1 = BABYLON.Tmp.Matrix[0];
  14712. parent.getWorldMatrix().invertToRef(m1);
  14713. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  14714. this.position.copyFrom(position);
  14715. }
  14716. this.parent = parent;
  14717. return this;
  14718. };
  14719. /**
  14720. * Adds the passed mesh as a child to the current mesh.
  14721. * Returns the AbstractMesh.
  14722. */
  14723. AbstractMesh.prototype.addChild = function (mesh) {
  14724. mesh.setParent(this);
  14725. return this;
  14726. };
  14727. /**
  14728. * Removes the passed mesh from the current mesh children list.
  14729. * Returns the AbstractMesh.
  14730. */
  14731. AbstractMesh.prototype.removeChild = function (mesh) {
  14732. mesh.setParent(null);
  14733. return this;
  14734. };
  14735. /**
  14736. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14737. * Returns the AbstractMesh.
  14738. */
  14739. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14740. result.x = this._pivotMatrix.m[12];
  14741. result.y = this._pivotMatrix.m[13];
  14742. result.z = this._pivotMatrix.m[14];
  14743. this.getPivotPointToRef(result);
  14744. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14745. return this;
  14746. };
  14747. // Facet data
  14748. /**
  14749. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14750. * Returns the AbstractMesh.
  14751. */
  14752. AbstractMesh.prototype._initFacetData = function () {
  14753. if (!this._facetNormals) {
  14754. this._facetNormals = new Array();
  14755. }
  14756. if (!this._facetPositions) {
  14757. this._facetPositions = new Array();
  14758. }
  14759. if (!this._facetPartitioning) {
  14760. this._facetPartitioning = new Array();
  14761. }
  14762. this._facetNb = this.getIndices().length / 3;
  14763. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14764. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14765. for (var f = 0; f < this._facetNb; f++) {
  14766. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14767. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14768. }
  14769. this._facetDataEnabled = true;
  14770. return this;
  14771. };
  14772. /**
  14773. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14774. * This method can be called within the render loop.
  14775. * 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.
  14776. * Returns the AbstractMesh.
  14777. */
  14778. AbstractMesh.prototype.updateFacetData = function () {
  14779. if (!this._facetDataEnabled) {
  14780. this._initFacetData();
  14781. }
  14782. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14783. var indices = this.getIndices();
  14784. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14785. var bInfo = this.getBoundingInfo();
  14786. if (!bInfo) {
  14787. return this;
  14788. }
  14789. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14790. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14791. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14792. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14793. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14794. this._subDiv.max = this._partitioningSubdivisions;
  14795. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14796. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14797. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14798. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14799. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14800. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14801. // set the parameters for ComputeNormals()
  14802. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14803. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14804. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14805. this._facetParameters.bInfo = bInfo;
  14806. this._facetParameters.bbSize = this._bbSize;
  14807. this._facetParameters.subDiv = this._subDiv;
  14808. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14809. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14810. return this;
  14811. };
  14812. /**
  14813. * Returns the facetLocalNormals array.
  14814. * The normals are expressed in the mesh local space.
  14815. */
  14816. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14817. if (!this._facetNormals) {
  14818. this.updateFacetData();
  14819. }
  14820. return this._facetNormals;
  14821. };
  14822. /**
  14823. * Returns the facetLocalPositions array.
  14824. * The facet positions are expressed in the mesh local space.
  14825. */
  14826. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14827. if (!this._facetPositions) {
  14828. this.updateFacetData();
  14829. }
  14830. return this._facetPositions;
  14831. };
  14832. /**
  14833. * Returns the facetLocalPartioning array.
  14834. */
  14835. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14836. if (!this._facetPartitioning) {
  14837. this.updateFacetData();
  14838. }
  14839. return this._facetPartitioning;
  14840. };
  14841. /**
  14842. * Returns the i-th facet position in the world system.
  14843. * This method allocates a new Vector3 per call.
  14844. */
  14845. AbstractMesh.prototype.getFacetPosition = function (i) {
  14846. var pos = BABYLON.Vector3.Zero();
  14847. this.getFacetPositionToRef(i, pos);
  14848. return pos;
  14849. };
  14850. /**
  14851. * Sets the reference Vector3 with the i-th facet position in the world system.
  14852. * Returns the AbstractMesh.
  14853. */
  14854. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14855. var localPos = (this.getFacetLocalPositions())[i];
  14856. var world = this.getWorldMatrix();
  14857. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14858. return this;
  14859. };
  14860. /**
  14861. * Returns the i-th facet normal in the world system.
  14862. * This method allocates a new Vector3 per call.
  14863. */
  14864. AbstractMesh.prototype.getFacetNormal = function (i) {
  14865. var norm = BABYLON.Vector3.Zero();
  14866. this.getFacetNormalToRef(i, norm);
  14867. return norm;
  14868. };
  14869. /**
  14870. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14871. * Returns the AbstractMesh.
  14872. */
  14873. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14874. var localNorm = (this.getFacetLocalNormals())[i];
  14875. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14876. return this;
  14877. };
  14878. /**
  14879. * 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).
  14880. */
  14881. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14882. var bInfo = this.getBoundingInfo();
  14883. if (!bInfo) {
  14884. return null;
  14885. }
  14886. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14887. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14888. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14889. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14890. return null;
  14891. }
  14892. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14893. };
  14894. /**
  14895. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14896. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14897. * 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.
  14898. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14899. * 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.
  14900. */
  14901. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14902. if (checkFace === void 0) { checkFace = false; }
  14903. if (facing === void 0) { facing = true; }
  14904. var world = this.getWorldMatrix();
  14905. var invMat = BABYLON.Tmp.Matrix[5];
  14906. world.invertToRef(invMat);
  14907. var invVect = BABYLON.Tmp.Vector3[8];
  14908. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14909. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14910. if (projected) {
  14911. // tranform the local computed projected vector to world coordinates
  14912. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14913. }
  14914. return closest;
  14915. };
  14916. /**
  14917. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14918. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14919. * 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.
  14920. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14921. * 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.
  14922. */
  14923. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14924. if (checkFace === void 0) { checkFace = false; }
  14925. if (facing === void 0) { facing = true; }
  14926. var closest = null;
  14927. var tmpx = 0.0;
  14928. var tmpy = 0.0;
  14929. var tmpz = 0.0;
  14930. var d = 0.0; // tmp dot facet normal * facet position
  14931. var t0 = 0.0;
  14932. var projx = 0.0;
  14933. var projy = 0.0;
  14934. var projz = 0.0;
  14935. // Get all the facets in the same partitioning block than (x, y, z)
  14936. var facetPositions = this.getFacetLocalPositions();
  14937. var facetNormals = this.getFacetLocalNormals();
  14938. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14939. if (!facetsInBlock) {
  14940. return null;
  14941. }
  14942. // Get the closest facet to (x, y, z)
  14943. var shortest = Number.MAX_VALUE; // init distance vars
  14944. var tmpDistance = shortest;
  14945. var fib; // current facet in the block
  14946. var norm; // current facet normal
  14947. var p0; // current facet barycenter position
  14948. // loop on all the facets in the current partitioning block
  14949. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14950. fib = facetsInBlock[idx];
  14951. norm = facetNormals[fib];
  14952. p0 = facetPositions[fib];
  14953. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14954. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14955. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14956. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14957. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14958. projx = x + norm.x * t0;
  14959. projy = y + norm.y * t0;
  14960. projz = z + norm.z * t0;
  14961. tmpx = projx - x;
  14962. tmpy = projy - y;
  14963. tmpz = projz - z;
  14964. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14965. if (tmpDistance < shortest) {
  14966. shortest = tmpDistance;
  14967. closest = fib;
  14968. if (projected) {
  14969. projected.x = projx;
  14970. projected.y = projy;
  14971. projected.z = projz;
  14972. }
  14973. }
  14974. }
  14975. }
  14976. return closest;
  14977. };
  14978. /**
  14979. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14980. */
  14981. AbstractMesh.prototype.getFacetDataParameters = function () {
  14982. return this._facetParameters;
  14983. };
  14984. /**
  14985. * Disables the feature FacetData and frees the related memory.
  14986. * Returns the AbstractMesh.
  14987. */
  14988. AbstractMesh.prototype.disableFacetData = function () {
  14989. if (this._facetDataEnabled) {
  14990. this._facetDataEnabled = false;
  14991. this._facetPositions = new Array();
  14992. ;
  14993. this._facetNormals = new Array();
  14994. ;
  14995. this._facetPartitioning = new Array();
  14996. ;
  14997. this._facetParameters = null;
  14998. }
  14999. return this;
  15000. };
  15001. /**
  15002. * Creates new normals data for the mesh.
  15003. * @param updatable.
  15004. */
  15005. AbstractMesh.prototype.createNormals = function (updatable) {
  15006. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15007. var indices = this.getIndices();
  15008. var normals;
  15009. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15010. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15011. }
  15012. else {
  15013. normals = [];
  15014. }
  15015. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15016. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15017. };
  15018. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15019. var engine = this.getEngine();
  15020. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15021. this._isOccluded = false;
  15022. return;
  15023. }
  15024. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15025. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15026. if (isOcclusionQueryAvailable) {
  15027. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15028. this._isOcclusionQueryInProgress = false;
  15029. this._occlusionInternalRetryCounter = 0;
  15030. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15031. }
  15032. else {
  15033. this._occlusionInternalRetryCounter++;
  15034. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15035. this._isOcclusionQueryInProgress = false;
  15036. this._occlusionInternalRetryCounter = 0;
  15037. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15038. // if strict continue the last state of the object.
  15039. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15040. }
  15041. else {
  15042. return;
  15043. }
  15044. }
  15045. }
  15046. var scene = this.getScene();
  15047. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15048. if (!this._occlusionQuery) {
  15049. this._occlusionQuery = engine.createQuery();
  15050. }
  15051. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15052. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15053. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15054. this._isOcclusionQueryInProgress = true;
  15055. };
  15056. // Statics
  15057. AbstractMesh._BILLBOARDMODE_NONE = 0;
  15058. AbstractMesh._BILLBOARDMODE_X = 1;
  15059. AbstractMesh._BILLBOARDMODE_Y = 2;
  15060. AbstractMesh._BILLBOARDMODE_Z = 4;
  15061. AbstractMesh._BILLBOARDMODE_ALL = 7;
  15062. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15063. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15064. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15065. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15066. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15067. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  15068. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15069. return AbstractMesh;
  15070. }(BABYLON.Node));
  15071. BABYLON.AbstractMesh = AbstractMesh;
  15072. })(BABYLON || (BABYLON = {}));
  15073. //# sourceMappingURL=babylon.abstractMesh.js.map
  15074. var BABYLON;
  15075. (function (BABYLON) {
  15076. var Light = /** @class */ (function (_super) {
  15077. __extends(Light, _super);
  15078. /**
  15079. * Creates a Light object in the scene.
  15080. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15081. */
  15082. function Light(name, scene) {
  15083. var _this = _super.call(this, name, scene) || this;
  15084. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15085. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15086. _this.intensity = 1.0;
  15087. _this.range = Number.MAX_VALUE;
  15088. /**
  15089. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15090. * of light.
  15091. */
  15092. _this._photometricScale = 1.0;
  15093. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15094. _this._radius = 0.00001;
  15095. _this.renderPriority = 0;
  15096. /**
  15097. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15098. * the current shadow generator.
  15099. */
  15100. _this.shadowEnabled = true;
  15101. _this._excludeWithLayerMask = 0;
  15102. _this._includeOnlyWithLayerMask = 0;
  15103. _this._lightmapMode = 0;
  15104. _this._excludedMeshesIds = new Array();
  15105. _this._includedOnlyMeshesIds = new Array();
  15106. _this.getScene().addLight(_this);
  15107. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15108. _this._buildUniformLayout();
  15109. _this.includedOnlyMeshes = new Array();
  15110. _this.excludedMeshes = new Array();
  15111. _this._resyncMeshes();
  15112. return _this;
  15113. }
  15114. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15115. /**
  15116. * If every light affecting the material is in this lightmapMode,
  15117. * material.lightmapTexture adds or multiplies
  15118. * (depends on material.useLightmapAsShadowmap)
  15119. * after every other light calculations.
  15120. */
  15121. get: function () {
  15122. return Light._LIGHTMAP_DEFAULT;
  15123. },
  15124. enumerable: true,
  15125. configurable: true
  15126. });
  15127. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15128. /**
  15129. * material.lightmapTexture as only diffuse lighting from this light
  15130. * adds pnly specular lighting from this light
  15131. * adds dynamic shadows
  15132. */
  15133. get: function () {
  15134. return Light._LIGHTMAP_SPECULAR;
  15135. },
  15136. enumerable: true,
  15137. configurable: true
  15138. });
  15139. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15140. /**
  15141. * material.lightmapTexture as only lighting
  15142. * no light calculation from this light
  15143. * only adds dynamic shadows from this light
  15144. */
  15145. get: function () {
  15146. return Light._LIGHTMAP_SHADOWSONLY;
  15147. },
  15148. enumerable: true,
  15149. configurable: true
  15150. });
  15151. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15152. /**
  15153. * Each light type uses the default quantity according to its type:
  15154. * point/spot lights use luminous intensity
  15155. * directional lights use illuminance
  15156. */
  15157. get: function () {
  15158. return Light._INTENSITYMODE_AUTOMATIC;
  15159. },
  15160. enumerable: true,
  15161. configurable: true
  15162. });
  15163. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15164. /**
  15165. * lumen (lm)
  15166. */
  15167. get: function () {
  15168. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15169. },
  15170. enumerable: true,
  15171. configurable: true
  15172. });
  15173. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15174. /**
  15175. * candela (lm/sr)
  15176. */
  15177. get: function () {
  15178. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15179. },
  15180. enumerable: true,
  15181. configurable: true
  15182. });
  15183. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15184. /**
  15185. * lux (lm/m^2)
  15186. */
  15187. get: function () {
  15188. return Light._INTENSITYMODE_ILLUMINANCE;
  15189. },
  15190. enumerable: true,
  15191. configurable: true
  15192. });
  15193. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15194. /**
  15195. * nit (cd/m^2)
  15196. */
  15197. get: function () {
  15198. return Light._INTENSITYMODE_LUMINANCE;
  15199. },
  15200. enumerable: true,
  15201. configurable: true
  15202. });
  15203. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15204. /**
  15205. * Light type const id of the point light.
  15206. */
  15207. get: function () {
  15208. return Light._LIGHTTYPEID_POINTLIGHT;
  15209. },
  15210. enumerable: true,
  15211. configurable: true
  15212. });
  15213. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15214. /**
  15215. * Light type const id of the directional light.
  15216. */
  15217. get: function () {
  15218. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15219. },
  15220. enumerable: true,
  15221. configurable: true
  15222. });
  15223. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15224. /**
  15225. * Light type const id of the spot light.
  15226. */
  15227. get: function () {
  15228. return Light._LIGHTTYPEID_SPOTLIGHT;
  15229. },
  15230. enumerable: true,
  15231. configurable: true
  15232. });
  15233. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15234. /**
  15235. * Light type const id of the hemispheric light.
  15236. */
  15237. get: function () {
  15238. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15239. },
  15240. enumerable: true,
  15241. configurable: true
  15242. });
  15243. Object.defineProperty(Light.prototype, "intensityMode", {
  15244. /**
  15245. * Gets the photometric scale used to interpret the intensity.
  15246. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15247. */
  15248. get: function () {
  15249. return this._intensityMode;
  15250. },
  15251. /**
  15252. * Sets the photometric scale used to interpret the intensity.
  15253. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15254. */
  15255. set: function (value) {
  15256. this._intensityMode = value;
  15257. this._computePhotometricScale();
  15258. },
  15259. enumerable: true,
  15260. configurable: true
  15261. });
  15262. ;
  15263. ;
  15264. Object.defineProperty(Light.prototype, "radius", {
  15265. /**
  15266. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15267. */
  15268. get: function () {
  15269. return this._radius;
  15270. },
  15271. /**
  15272. * sets the light radius used by PBR Materials to simulate soft area lights.
  15273. */
  15274. set: function (value) {
  15275. this._radius = value;
  15276. this._computePhotometricScale();
  15277. },
  15278. enumerable: true,
  15279. configurable: true
  15280. });
  15281. ;
  15282. ;
  15283. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15284. get: function () {
  15285. return this._includedOnlyMeshes;
  15286. },
  15287. set: function (value) {
  15288. this._includedOnlyMeshes = value;
  15289. this._hookArrayForIncludedOnly(value);
  15290. },
  15291. enumerable: true,
  15292. configurable: true
  15293. });
  15294. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15295. get: function () {
  15296. return this._excludedMeshes;
  15297. },
  15298. set: function (value) {
  15299. this._excludedMeshes = value;
  15300. this._hookArrayForExcluded(value);
  15301. },
  15302. enumerable: true,
  15303. configurable: true
  15304. });
  15305. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15306. get: function () {
  15307. return this._excludeWithLayerMask;
  15308. },
  15309. set: function (value) {
  15310. this._excludeWithLayerMask = value;
  15311. this._resyncMeshes();
  15312. },
  15313. enumerable: true,
  15314. configurable: true
  15315. });
  15316. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15317. get: function () {
  15318. return this._includeOnlyWithLayerMask;
  15319. },
  15320. set: function (value) {
  15321. this._includeOnlyWithLayerMask = value;
  15322. this._resyncMeshes();
  15323. },
  15324. enumerable: true,
  15325. configurable: true
  15326. });
  15327. Object.defineProperty(Light.prototype, "lightmapMode", {
  15328. get: function () {
  15329. return this._lightmapMode;
  15330. },
  15331. set: function (value) {
  15332. if (this._lightmapMode === value) {
  15333. return;
  15334. }
  15335. this._lightmapMode = value;
  15336. this._markMeshesAsLightDirty();
  15337. },
  15338. enumerable: true,
  15339. configurable: true
  15340. });
  15341. Light.prototype._buildUniformLayout = function () {
  15342. // Overridden
  15343. };
  15344. /**
  15345. * Returns the string "Light".
  15346. */
  15347. Light.prototype.getClassName = function () {
  15348. return "Light";
  15349. };
  15350. /**
  15351. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15352. */
  15353. Light.prototype.toString = function (fullDetails) {
  15354. var ret = "Name: " + this.name;
  15355. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15356. if (this.animations) {
  15357. for (var i = 0; i < this.animations.length; i++) {
  15358. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15359. }
  15360. }
  15361. if (fullDetails) {
  15362. }
  15363. return ret;
  15364. };
  15365. /**
  15366. * Set the enabled state of this node.
  15367. * @param {boolean} value - the new enabled state
  15368. * @see isEnabled
  15369. */
  15370. Light.prototype.setEnabled = function (value) {
  15371. _super.prototype.setEnabled.call(this, value);
  15372. this._resyncMeshes();
  15373. };
  15374. /**
  15375. * Returns the Light associated shadow generator.
  15376. */
  15377. Light.prototype.getShadowGenerator = function () {
  15378. return this._shadowGenerator;
  15379. };
  15380. /**
  15381. * Returns a Vector3, the absolute light position in the World.
  15382. */
  15383. Light.prototype.getAbsolutePosition = function () {
  15384. return BABYLON.Vector3.Zero();
  15385. };
  15386. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15387. };
  15388. Light.prototype._getWorldMatrix = function () {
  15389. return BABYLON.Matrix.Identity();
  15390. };
  15391. /**
  15392. * Boolean : True if the light will affect the passed mesh.
  15393. */
  15394. Light.prototype.canAffectMesh = function (mesh) {
  15395. if (!mesh) {
  15396. return true;
  15397. }
  15398. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15399. return false;
  15400. }
  15401. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15402. return false;
  15403. }
  15404. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15405. return false;
  15406. }
  15407. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15408. return false;
  15409. }
  15410. return true;
  15411. };
  15412. /**
  15413. * Returns the light World matrix.
  15414. */
  15415. Light.prototype.getWorldMatrix = function () {
  15416. this._currentRenderId = this.getScene().getRenderId();
  15417. var worldMatrix = this._getWorldMatrix();
  15418. if (this.parent && this.parent.getWorldMatrix) {
  15419. if (!this._parentedWorldMatrix) {
  15420. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15421. }
  15422. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15423. this._markSyncedWithParent();
  15424. return this._parentedWorldMatrix;
  15425. }
  15426. return worldMatrix;
  15427. };
  15428. /**
  15429. * Sort function to order lights for rendering.
  15430. * @param a First Light object to compare to second.
  15431. * @param b Second Light object to compare first.
  15432. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15433. */
  15434. Light.compareLightsPriority = function (a, b) {
  15435. //shadow-casting lights have priority over non-shadow-casting lights
  15436. //the renderPrioirty is a secondary sort criterion
  15437. if (a.shadowEnabled !== b.shadowEnabled) {
  15438. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15439. }
  15440. return b.renderPriority - a.renderPriority;
  15441. };
  15442. /**
  15443. * Disposes the light.
  15444. */
  15445. Light.prototype.dispose = function () {
  15446. if (this._shadowGenerator) {
  15447. this._shadowGenerator.dispose();
  15448. this._shadowGenerator = null;
  15449. }
  15450. // Animations
  15451. this.getScene().stopAnimation(this);
  15452. // Remove from meshes
  15453. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15454. var mesh = _a[_i];
  15455. mesh._removeLightSource(this);
  15456. }
  15457. this._uniformBuffer.dispose();
  15458. // Remove from scene
  15459. this.getScene().removeLight(this);
  15460. _super.prototype.dispose.call(this);
  15461. };
  15462. /**
  15463. * Returns the light type ID (integer).
  15464. */
  15465. Light.prototype.getTypeID = function () {
  15466. return 0;
  15467. };
  15468. /**
  15469. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15470. */
  15471. Light.prototype.getScaledIntensity = function () {
  15472. return this._photometricScale * this.intensity;
  15473. };
  15474. /**
  15475. * Returns a new Light object, named "name", from the current one.
  15476. */
  15477. Light.prototype.clone = function (name) {
  15478. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15479. if (!constructor) {
  15480. return null;
  15481. }
  15482. return BABYLON.SerializationHelper.Clone(constructor, this);
  15483. };
  15484. /**
  15485. * Serializes the current light into a Serialization object.
  15486. * Returns the serialized object.
  15487. */
  15488. Light.prototype.serialize = function () {
  15489. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15490. // Type
  15491. serializationObject.type = this.getTypeID();
  15492. // Parent
  15493. if (this.parent) {
  15494. serializationObject.parentId = this.parent.id;
  15495. }
  15496. // Inclusion / exclusions
  15497. if (this.excludedMeshes.length > 0) {
  15498. serializationObject.excludedMeshesIds = [];
  15499. this.excludedMeshes.forEach(function (mesh) {
  15500. serializationObject.excludedMeshesIds.push(mesh.id);
  15501. });
  15502. }
  15503. if (this.includedOnlyMeshes.length > 0) {
  15504. serializationObject.includedOnlyMeshesIds = [];
  15505. this.includedOnlyMeshes.forEach(function (mesh) {
  15506. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15507. });
  15508. }
  15509. // Animations
  15510. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15511. serializationObject.ranges = this.serializeAnimationRanges();
  15512. return serializationObject;
  15513. };
  15514. /**
  15515. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15516. * This new light is named "name" and added to the passed scene.
  15517. */
  15518. Light.GetConstructorFromName = function (type, name, scene) {
  15519. switch (type) {
  15520. case 0:
  15521. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15522. case 1:
  15523. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15524. case 2:
  15525. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15526. case 3:
  15527. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15528. }
  15529. return null;
  15530. };
  15531. /**
  15532. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15533. */
  15534. Light.Parse = function (parsedLight, scene) {
  15535. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15536. if (!constructor) {
  15537. return null;
  15538. }
  15539. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15540. // Inclusion / exclusions
  15541. if (parsedLight.excludedMeshesIds) {
  15542. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15543. }
  15544. if (parsedLight.includedOnlyMeshesIds) {
  15545. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15546. }
  15547. // Parent
  15548. if (parsedLight.parentId) {
  15549. light._waitingParentId = parsedLight.parentId;
  15550. }
  15551. // Animations
  15552. if (parsedLight.animations) {
  15553. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15554. var parsedAnimation = parsedLight.animations[animationIndex];
  15555. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15556. }
  15557. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15558. }
  15559. if (parsedLight.autoAnimate) {
  15560. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15561. }
  15562. return light;
  15563. };
  15564. Light.prototype._hookArrayForExcluded = function (array) {
  15565. var _this = this;
  15566. var oldPush = array.push;
  15567. array.push = function () {
  15568. var items = [];
  15569. for (var _i = 0; _i < arguments.length; _i++) {
  15570. items[_i] = arguments[_i];
  15571. }
  15572. var result = oldPush.apply(array, items);
  15573. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15574. var item = items_1[_a];
  15575. item._resyncLighSource(_this);
  15576. }
  15577. return result;
  15578. };
  15579. var oldSplice = array.splice;
  15580. array.splice = function (index, deleteCount) {
  15581. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15582. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15583. var item = deleted_1[_i];
  15584. item._resyncLighSource(_this);
  15585. }
  15586. return deleted;
  15587. };
  15588. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15589. var item = array_1[_i];
  15590. item._resyncLighSource(this);
  15591. }
  15592. };
  15593. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15594. var _this = this;
  15595. var oldPush = array.push;
  15596. array.push = function () {
  15597. var items = [];
  15598. for (var _i = 0; _i < arguments.length; _i++) {
  15599. items[_i] = arguments[_i];
  15600. }
  15601. var result = oldPush.apply(array, items);
  15602. _this._resyncMeshes();
  15603. return result;
  15604. };
  15605. var oldSplice = array.splice;
  15606. array.splice = function (index, deleteCount) {
  15607. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15608. _this._resyncMeshes();
  15609. return deleted;
  15610. };
  15611. this._resyncMeshes();
  15612. };
  15613. Light.prototype._resyncMeshes = function () {
  15614. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15615. var mesh = _a[_i];
  15616. mesh._resyncLighSource(this);
  15617. }
  15618. };
  15619. Light.prototype._markMeshesAsLightDirty = function () {
  15620. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15621. var mesh = _a[_i];
  15622. if (mesh._lightSources.indexOf(this) !== -1) {
  15623. mesh._markSubMeshesAsLightDirty();
  15624. }
  15625. }
  15626. };
  15627. /**
  15628. * Recomputes the cached photometric scale if needed.
  15629. */
  15630. Light.prototype._computePhotometricScale = function () {
  15631. this._photometricScale = this._getPhotometricScale();
  15632. this.getScene().resetCachedMaterial();
  15633. };
  15634. /**
  15635. * Returns the Photometric Scale according to the light type and intensity mode.
  15636. */
  15637. Light.prototype._getPhotometricScale = function () {
  15638. var photometricScale = 0.0;
  15639. var lightTypeID = this.getTypeID();
  15640. //get photometric mode
  15641. var photometricMode = this.intensityMode;
  15642. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15643. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15644. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15645. }
  15646. else {
  15647. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15648. }
  15649. }
  15650. //compute photometric scale
  15651. switch (lightTypeID) {
  15652. case Light.LIGHTTYPEID_POINTLIGHT:
  15653. case Light.LIGHTTYPEID_SPOTLIGHT:
  15654. switch (photometricMode) {
  15655. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15656. photometricScale = 1.0 / (4.0 * Math.PI);
  15657. break;
  15658. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15659. photometricScale = 1.0;
  15660. break;
  15661. case Light.INTENSITYMODE_LUMINANCE:
  15662. photometricScale = this.radius * this.radius;
  15663. break;
  15664. }
  15665. break;
  15666. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15667. switch (photometricMode) {
  15668. case Light.INTENSITYMODE_ILLUMINANCE:
  15669. photometricScale = 1.0;
  15670. break;
  15671. case Light.INTENSITYMODE_LUMINANCE:
  15672. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15673. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15674. var apexAngleRadians = this.radius;
  15675. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15676. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15677. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15678. photometricScale = solidAngle;
  15679. break;
  15680. }
  15681. break;
  15682. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15683. // No fall off in hemisperic light.
  15684. photometricScale = 1.0;
  15685. break;
  15686. }
  15687. return photometricScale;
  15688. };
  15689. Light.prototype._reorderLightsInScene = function () {
  15690. var scene = this.getScene();
  15691. if (this._renderPriority != 0) {
  15692. scene.requireLightSorting = true;
  15693. }
  15694. this.getScene().sortLightsByPriority();
  15695. };
  15696. //lightmapMode Consts
  15697. Light._LIGHTMAP_DEFAULT = 0;
  15698. Light._LIGHTMAP_SPECULAR = 1;
  15699. Light._LIGHTMAP_SHADOWSONLY = 2;
  15700. // Intensity Mode Consts
  15701. Light._INTENSITYMODE_AUTOMATIC = 0;
  15702. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15703. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15704. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15705. Light._INTENSITYMODE_LUMINANCE = 4;
  15706. // Light types ids const.
  15707. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15708. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15709. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15710. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15711. __decorate([
  15712. BABYLON.serializeAsColor3()
  15713. ], Light.prototype, "diffuse", void 0);
  15714. __decorate([
  15715. BABYLON.serializeAsColor3()
  15716. ], Light.prototype, "specular", void 0);
  15717. __decorate([
  15718. BABYLON.serialize()
  15719. ], Light.prototype, "intensity", void 0);
  15720. __decorate([
  15721. BABYLON.serialize()
  15722. ], Light.prototype, "range", void 0);
  15723. __decorate([
  15724. BABYLON.serialize()
  15725. ], Light.prototype, "intensityMode", null);
  15726. __decorate([
  15727. BABYLON.serialize()
  15728. ], Light.prototype, "radius", null);
  15729. __decorate([
  15730. BABYLON.serialize()
  15731. ], Light.prototype, "_renderPriority", void 0);
  15732. __decorate([
  15733. BABYLON.expandToProperty("_reorderLightsInScene")
  15734. ], Light.prototype, "renderPriority", void 0);
  15735. __decorate([
  15736. BABYLON.serialize()
  15737. ], Light.prototype, "shadowEnabled", void 0);
  15738. __decorate([
  15739. BABYLON.serialize("excludeWithLayerMask")
  15740. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15741. __decorate([
  15742. BABYLON.serialize("includeOnlyWithLayerMask")
  15743. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15744. __decorate([
  15745. BABYLON.serialize("lightmapMode")
  15746. ], Light.prototype, "_lightmapMode", void 0);
  15747. return Light;
  15748. }(BABYLON.Node));
  15749. BABYLON.Light = Light;
  15750. })(BABYLON || (BABYLON = {}));
  15751. //# sourceMappingURL=babylon.light.js.map
  15752. var BABYLON;
  15753. (function (BABYLON) {
  15754. var Camera = /** @class */ (function (_super) {
  15755. __extends(Camera, _super);
  15756. function Camera(name, position, scene) {
  15757. var _this = _super.call(this, name, scene) || this;
  15758. _this.upVector = BABYLON.Vector3.Up();
  15759. _this.orthoLeft = null;
  15760. _this.orthoRight = null;
  15761. _this.orthoBottom = null;
  15762. _this.orthoTop = null;
  15763. _this.fov = 0.8;
  15764. _this.minZ = 1;
  15765. _this.maxZ = 10000.0;
  15766. _this.inertia = 0.9;
  15767. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15768. _this.isIntermediate = false;
  15769. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15770. _this.layerMask = 0x0FFFFFFF;
  15771. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15772. // Camera rig members
  15773. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15774. _this._rigCameras = new Array();
  15775. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15776. _this._skipRendering = false;
  15777. _this.customRenderTargets = new Array();
  15778. // Observables
  15779. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15780. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15781. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15782. _this.onRestoreStateObservable = new BABYLON.Observable();
  15783. // Cache
  15784. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15785. _this._projectionMatrix = new BABYLON.Matrix();
  15786. _this._doNotComputeProjectionMatrix = false;
  15787. _this._postProcesses = new Array();
  15788. _this._transformMatrix = BABYLON.Matrix.Zero();
  15789. _this._activeMeshes = new BABYLON.SmartArray(256);
  15790. _this._globalPosition = BABYLON.Vector3.Zero();
  15791. _this._refreshFrustumPlanes = true;
  15792. _this.getScene().addCamera(_this);
  15793. if (!_this.getScene().activeCamera) {
  15794. _this.getScene().activeCamera = _this;
  15795. }
  15796. _this.position = position;
  15797. return _this;
  15798. }
  15799. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15800. get: function () {
  15801. return Camera._PERSPECTIVE_CAMERA;
  15802. },
  15803. enumerable: true,
  15804. configurable: true
  15805. });
  15806. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15807. get: function () {
  15808. return Camera._ORTHOGRAPHIC_CAMERA;
  15809. },
  15810. enumerable: true,
  15811. configurable: true
  15812. });
  15813. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15814. get: function () {
  15815. return Camera._FOVMODE_VERTICAL_FIXED;
  15816. },
  15817. enumerable: true,
  15818. configurable: true
  15819. });
  15820. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15821. get: function () {
  15822. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15823. },
  15824. enumerable: true,
  15825. configurable: true
  15826. });
  15827. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15828. get: function () {
  15829. return Camera._RIG_MODE_NONE;
  15830. },
  15831. enumerable: true,
  15832. configurable: true
  15833. });
  15834. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15835. get: function () {
  15836. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15837. },
  15838. enumerable: true,
  15839. configurable: true
  15840. });
  15841. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15842. get: function () {
  15843. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15844. },
  15845. enumerable: true,
  15846. configurable: true
  15847. });
  15848. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15849. get: function () {
  15850. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15851. },
  15852. enumerable: true,
  15853. configurable: true
  15854. });
  15855. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15856. get: function () {
  15857. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15858. },
  15859. enumerable: true,
  15860. configurable: true
  15861. });
  15862. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15863. get: function () {
  15864. return Camera._RIG_MODE_VR;
  15865. },
  15866. enumerable: true,
  15867. configurable: true
  15868. });
  15869. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15870. get: function () {
  15871. return Camera._RIG_MODE_WEBVR;
  15872. },
  15873. enumerable: true,
  15874. configurable: true
  15875. });
  15876. /**
  15877. * Store current camera state (fov, position, etc..)
  15878. */
  15879. Camera.prototype.storeState = function () {
  15880. this._stateStored = true;
  15881. this._storedFov = this.fov;
  15882. return this;
  15883. };
  15884. /**
  15885. * Restores the camera state values if it has been stored. You must call storeState() first
  15886. */
  15887. Camera.prototype._restoreStateValues = function () {
  15888. if (!this._stateStored) {
  15889. return false;
  15890. }
  15891. this.fov = this._storedFov;
  15892. return true;
  15893. };
  15894. /**
  15895. * Restored camera state. You must call storeState() first
  15896. */
  15897. Camera.prototype.restoreState = function () {
  15898. if (this._restoreStateValues()) {
  15899. this.onRestoreStateObservable.notifyObservers(this);
  15900. return true;
  15901. }
  15902. return false;
  15903. };
  15904. Camera.prototype.getClassName = function () {
  15905. return "Camera";
  15906. };
  15907. /**
  15908. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15909. */
  15910. Camera.prototype.toString = function (fullDetails) {
  15911. var ret = "Name: " + this.name;
  15912. ret += ", type: " + this.getClassName();
  15913. if (this.animations) {
  15914. for (var i = 0; i < this.animations.length; i++) {
  15915. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15916. }
  15917. }
  15918. if (fullDetails) {
  15919. }
  15920. return ret;
  15921. };
  15922. Object.defineProperty(Camera.prototype, "globalPosition", {
  15923. get: function () {
  15924. return this._globalPosition;
  15925. },
  15926. enumerable: true,
  15927. configurable: true
  15928. });
  15929. Camera.prototype.getActiveMeshes = function () {
  15930. return this._activeMeshes;
  15931. };
  15932. Camera.prototype.isActiveMesh = function (mesh) {
  15933. return (this._activeMeshes.indexOf(mesh) !== -1);
  15934. };
  15935. //Cache
  15936. Camera.prototype._initCache = function () {
  15937. _super.prototype._initCache.call(this);
  15938. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15939. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15940. this._cache.mode = undefined;
  15941. this._cache.minZ = undefined;
  15942. this._cache.maxZ = undefined;
  15943. this._cache.fov = undefined;
  15944. this._cache.fovMode = undefined;
  15945. this._cache.aspectRatio = undefined;
  15946. this._cache.orthoLeft = undefined;
  15947. this._cache.orthoRight = undefined;
  15948. this._cache.orthoBottom = undefined;
  15949. this._cache.orthoTop = undefined;
  15950. this._cache.renderWidth = undefined;
  15951. this._cache.renderHeight = undefined;
  15952. };
  15953. Camera.prototype._updateCache = function (ignoreParentClass) {
  15954. if (!ignoreParentClass) {
  15955. _super.prototype._updateCache.call(this);
  15956. }
  15957. this._cache.position.copyFrom(this.position);
  15958. this._cache.upVector.copyFrom(this.upVector);
  15959. };
  15960. // Synchronized
  15961. Camera.prototype._isSynchronized = function () {
  15962. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15963. };
  15964. Camera.prototype._isSynchronizedViewMatrix = function () {
  15965. if (!_super.prototype._isSynchronized.call(this))
  15966. return false;
  15967. return this._cache.position.equals(this.position)
  15968. && this._cache.upVector.equals(this.upVector)
  15969. && this.isSynchronizedWithParent();
  15970. };
  15971. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15972. var check = this._cache.mode === this.mode
  15973. && this._cache.minZ === this.minZ
  15974. && this._cache.maxZ === this.maxZ;
  15975. if (!check) {
  15976. return false;
  15977. }
  15978. var engine = this.getEngine();
  15979. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15980. check = this._cache.fov === this.fov
  15981. && this._cache.fovMode === this.fovMode
  15982. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15983. }
  15984. else {
  15985. check = this._cache.orthoLeft === this.orthoLeft
  15986. && this._cache.orthoRight === this.orthoRight
  15987. && this._cache.orthoBottom === this.orthoBottom
  15988. && this._cache.orthoTop === this.orthoTop
  15989. && this._cache.renderWidth === engine.getRenderWidth()
  15990. && this._cache.renderHeight === engine.getRenderHeight();
  15991. }
  15992. return check;
  15993. };
  15994. // Controls
  15995. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15996. };
  15997. Camera.prototype.detachControl = function (element) {
  15998. };
  15999. Camera.prototype.update = function () {
  16000. this._checkInputs();
  16001. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16002. this._updateRigCameras();
  16003. }
  16004. };
  16005. Camera.prototype._checkInputs = function () {
  16006. this.onAfterCheckInputsObservable.notifyObservers(this);
  16007. };
  16008. Object.defineProperty(Camera.prototype, "rigCameras", {
  16009. get: function () {
  16010. return this._rigCameras;
  16011. },
  16012. enumerable: true,
  16013. configurable: true
  16014. });
  16015. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16016. get: function () {
  16017. return this._rigPostProcess;
  16018. },
  16019. enumerable: true,
  16020. configurable: true
  16021. });
  16022. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16023. // invalidate framebuffer
  16024. if (this._postProcesses.length > 0) {
  16025. this._postProcesses[0].markTextureDirty();
  16026. }
  16027. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16028. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16029. var cam = this._rigCameras[i];
  16030. var rigPostProcess = cam._rigPostProcess;
  16031. // for VR rig, there does not have to be a post process
  16032. if (rigPostProcess) {
  16033. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16034. if (isPass) {
  16035. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16036. cam.isIntermediate = this._postProcesses.length === 0;
  16037. }
  16038. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16039. rigPostProcess.markTextureDirty();
  16040. }
  16041. else {
  16042. cam._postProcesses = this._postProcesses.slice(0);
  16043. }
  16044. }
  16045. };
  16046. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16047. if (insertAt === void 0) { insertAt = null; }
  16048. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16049. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16050. return 0;
  16051. }
  16052. if (insertAt == null || insertAt < 0) {
  16053. this._postProcesses.push(postProcess);
  16054. }
  16055. else {
  16056. this._postProcesses.splice(insertAt, 0, postProcess);
  16057. }
  16058. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16059. return this._postProcesses.indexOf(postProcess);
  16060. };
  16061. Camera.prototype.detachPostProcess = function (postProcess) {
  16062. var idx = this._postProcesses.indexOf(postProcess);
  16063. if (idx !== -1) {
  16064. this._postProcesses.splice(idx, 1);
  16065. }
  16066. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16067. };
  16068. Camera.prototype.getWorldMatrix = function () {
  16069. if (!this._worldMatrix) {
  16070. this._worldMatrix = BABYLON.Matrix.Identity();
  16071. }
  16072. var viewMatrix = this.getViewMatrix();
  16073. viewMatrix.invertToRef(this._worldMatrix);
  16074. return this._worldMatrix;
  16075. };
  16076. Camera.prototype._getViewMatrix = function () {
  16077. return BABYLON.Matrix.Identity();
  16078. };
  16079. Camera.prototype.getViewMatrix = function (force) {
  16080. if (!force && this._isSynchronizedViewMatrix()) {
  16081. return this._computedViewMatrix;
  16082. }
  16083. this.updateCache();
  16084. this._computedViewMatrix = this._getViewMatrix();
  16085. this._currentRenderId = this.getScene().getRenderId();
  16086. this._refreshFrustumPlanes = true;
  16087. if (!this.parent || !this.parent.getWorldMatrix) {
  16088. this._globalPosition.copyFrom(this.position);
  16089. }
  16090. else {
  16091. if (!this._worldMatrix) {
  16092. this._worldMatrix = BABYLON.Matrix.Identity();
  16093. }
  16094. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16095. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16096. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16097. this._computedViewMatrix.invert();
  16098. this._markSyncedWithParent();
  16099. }
  16100. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16101. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16102. }
  16103. this.onViewMatrixChangedObservable.notifyObservers(this);
  16104. return this._computedViewMatrix;
  16105. };
  16106. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16107. this._doNotComputeProjectionMatrix = true;
  16108. if (projection !== undefined) {
  16109. this._projectionMatrix = projection;
  16110. }
  16111. };
  16112. ;
  16113. Camera.prototype.unfreezeProjectionMatrix = function () {
  16114. this._doNotComputeProjectionMatrix = false;
  16115. };
  16116. ;
  16117. Camera.prototype.getProjectionMatrix = function (force) {
  16118. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16119. return this._projectionMatrix;
  16120. }
  16121. // Cache
  16122. this._cache.mode = this.mode;
  16123. this._cache.minZ = this.minZ;
  16124. this._cache.maxZ = this.maxZ;
  16125. // Matrix
  16126. this._refreshFrustumPlanes = true;
  16127. var engine = this.getEngine();
  16128. var scene = this.getScene();
  16129. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16130. this._cache.fov = this.fov;
  16131. this._cache.fovMode = this.fovMode;
  16132. this._cache.aspectRatio = engine.getAspectRatio(this);
  16133. if (this.minZ <= 0) {
  16134. this.minZ = 0.1;
  16135. }
  16136. if (scene.useRightHandedSystem) {
  16137. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16138. }
  16139. else {
  16140. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16141. }
  16142. }
  16143. else {
  16144. var halfWidth = engine.getRenderWidth() / 2.0;
  16145. var halfHeight = engine.getRenderHeight() / 2.0;
  16146. if (scene.useRightHandedSystem) {
  16147. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16148. }
  16149. else {
  16150. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16151. }
  16152. this._cache.orthoLeft = this.orthoLeft;
  16153. this._cache.orthoRight = this.orthoRight;
  16154. this._cache.orthoBottom = this.orthoBottom;
  16155. this._cache.orthoTop = this.orthoTop;
  16156. this._cache.renderWidth = engine.getRenderWidth();
  16157. this._cache.renderHeight = engine.getRenderHeight();
  16158. }
  16159. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16160. return this._projectionMatrix;
  16161. };
  16162. Camera.prototype.getTranformationMatrix = function () {
  16163. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16164. return this._transformMatrix;
  16165. };
  16166. Camera.prototype.updateFrustumPlanes = function () {
  16167. if (!this._refreshFrustumPlanes) {
  16168. return;
  16169. }
  16170. this.getTranformationMatrix();
  16171. if (!this._frustumPlanes) {
  16172. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16173. }
  16174. else {
  16175. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16176. }
  16177. this._refreshFrustumPlanes = false;
  16178. };
  16179. Camera.prototype.isInFrustum = function (target) {
  16180. this.updateFrustumPlanes();
  16181. return target.isInFrustum(this._frustumPlanes);
  16182. };
  16183. Camera.prototype.isCompletelyInFrustum = function (target) {
  16184. this.updateFrustumPlanes();
  16185. return target.isCompletelyInFrustum(this._frustumPlanes);
  16186. };
  16187. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16188. if (length === void 0) { length = 100; }
  16189. if (!transform) {
  16190. transform = this.getWorldMatrix();
  16191. }
  16192. if (!origin) {
  16193. origin = this.position;
  16194. }
  16195. var forward = new BABYLON.Vector3(0, 0, 1);
  16196. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16197. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16198. return new BABYLON.Ray(origin, direction, length);
  16199. };
  16200. Camera.prototype.dispose = function () {
  16201. // Observables
  16202. this.onViewMatrixChangedObservable.clear();
  16203. this.onProjectionMatrixChangedObservable.clear();
  16204. this.onAfterCheckInputsObservable.clear();
  16205. this.onRestoreStateObservable.clear();
  16206. // Inputs
  16207. if (this.inputs) {
  16208. this.inputs.clear();
  16209. }
  16210. // Animations
  16211. this.getScene().stopAnimation(this);
  16212. // Remove from scene
  16213. this.getScene().removeCamera(this);
  16214. while (this._rigCameras.length > 0) {
  16215. var camera = this._rigCameras.pop();
  16216. if (camera) {
  16217. camera.dispose();
  16218. }
  16219. }
  16220. // Postprocesses
  16221. if (this._rigPostProcess) {
  16222. this._rigPostProcess.dispose(this);
  16223. this._rigPostProcess = null;
  16224. this._postProcesses = [];
  16225. }
  16226. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16227. this._rigPostProcess = null;
  16228. this._postProcesses = [];
  16229. }
  16230. else {
  16231. var i = this._postProcesses.length;
  16232. while (--i >= 0) {
  16233. this._postProcesses[i].dispose(this);
  16234. }
  16235. }
  16236. // Render targets
  16237. var i = this.customRenderTargets.length;
  16238. while (--i >= 0) {
  16239. this.customRenderTargets[i].dispose();
  16240. }
  16241. this.customRenderTargets = [];
  16242. // Active Meshes
  16243. this._activeMeshes.dispose();
  16244. _super.prototype.dispose.call(this);
  16245. };
  16246. Object.defineProperty(Camera.prototype, "leftCamera", {
  16247. // ---- Camera rigs section ----
  16248. get: function () {
  16249. if (this._rigCameras.length < 1) {
  16250. return null;
  16251. }
  16252. return this._rigCameras[0];
  16253. },
  16254. enumerable: true,
  16255. configurable: true
  16256. });
  16257. Object.defineProperty(Camera.prototype, "rightCamera", {
  16258. get: function () {
  16259. if (this._rigCameras.length < 2) {
  16260. return null;
  16261. }
  16262. return this._rigCameras[1];
  16263. },
  16264. enumerable: true,
  16265. configurable: true
  16266. });
  16267. Camera.prototype.getLeftTarget = function () {
  16268. if (this._rigCameras.length < 1) {
  16269. return null;
  16270. }
  16271. return this._rigCameras[0].getTarget();
  16272. };
  16273. Camera.prototype.getRightTarget = function () {
  16274. if (this._rigCameras.length < 2) {
  16275. return null;
  16276. }
  16277. return this._rigCameras[1].getTarget();
  16278. };
  16279. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16280. if (this.cameraRigMode === mode) {
  16281. return;
  16282. }
  16283. while (this._rigCameras.length > 0) {
  16284. var camera = this._rigCameras.pop();
  16285. if (camera) {
  16286. camera.dispose();
  16287. }
  16288. }
  16289. this.cameraRigMode = mode;
  16290. this._cameraRigParams = {};
  16291. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16292. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16293. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16294. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16295. // create the rig cameras, unless none
  16296. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16297. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16298. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16299. if (leftCamera && rightCamera) {
  16300. this._rigCameras.push(leftCamera);
  16301. this._rigCameras.push(rightCamera);
  16302. }
  16303. }
  16304. switch (this.cameraRigMode) {
  16305. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16306. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16307. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16308. break;
  16309. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16310. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16311. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16312. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16313. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16314. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16315. break;
  16316. case Camera.RIG_MODE_VR:
  16317. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16318. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16319. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16320. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16321. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16322. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16323. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16324. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16325. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16326. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16327. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16328. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16329. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16330. if (metrics.compensateDistortion) {
  16331. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16332. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16333. }
  16334. break;
  16335. case Camera.RIG_MODE_WEBVR:
  16336. if (rigParams.vrDisplay) {
  16337. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16338. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16339. //Left eye
  16340. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16341. this._rigCameras[0].setCameraRigParameter("left", true);
  16342. //leaving this for future reference
  16343. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16344. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16345. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16346. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16347. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16348. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16349. this._rigCameras[0].parent = this;
  16350. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16351. //Right eye
  16352. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16353. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16354. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16355. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16356. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16357. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16358. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16359. this._rigCameras[1].parent = this;
  16360. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16361. if (Camera.UseAlternateWebVRRendering) {
  16362. this._rigCameras[1]._skipRendering = true;
  16363. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16364. }
  16365. }
  16366. break;
  16367. }
  16368. this._cascadePostProcessesToRigCams();
  16369. this.update();
  16370. };
  16371. Camera.prototype._getVRProjectionMatrix = function () {
  16372. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16373. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16374. return this._projectionMatrix;
  16375. };
  16376. Camera.prototype._updateCameraRotationMatrix = function () {
  16377. //Here for WebVR
  16378. };
  16379. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16380. //Here for WebVR
  16381. };
  16382. /**
  16383. * This function MUST be overwritten by the different WebVR cameras available.
  16384. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16385. */
  16386. Camera.prototype._getWebVRProjectionMatrix = function () {
  16387. return BABYLON.Matrix.Identity();
  16388. };
  16389. /**
  16390. * This function MUST be overwritten by the different WebVR cameras available.
  16391. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16392. */
  16393. Camera.prototype._getWebVRViewMatrix = function () {
  16394. return BABYLON.Matrix.Identity();
  16395. };
  16396. Camera.prototype.setCameraRigParameter = function (name, value) {
  16397. if (!this._cameraRigParams) {
  16398. this._cameraRigParams = {};
  16399. }
  16400. this._cameraRigParams[name] = value;
  16401. //provisionnally:
  16402. if (name === "interaxialDistance") {
  16403. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16404. }
  16405. };
  16406. /**
  16407. * needs to be overridden by children so sub has required properties to be copied
  16408. */
  16409. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16410. return null;
  16411. };
  16412. /**
  16413. * May need to be overridden by children
  16414. */
  16415. Camera.prototype._updateRigCameras = function () {
  16416. for (var i = 0; i < this._rigCameras.length; i++) {
  16417. this._rigCameras[i].minZ = this.minZ;
  16418. this._rigCameras[i].maxZ = this.maxZ;
  16419. this._rigCameras[i].fov = this.fov;
  16420. }
  16421. // only update viewport when ANAGLYPH
  16422. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16423. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16424. }
  16425. };
  16426. Camera.prototype._setupInputs = function () {
  16427. };
  16428. Camera.prototype.serialize = function () {
  16429. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16430. // Type
  16431. serializationObject.type = this.getClassName();
  16432. // Parent
  16433. if (this.parent) {
  16434. serializationObject.parentId = this.parent.id;
  16435. }
  16436. if (this.inputs) {
  16437. this.inputs.serialize(serializationObject);
  16438. }
  16439. // Animations
  16440. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16441. serializationObject.ranges = this.serializeAnimationRanges();
  16442. return serializationObject;
  16443. };
  16444. Camera.prototype.clone = function (name) {
  16445. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16446. };
  16447. Camera.prototype.getDirection = function (localAxis) {
  16448. var result = BABYLON.Vector3.Zero();
  16449. this.getDirectionToRef(localAxis, result);
  16450. return result;
  16451. };
  16452. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16453. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16454. };
  16455. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16456. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16457. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16458. switch (type) {
  16459. case "ArcRotateCamera":
  16460. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16461. case "DeviceOrientationCamera":
  16462. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16463. case "FollowCamera":
  16464. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16465. case "ArcFollowCamera":
  16466. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16467. case "GamepadCamera":
  16468. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16469. case "TouchCamera":
  16470. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16471. case "VirtualJoysticksCamera":
  16472. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16473. case "WebVRFreeCamera":
  16474. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16475. case "WebVRGamepadCamera":
  16476. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16477. case "VRDeviceOrientationFreeCamera":
  16478. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16479. case "VRDeviceOrientationGamepadCamera":
  16480. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16481. case "AnaglyphArcRotateCamera":
  16482. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16483. case "AnaglyphFreeCamera":
  16484. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16485. case "AnaglyphGamepadCamera":
  16486. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16487. case "AnaglyphUniversalCamera":
  16488. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16489. case "StereoscopicArcRotateCamera":
  16490. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16491. case "StereoscopicFreeCamera":
  16492. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16493. case "StereoscopicGamepadCamera":
  16494. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16495. case "StereoscopicUniversalCamera":
  16496. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16497. case "FreeCamera":// Forcing Universal here
  16498. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16499. default:// Universal Camera is the default value
  16500. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16501. }
  16502. };
  16503. Camera.Parse = function (parsedCamera, scene) {
  16504. var type = parsedCamera.type;
  16505. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16506. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16507. // Parent
  16508. if (parsedCamera.parentId) {
  16509. camera._waitingParentId = parsedCamera.parentId;
  16510. }
  16511. //If camera has an input manager, let it parse inputs settings
  16512. if (camera.inputs) {
  16513. camera.inputs.parse(parsedCamera);
  16514. camera._setupInputs();
  16515. }
  16516. if (camera.setPosition) {
  16517. camera.position.copyFromFloats(0, 0, 0);
  16518. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16519. }
  16520. // Target
  16521. if (parsedCamera.target) {
  16522. if (camera.setTarget) {
  16523. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16524. }
  16525. }
  16526. // Apply 3d rig, when found
  16527. if (parsedCamera.cameraRigMode) {
  16528. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16529. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16530. }
  16531. // Animations
  16532. if (parsedCamera.animations) {
  16533. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16534. var parsedAnimation = parsedCamera.animations[animationIndex];
  16535. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16536. }
  16537. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16538. }
  16539. if (parsedCamera.autoAnimate) {
  16540. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16541. }
  16542. return camera;
  16543. };
  16544. // Statics
  16545. Camera._PERSPECTIVE_CAMERA = 0;
  16546. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16547. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16548. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16549. Camera._RIG_MODE_NONE = 0;
  16550. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16551. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16552. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16553. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16554. Camera._RIG_MODE_VR = 20;
  16555. Camera._RIG_MODE_WEBVR = 21;
  16556. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16557. Camera.UseAlternateWebVRRendering = false;
  16558. __decorate([
  16559. BABYLON.serializeAsVector3()
  16560. ], Camera.prototype, "position", void 0);
  16561. __decorate([
  16562. BABYLON.serializeAsVector3()
  16563. ], Camera.prototype, "upVector", void 0);
  16564. __decorate([
  16565. BABYLON.serialize()
  16566. ], Camera.prototype, "orthoLeft", void 0);
  16567. __decorate([
  16568. BABYLON.serialize()
  16569. ], Camera.prototype, "orthoRight", void 0);
  16570. __decorate([
  16571. BABYLON.serialize()
  16572. ], Camera.prototype, "orthoBottom", void 0);
  16573. __decorate([
  16574. BABYLON.serialize()
  16575. ], Camera.prototype, "orthoTop", void 0);
  16576. __decorate([
  16577. BABYLON.serialize()
  16578. ], Camera.prototype, "fov", void 0);
  16579. __decorate([
  16580. BABYLON.serialize()
  16581. ], Camera.prototype, "minZ", void 0);
  16582. __decorate([
  16583. BABYLON.serialize()
  16584. ], Camera.prototype, "maxZ", void 0);
  16585. __decorate([
  16586. BABYLON.serialize()
  16587. ], Camera.prototype, "inertia", void 0);
  16588. __decorate([
  16589. BABYLON.serialize()
  16590. ], Camera.prototype, "mode", void 0);
  16591. __decorate([
  16592. BABYLON.serialize()
  16593. ], Camera.prototype, "layerMask", void 0);
  16594. __decorate([
  16595. BABYLON.serialize()
  16596. ], Camera.prototype, "fovMode", void 0);
  16597. __decorate([
  16598. BABYLON.serialize()
  16599. ], Camera.prototype, "cameraRigMode", void 0);
  16600. __decorate([
  16601. BABYLON.serialize()
  16602. ], Camera.prototype, "interaxialDistance", void 0);
  16603. __decorate([
  16604. BABYLON.serialize()
  16605. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16606. return Camera;
  16607. }(BABYLON.Node));
  16608. BABYLON.Camera = Camera;
  16609. })(BABYLON || (BABYLON = {}));
  16610. //# sourceMappingURL=babylon.camera.js.map
  16611. var BABYLON;
  16612. (function (BABYLON) {
  16613. var RenderingManager = /** @class */ (function () {
  16614. function RenderingManager(scene) {
  16615. this._renderingGroups = new Array();
  16616. this._autoClearDepthStencil = {};
  16617. this._customOpaqueSortCompareFn = {};
  16618. this._customAlphaTestSortCompareFn = {};
  16619. this._customTransparentSortCompareFn = {};
  16620. this._renderinGroupInfo = null;
  16621. this._scene = scene;
  16622. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16623. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16624. }
  16625. }
  16626. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16627. if (depth === void 0) { depth = true; }
  16628. if (stencil === void 0) { stencil = true; }
  16629. if (this._depthStencilBufferAlreadyCleaned) {
  16630. return;
  16631. }
  16632. this._scene.getEngine().clear(null, false, depth, stencil);
  16633. this._depthStencilBufferAlreadyCleaned = true;
  16634. };
  16635. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16636. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16637. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16638. var info = null;
  16639. if (observable) {
  16640. if (!this._renderinGroupInfo) {
  16641. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16642. }
  16643. info = this._renderinGroupInfo;
  16644. info.scene = this._scene;
  16645. info.camera = this._scene.activeCamera;
  16646. }
  16647. // Dispatch sprites
  16648. if (renderSprites) {
  16649. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16650. var manager = this._scene.spriteManagers[index];
  16651. this.dispatchSprites(manager);
  16652. }
  16653. }
  16654. // Render
  16655. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16656. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16657. var renderingGroup = this._renderingGroups[index];
  16658. if (!renderingGroup && !observable)
  16659. continue;
  16660. this._currentIndex = index;
  16661. var renderingGroupMask = 0;
  16662. // Fire PRECLEAR stage
  16663. if (observable && info) {
  16664. renderingGroupMask = Math.pow(2, index);
  16665. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16666. info.renderingGroupId = index;
  16667. observable.notifyObservers(info, renderingGroupMask);
  16668. }
  16669. // Clear depth/stencil if needed
  16670. if (RenderingManager.AUTOCLEAR) {
  16671. var autoClear = this._autoClearDepthStencil[index];
  16672. if (autoClear && autoClear.autoClear) {
  16673. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16674. }
  16675. }
  16676. if (observable && info) {
  16677. // Fire PREOPAQUE stage
  16678. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16679. observable.notifyObservers(info, renderingGroupMask);
  16680. // Fire PRETRANSPARENT stage
  16681. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16682. observable.notifyObservers(info, renderingGroupMask);
  16683. }
  16684. if (renderingGroup)
  16685. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16686. // Fire POSTTRANSPARENT stage
  16687. if (observable && info) {
  16688. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16689. observable.notifyObservers(info, renderingGroupMask);
  16690. }
  16691. }
  16692. };
  16693. RenderingManager.prototype.reset = function () {
  16694. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16695. var renderingGroup = this._renderingGroups[index];
  16696. if (renderingGroup) {
  16697. renderingGroup.prepare();
  16698. }
  16699. }
  16700. };
  16701. RenderingManager.prototype.dispose = function () {
  16702. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16703. var renderingGroup = this._renderingGroups[index];
  16704. if (renderingGroup) {
  16705. renderingGroup.dispose();
  16706. }
  16707. }
  16708. this._renderingGroups.length = 0;
  16709. };
  16710. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16711. if (!this._renderingGroups[renderingGroupId]) {
  16712. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16713. }
  16714. };
  16715. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16716. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16717. this._prepareRenderingGroup(renderingGroupId);
  16718. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16719. };
  16720. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16721. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16722. this._prepareRenderingGroup(renderingGroupId);
  16723. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16724. };
  16725. RenderingManager.prototype.dispatch = function (subMesh) {
  16726. var mesh = subMesh.getMesh();
  16727. var renderingGroupId = mesh.renderingGroupId || 0;
  16728. this._prepareRenderingGroup(renderingGroupId);
  16729. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16730. };
  16731. /**
  16732. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16733. * This allowed control for front to back rendering or reversly depending of the special needs.
  16734. *
  16735. * @param renderingGroupId The rendering group id corresponding to its index
  16736. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16737. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16738. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16739. */
  16740. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16741. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16742. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16743. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16744. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16745. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16746. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16747. if (this._renderingGroups[renderingGroupId]) {
  16748. var group = this._renderingGroups[renderingGroupId];
  16749. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16750. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16751. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16752. }
  16753. };
  16754. /**
  16755. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16756. *
  16757. * @param renderingGroupId The rendering group id corresponding to its index
  16758. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16759. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16760. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16761. */
  16762. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16763. if (depth === void 0) { depth = true; }
  16764. if (stencil === void 0) { stencil = true; }
  16765. this._autoClearDepthStencil[renderingGroupId] = {
  16766. autoClear: autoClearDepthStencil,
  16767. depth: depth,
  16768. stencil: stencil
  16769. };
  16770. };
  16771. /**
  16772. * The max id used for rendering groups (not included)
  16773. */
  16774. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16775. /**
  16776. * The min id used for rendering groups (included)
  16777. */
  16778. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16779. /**
  16780. * Used to globally prevent autoclearing scenes.
  16781. */
  16782. RenderingManager.AUTOCLEAR = true;
  16783. return RenderingManager;
  16784. }());
  16785. BABYLON.RenderingManager = RenderingManager;
  16786. })(BABYLON || (BABYLON = {}));
  16787. //# sourceMappingURL=babylon.renderingManager.js.map
  16788. var BABYLON;
  16789. (function (BABYLON) {
  16790. var RenderingGroup = /** @class */ (function () {
  16791. /**
  16792. * Creates a new rendering group.
  16793. * @param index The rendering group index
  16794. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16795. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16796. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16797. */
  16798. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16799. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16800. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16801. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16802. this.index = index;
  16803. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16804. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16805. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16806. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16807. this._particleSystems = new BABYLON.SmartArray(256);
  16808. this._spriteManagers = new BABYLON.SmartArray(256);
  16809. this._edgesRenderers = new BABYLON.SmartArray(16);
  16810. this._scene = scene;
  16811. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16812. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16813. this.transparentSortCompareFn = transparentSortCompareFn;
  16814. }
  16815. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16816. /**
  16817. * Set the opaque sort comparison function.
  16818. * If null the sub meshes will be render in the order they were created
  16819. */
  16820. set: function (value) {
  16821. this._opaqueSortCompareFn = value;
  16822. if (value) {
  16823. this._renderOpaque = this.renderOpaqueSorted;
  16824. }
  16825. else {
  16826. this._renderOpaque = RenderingGroup.renderUnsorted;
  16827. }
  16828. },
  16829. enumerable: true,
  16830. configurable: true
  16831. });
  16832. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16833. /**
  16834. * Set the alpha test sort comparison function.
  16835. * If null the sub meshes will be render in the order they were created
  16836. */
  16837. set: function (value) {
  16838. this._alphaTestSortCompareFn = value;
  16839. if (value) {
  16840. this._renderAlphaTest = this.renderAlphaTestSorted;
  16841. }
  16842. else {
  16843. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16844. }
  16845. },
  16846. enumerable: true,
  16847. configurable: true
  16848. });
  16849. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16850. /**
  16851. * Set the transparent sort comparison function.
  16852. * If null the sub meshes will be render in the order they were created
  16853. */
  16854. set: function (value) {
  16855. if (value) {
  16856. this._transparentSortCompareFn = value;
  16857. }
  16858. else {
  16859. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16860. }
  16861. this._renderTransparent = this.renderTransparentSorted;
  16862. },
  16863. enumerable: true,
  16864. configurable: true
  16865. });
  16866. /**
  16867. * Render all the sub meshes contained in the group.
  16868. * @param customRenderFunction Used to override the default render behaviour of the group.
  16869. * @returns true if rendered some submeshes.
  16870. */
  16871. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16872. if (customRenderFunction) {
  16873. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16874. return;
  16875. }
  16876. var engine = this._scene.getEngine();
  16877. // Depth only
  16878. if (this._depthOnlySubMeshes.length !== 0) {
  16879. engine.setAlphaTesting(true);
  16880. engine.setColorWrite(false);
  16881. this._renderAlphaTest(this._depthOnlySubMeshes);
  16882. engine.setAlphaTesting(false);
  16883. engine.setColorWrite(true);
  16884. }
  16885. // Opaque
  16886. if (this._opaqueSubMeshes.length !== 0) {
  16887. this._renderOpaque(this._opaqueSubMeshes);
  16888. }
  16889. // Alpha test
  16890. if (this._alphaTestSubMeshes.length !== 0) {
  16891. engine.setAlphaTesting(true);
  16892. this._renderAlphaTest(this._alphaTestSubMeshes);
  16893. engine.setAlphaTesting(false);
  16894. }
  16895. var stencilState = engine.getStencilBuffer();
  16896. engine.setStencilBuffer(false);
  16897. // Sprites
  16898. if (renderSprites) {
  16899. this._renderSprites();
  16900. }
  16901. // Particles
  16902. if (renderParticles) {
  16903. this._renderParticles(activeMeshes);
  16904. }
  16905. if (this.onBeforeTransparentRendering) {
  16906. this.onBeforeTransparentRendering();
  16907. }
  16908. // Transparent
  16909. if (this._transparentSubMeshes.length !== 0) {
  16910. this._renderTransparent(this._transparentSubMeshes);
  16911. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16912. }
  16913. // Set back stencil to false in case it changes before the edge renderer.
  16914. engine.setStencilBuffer(false);
  16915. // Edges
  16916. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16917. this._edgesRenderers.data[edgesRendererIndex].render();
  16918. }
  16919. // Restore Stencil state.
  16920. engine.setStencilBuffer(stencilState);
  16921. };
  16922. /**
  16923. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16924. * @param subMeshes The submeshes to render
  16925. */
  16926. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16927. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  16928. };
  16929. /**
  16930. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16931. * @param subMeshes The submeshes to render
  16932. */
  16933. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16934. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  16935. };
  16936. /**
  16937. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16938. * @param subMeshes The submeshes to render
  16939. */
  16940. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16941. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  16942. };
  16943. /**
  16944. * Renders the submeshes in a specified order.
  16945. * @param subMeshes The submeshes to sort before render
  16946. * @param sortCompareFn The comparison function use to sort
  16947. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16948. * @param transparent Specifies to activate blending if true
  16949. */
  16950. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  16951. var subIndex = 0;
  16952. var subMesh;
  16953. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  16954. for (; subIndex < subMeshes.length; subIndex++) {
  16955. subMesh = subMeshes.data[subIndex];
  16956. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16957. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16958. }
  16959. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16960. if (sortCompareFn) {
  16961. sortedArray.sort(sortCompareFn);
  16962. }
  16963. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16964. subMesh = sortedArray[subIndex];
  16965. if (transparent) {
  16966. var material = subMesh.getMaterial();
  16967. if (material && material.needDepthPrePass) {
  16968. var engine = material.getScene().getEngine();
  16969. engine.setColorWrite(false);
  16970. engine.setAlphaTesting(true);
  16971. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16972. subMesh.render(false);
  16973. engine.setAlphaTesting(false);
  16974. engine.setColorWrite(true);
  16975. }
  16976. }
  16977. subMesh.render(transparent);
  16978. }
  16979. };
  16980. /**
  16981. * Renders the submeshes in the order they were dispatched (no sort applied).
  16982. * @param subMeshes The submeshes to render
  16983. */
  16984. RenderingGroup.renderUnsorted = function (subMeshes) {
  16985. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16986. var submesh = subMeshes.data[subIndex];
  16987. submesh.render(false);
  16988. }
  16989. };
  16990. /**
  16991. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16992. * are rendered back to front if in the same alpha index.
  16993. *
  16994. * @param a The first submesh
  16995. * @param b The second submesh
  16996. * @returns The result of the comparison
  16997. */
  16998. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16999. // Alpha index first
  17000. if (a._alphaIndex > b._alphaIndex) {
  17001. return 1;
  17002. }
  17003. if (a._alphaIndex < b._alphaIndex) {
  17004. return -1;
  17005. }
  17006. // Then distance to camera
  17007. return RenderingGroup.backToFrontSortCompare(a, b);
  17008. };
  17009. /**
  17010. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17011. * are rendered back to front.
  17012. *
  17013. * @param a The first submesh
  17014. * @param b The second submesh
  17015. * @returns The result of the comparison
  17016. */
  17017. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17018. // Then distance to camera
  17019. if (a._distanceToCamera < b._distanceToCamera) {
  17020. return 1;
  17021. }
  17022. if (a._distanceToCamera > b._distanceToCamera) {
  17023. return -1;
  17024. }
  17025. return 0;
  17026. };
  17027. /**
  17028. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17029. * are rendered front to back (prevent overdraw).
  17030. *
  17031. * @param a The first submesh
  17032. * @param b The second submesh
  17033. * @returns The result of the comparison
  17034. */
  17035. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17036. // Then distance to camera
  17037. if (a._distanceToCamera < b._distanceToCamera) {
  17038. return -1;
  17039. }
  17040. if (a._distanceToCamera > b._distanceToCamera) {
  17041. return 1;
  17042. }
  17043. return 0;
  17044. };
  17045. /**
  17046. * Resets the different lists of submeshes to prepare a new frame.
  17047. */
  17048. RenderingGroup.prototype.prepare = function () {
  17049. this._opaqueSubMeshes.reset();
  17050. this._transparentSubMeshes.reset();
  17051. this._alphaTestSubMeshes.reset();
  17052. this._depthOnlySubMeshes.reset();
  17053. this._particleSystems.reset();
  17054. this._spriteManagers.reset();
  17055. this._edgesRenderers.reset();
  17056. };
  17057. RenderingGroup.prototype.dispose = function () {
  17058. this._opaqueSubMeshes.dispose();
  17059. this._transparentSubMeshes.dispose();
  17060. this._alphaTestSubMeshes.dispose();
  17061. this._depthOnlySubMeshes.dispose();
  17062. this._particleSystems.dispose();
  17063. this._spriteManagers.dispose();
  17064. this._edgesRenderers.dispose();
  17065. };
  17066. /**
  17067. * Inserts the submesh in its correct queue depending on its material.
  17068. * @param subMesh The submesh to dispatch
  17069. */
  17070. RenderingGroup.prototype.dispatch = function (subMesh) {
  17071. var material = subMesh.getMaterial();
  17072. var mesh = subMesh.getMesh();
  17073. if (!material) {
  17074. return;
  17075. }
  17076. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  17077. this._transparentSubMeshes.push(subMesh);
  17078. }
  17079. else if (material.needAlphaTesting()) {
  17080. if (material.needDepthPrePass) {
  17081. this._depthOnlySubMeshes.push(subMesh);
  17082. }
  17083. this._alphaTestSubMeshes.push(subMesh);
  17084. }
  17085. else {
  17086. if (material.needDepthPrePass) {
  17087. this._depthOnlySubMeshes.push(subMesh);
  17088. }
  17089. this._opaqueSubMeshes.push(subMesh); // Opaque
  17090. }
  17091. if (mesh._edgesRenderer) {
  17092. this._edgesRenderers.push(mesh._edgesRenderer);
  17093. }
  17094. };
  17095. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17096. this._spriteManagers.push(spriteManager);
  17097. };
  17098. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17099. this._particleSystems.push(particleSystem);
  17100. };
  17101. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17102. if (this._particleSystems.length === 0) {
  17103. return;
  17104. }
  17105. // Particles
  17106. var activeCamera = this._scene.activeCamera;
  17107. this._scene._particlesDuration.beginMonitoring();
  17108. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17109. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17110. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17111. continue;
  17112. }
  17113. var emitter = particleSystem.emitter;
  17114. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17115. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17116. }
  17117. }
  17118. this._scene._particlesDuration.endMonitoring(false);
  17119. };
  17120. RenderingGroup.prototype._renderSprites = function () {
  17121. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17122. return;
  17123. }
  17124. // Sprites
  17125. var activeCamera = this._scene.activeCamera;
  17126. this._scene._spritesDuration.beginMonitoring();
  17127. for (var id = 0; id < this._spriteManagers.length; id++) {
  17128. var spriteManager = this._spriteManagers.data[id];
  17129. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17130. spriteManager.render();
  17131. }
  17132. }
  17133. this._scene._spritesDuration.endMonitoring(false);
  17134. };
  17135. return RenderingGroup;
  17136. }());
  17137. BABYLON.RenderingGroup = RenderingGroup;
  17138. })(BABYLON || (BABYLON = {}));
  17139. //# sourceMappingURL=babylon.renderingGroup.js.map
  17140. var BABYLON;
  17141. (function (BABYLON) {
  17142. var ClickInfo = /** @class */ (function () {
  17143. function ClickInfo() {
  17144. this._singleClick = false;
  17145. this._doubleClick = false;
  17146. this._hasSwiped = false;
  17147. this._ignore = false;
  17148. }
  17149. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17150. get: function () {
  17151. return this._singleClick;
  17152. },
  17153. set: function (b) {
  17154. this._singleClick = b;
  17155. },
  17156. enumerable: true,
  17157. configurable: true
  17158. });
  17159. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17160. get: function () {
  17161. return this._doubleClick;
  17162. },
  17163. set: function (b) {
  17164. this._doubleClick = b;
  17165. },
  17166. enumerable: true,
  17167. configurable: true
  17168. });
  17169. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17170. get: function () {
  17171. return this._hasSwiped;
  17172. },
  17173. set: function (b) {
  17174. this._hasSwiped = b;
  17175. },
  17176. enumerable: true,
  17177. configurable: true
  17178. });
  17179. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17180. get: function () {
  17181. return this._ignore;
  17182. },
  17183. set: function (b) {
  17184. this._ignore = b;
  17185. },
  17186. enumerable: true,
  17187. configurable: true
  17188. });
  17189. return ClickInfo;
  17190. }());
  17191. /**
  17192. * This class is used by the onRenderingGroupObservable
  17193. */
  17194. var RenderingGroupInfo = /** @class */ (function () {
  17195. function RenderingGroupInfo() {
  17196. }
  17197. /**
  17198. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17199. * This stage will be fired no matter what
  17200. */
  17201. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17202. /**
  17203. * Called before opaque object are rendered.
  17204. * This stage will be fired only if there's 3D Opaque content to render
  17205. */
  17206. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17207. /**
  17208. * Called after the opaque objects are rendered and before the transparent ones
  17209. * This stage will be fired only if there's 3D transparent content to render
  17210. */
  17211. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17212. /**
  17213. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17214. * This stage will be fired no matter what
  17215. */
  17216. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17217. return RenderingGroupInfo;
  17218. }());
  17219. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17220. /**
  17221. * Represents a scene to be rendered by the engine.
  17222. * @see http://doc.babylonjs.com/page.php?p=21911
  17223. */
  17224. var Scene = /** @class */ (function () {
  17225. /**
  17226. * @constructor
  17227. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17228. */
  17229. function Scene(engine) {
  17230. // Members
  17231. this.autoClear = true;
  17232. this.autoClearDepthAndStencil = true;
  17233. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17234. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17235. this.forceWireframe = false;
  17236. this._forcePointsCloud = false;
  17237. this.forceShowBoundingBoxes = false;
  17238. this.animationsEnabled = true;
  17239. this.constantlyUpdateMeshUnderPointer = false;
  17240. this.hoverCursor = "pointer";
  17241. this.defaultCursor = "";
  17242. /**
  17243. * This is used to call preventDefault() on pointer down
  17244. * in order to block unwanted artifacts like system double clicks
  17245. */
  17246. this.preventDefaultOnPointerDown = true;
  17247. // Metadata
  17248. this.metadata = null;
  17249. /**
  17250. * An event triggered when the scene is disposed.
  17251. * @type {BABYLON.Observable}
  17252. */
  17253. this.onDisposeObservable = new BABYLON.Observable();
  17254. /**
  17255. * An event triggered before rendering the scene
  17256. * @type {BABYLON.Observable}
  17257. */
  17258. this.onBeforeRenderObservable = new BABYLON.Observable();
  17259. /**
  17260. * An event triggered after rendering the scene
  17261. * @type {BABYLON.Observable}
  17262. */
  17263. this.onAfterRenderObservable = new BABYLON.Observable();
  17264. /**
  17265. * An event triggered when the scene is ready
  17266. * @type {BABYLON.Observable}
  17267. */
  17268. this.onReadyObservable = new BABYLON.Observable();
  17269. /**
  17270. * An event triggered before rendering a camera
  17271. * @type {BABYLON.Observable}
  17272. */
  17273. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17274. /**
  17275. * An event triggered after rendering a camera
  17276. * @type {BABYLON.Observable}
  17277. */
  17278. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17279. /**
  17280. * An event triggered when active meshes evaluation is about to start
  17281. * @type {BABYLON.Observable}
  17282. */
  17283. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17284. /**
  17285. * An event triggered when active meshes evaluation is done
  17286. * @type {BABYLON.Observable}
  17287. */
  17288. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17289. /**
  17290. * An event triggered when a camera is created
  17291. * @type {BABYLON.Observable}
  17292. */
  17293. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17294. /**
  17295. * An event triggered when a camera is removed
  17296. * @type {BABYLON.Observable}
  17297. */
  17298. this.onCameraRemovedObservable = new BABYLON.Observable();
  17299. /**
  17300. * An event triggered when a light is created
  17301. * @type {BABYLON.Observable}
  17302. */
  17303. this.onNewLightAddedObservable = new BABYLON.Observable();
  17304. /**
  17305. * An event triggered when a light is removed
  17306. * @type {BABYLON.Observable}
  17307. */
  17308. this.onLightRemovedObservable = new BABYLON.Observable();
  17309. /**
  17310. * An event triggered when a geometry is created
  17311. * @type {BABYLON.Observable}
  17312. */
  17313. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17314. /**
  17315. * An event triggered when a geometry is removed
  17316. * @type {BABYLON.Observable}
  17317. */
  17318. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17319. /**
  17320. * An event triggered when a mesh is created
  17321. * @type {BABYLON.Observable}
  17322. */
  17323. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17324. /**
  17325. * An event triggered when a mesh is removed
  17326. * @type {BABYLON.Observable}
  17327. */
  17328. this.onMeshRemovedObservable = new BABYLON.Observable();
  17329. /**
  17330. * An event triggered when render targets are about to be rendered
  17331. * Can happen multiple times per frame.
  17332. * @type {BABYLON.Observable}
  17333. */
  17334. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17335. /**
  17336. * An event triggered when render targets were rendered.
  17337. * Can happen multiple times per frame.
  17338. * @type {BABYLON.Observable}
  17339. */
  17340. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17341. /**
  17342. * An event triggered before calculating deterministic simulation step
  17343. * @type {BABYLON.Observable}
  17344. */
  17345. this.onBeforeStepObservable = new BABYLON.Observable();
  17346. /**
  17347. * An event triggered after calculating deterministic simulation step
  17348. * @type {BABYLON.Observable}
  17349. */
  17350. this.onAfterStepObservable = new BABYLON.Observable();
  17351. /**
  17352. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17353. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17354. * 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)
  17355. */
  17356. this.onRenderingGroupObservable = new BABYLON.Observable();
  17357. // Animations
  17358. this.animations = [];
  17359. /**
  17360. * 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).
  17361. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17362. */
  17363. this.onPrePointerObservable = new BABYLON.Observable();
  17364. /**
  17365. * Observable event triggered each time an input event is received from the rendering canvas
  17366. */
  17367. this.onPointerObservable = new BABYLON.Observable();
  17368. this._meshPickProceed = false;
  17369. this._previousHasSwiped = false;
  17370. this._currentPickResult = null;
  17371. this._previousPickResult = null;
  17372. this._totalPointersPressed = 0;
  17373. this._doubleClickOccured = false;
  17374. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17375. this.cameraToUseForPointers = null;
  17376. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17377. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17378. this._startingPointerTime = 0;
  17379. this._previousStartingPointerTime = 0;
  17380. // Deterministic lockstep
  17381. this._timeAccumulator = 0;
  17382. this._currentStepId = 0;
  17383. this._currentInternalStep = 0;
  17384. // Keyboard
  17385. /**
  17386. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17387. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17388. */
  17389. this.onPreKeyboardObservable = new BABYLON.Observable();
  17390. /**
  17391. * Observable event triggered each time an keyboard event is received from the hosting window
  17392. */
  17393. this.onKeyboardObservable = new BABYLON.Observable();
  17394. // Coordinate system
  17395. /**
  17396. * use right-handed coordinate system on this scene.
  17397. * @type {boolean}
  17398. */
  17399. this._useRightHandedSystem = false;
  17400. // Fog
  17401. this._fogEnabled = true;
  17402. this._fogMode = Scene.FOGMODE_NONE;
  17403. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17404. this.fogDensity = 0.1;
  17405. this.fogStart = 0;
  17406. this.fogEnd = 1000.0;
  17407. // Lights
  17408. /**
  17409. * is shadow enabled on this scene.
  17410. * @type {boolean}
  17411. */
  17412. this._shadowsEnabled = true;
  17413. /**
  17414. * is light enabled on this scene.
  17415. * @type {boolean}
  17416. */
  17417. this._lightsEnabled = true;
  17418. /**
  17419. * All of the lights added to this scene.
  17420. * @see BABYLON.Light
  17421. * @type {BABYLON.Light[]}
  17422. */
  17423. this.lights = new Array();
  17424. // Cameras
  17425. /** All of the cameras added to this scene. */
  17426. this.cameras = new Array();
  17427. /** All of the active cameras added to this scene. */
  17428. this.activeCameras = new Array();
  17429. // Meshes
  17430. /**
  17431. * All of the (abstract) meshes added to this scene.
  17432. * @see BABYLON.AbstractMesh
  17433. * @type {BABYLON.AbstractMesh[]}
  17434. */
  17435. this.meshes = new Array();
  17436. // Geometries
  17437. this._geometries = new Array();
  17438. this.materials = new Array();
  17439. this.multiMaterials = new Array();
  17440. // Textures
  17441. this._texturesEnabled = true;
  17442. this.textures = new Array();
  17443. // Particles
  17444. this.particlesEnabled = true;
  17445. this.particleSystems = new Array();
  17446. // Sprites
  17447. this.spritesEnabled = true;
  17448. this.spriteManagers = new Array();
  17449. // Layers
  17450. this.layers = new Array();
  17451. this.highlightLayers = new Array();
  17452. // Skeletons
  17453. this._skeletonsEnabled = true;
  17454. this.skeletons = new Array();
  17455. // Morph targets
  17456. this.morphTargetManagers = new Array();
  17457. // Lens flares
  17458. this.lensFlaresEnabled = true;
  17459. this.lensFlareSystems = new Array();
  17460. // Collisions
  17461. this.collisionsEnabled = true;
  17462. /** Defines the gravity applied to this scene */
  17463. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17464. // Postprocesses
  17465. this.postProcesses = new Array();
  17466. this.postProcessesEnabled = true;
  17467. // Customs render targets
  17468. this.renderTargetsEnabled = true;
  17469. this.dumpNextRenderTargets = false;
  17470. this.customRenderTargets = new Array();
  17471. // Imported meshes
  17472. this.importedMeshesFiles = new Array();
  17473. // Probes
  17474. this.probesEnabled = true;
  17475. this.reflectionProbes = new Array();
  17476. this._actionManagers = new Array();
  17477. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17478. // Procedural textures
  17479. this.proceduralTexturesEnabled = true;
  17480. this._proceduralTextures = new Array();
  17481. this.soundTracks = new Array();
  17482. this._audioEnabled = true;
  17483. this._headphone = false;
  17484. // Performance counters
  17485. this._totalVertices = new BABYLON.PerfCounter();
  17486. this._activeIndices = new BABYLON.PerfCounter();
  17487. this._activeParticles = new BABYLON.PerfCounter();
  17488. this._interFrameDuration = new BABYLON.PerfCounter();
  17489. this._particlesDuration = new BABYLON.PerfCounter();
  17490. this._renderDuration = new BABYLON.PerfCounter();
  17491. this._spritesDuration = new BABYLON.PerfCounter();
  17492. this._activeBones = new BABYLON.PerfCounter();
  17493. this._animationTime = 0;
  17494. this.animationTimeScale = 1;
  17495. this._renderId = 0;
  17496. this._executeWhenReadyTimeoutId = -1;
  17497. this._intermediateRendering = false;
  17498. this._viewUpdateFlag = -1;
  17499. this._projectionUpdateFlag = -1;
  17500. this._alternateViewUpdateFlag = -1;
  17501. this._alternateProjectionUpdateFlag = -1;
  17502. this._toBeDisposed = new BABYLON.SmartArray(256);
  17503. this._pendingData = new Array();
  17504. this._isDisposed = false;
  17505. this._activeMeshes = new BABYLON.SmartArray(256);
  17506. this._processedMaterials = new BABYLON.SmartArray(256);
  17507. this._renderTargets = new BABYLON.SmartArray(256);
  17508. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17509. this._activeSkeletons = new BABYLON.SmartArray(32);
  17510. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17511. this._activeAnimatables = new Array();
  17512. this._transformMatrix = BABYLON.Matrix.Zero();
  17513. this._useAlternateCameraConfiguration = false;
  17514. this._alternateRendering = false;
  17515. this.requireLightSorting = false;
  17516. this._activeMeshesFrozen = false;
  17517. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17518. this._engine.scenes.push(this);
  17519. this._uid = null;
  17520. this._renderingManager = new BABYLON.RenderingManager(this);
  17521. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17522. if (BABYLON.OutlineRenderer) {
  17523. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17524. }
  17525. if (BABYLON.Tools.IsWindowObjectExist()) {
  17526. this.attachControl();
  17527. }
  17528. //simplification queue
  17529. if (BABYLON.SimplificationQueue) {
  17530. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17531. }
  17532. //collision coordinator initialization. For now legacy per default.
  17533. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17534. // Uniform Buffer
  17535. this._createUbo();
  17536. // Default Image processing definition.
  17537. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17538. }
  17539. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17540. /** The fog is deactivated */
  17541. get: function () {
  17542. return Scene._FOGMODE_NONE;
  17543. },
  17544. enumerable: true,
  17545. configurable: true
  17546. });
  17547. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17548. /** The fog density is following an exponential function */
  17549. get: function () {
  17550. return Scene._FOGMODE_EXP;
  17551. },
  17552. enumerable: true,
  17553. configurable: true
  17554. });
  17555. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17556. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17557. get: function () {
  17558. return Scene._FOGMODE_EXP2;
  17559. },
  17560. enumerable: true,
  17561. configurable: true
  17562. });
  17563. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17564. /** The fog density is following a linear function. */
  17565. get: function () {
  17566. return Scene._FOGMODE_LINEAR;
  17567. },
  17568. enumerable: true,
  17569. configurable: true
  17570. });
  17571. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17572. /**
  17573. * Texture used in all pbr material as the reflection texture.
  17574. * As in the majority of the scene they are the same (exception for multi room and so on),
  17575. * this is easier to reference from here than from all the materials.
  17576. */
  17577. get: function () {
  17578. return this._environmentTexture;
  17579. },
  17580. /**
  17581. * Texture used in all pbr material as the reflection texture.
  17582. * As in the majority of the scene they are the same (exception for multi room and so on),
  17583. * this is easier to set here than in all the materials.
  17584. */
  17585. set: function (value) {
  17586. if (this._environmentTexture === value) {
  17587. return;
  17588. }
  17589. this._environmentTexture = value;
  17590. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17591. },
  17592. enumerable: true,
  17593. configurable: true
  17594. });
  17595. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17596. /**
  17597. * Default image processing configuration used either in the rendering
  17598. * Forward main pass or through the imageProcessingPostProcess if present.
  17599. * As in the majority of the scene they are the same (exception for multi camera),
  17600. * this is easier to reference from here than from all the materials and post process.
  17601. *
  17602. * No setter as we it is a shared configuration, you can set the values instead.
  17603. */
  17604. get: function () {
  17605. return this._imageProcessingConfiguration;
  17606. },
  17607. enumerable: true,
  17608. configurable: true
  17609. });
  17610. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17611. get: function () {
  17612. return this._forcePointsCloud;
  17613. },
  17614. set: function (value) {
  17615. if (this._forcePointsCloud === value) {
  17616. return;
  17617. }
  17618. this._forcePointsCloud = value;
  17619. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17620. },
  17621. enumerable: true,
  17622. configurable: true
  17623. });
  17624. Object.defineProperty(Scene.prototype, "onDispose", {
  17625. /** A function to be executed when this scene is disposed. */
  17626. set: function (callback) {
  17627. if (this._onDisposeObserver) {
  17628. this.onDisposeObservable.remove(this._onDisposeObserver);
  17629. }
  17630. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17631. },
  17632. enumerable: true,
  17633. configurable: true
  17634. });
  17635. Object.defineProperty(Scene.prototype, "beforeRender", {
  17636. /** A function to be executed before rendering this scene */
  17637. set: function (callback) {
  17638. if (this._onBeforeRenderObserver) {
  17639. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17640. }
  17641. if (callback) {
  17642. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17643. }
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. Object.defineProperty(Scene.prototype, "afterRender", {
  17649. /** A function to be executed after rendering this scene */
  17650. set: function (callback) {
  17651. if (this._onAfterRenderObserver) {
  17652. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17653. }
  17654. if (callback) {
  17655. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17656. }
  17657. },
  17658. enumerable: true,
  17659. configurable: true
  17660. });
  17661. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17662. set: function (callback) {
  17663. if (this._onBeforeCameraRenderObserver) {
  17664. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17665. }
  17666. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17667. },
  17668. enumerable: true,
  17669. configurable: true
  17670. });
  17671. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17672. set: function (callback) {
  17673. if (this._onAfterCameraRenderObserver) {
  17674. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17675. }
  17676. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17677. },
  17678. enumerable: true,
  17679. configurable: true
  17680. });
  17681. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17682. get: function () {
  17683. if (!this._gamepadManager) {
  17684. this._gamepadManager = new BABYLON.GamepadManager();
  17685. }
  17686. return this._gamepadManager;
  17687. },
  17688. enumerable: true,
  17689. configurable: true
  17690. });
  17691. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17692. get: function () {
  17693. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17699. get: function () {
  17700. return this._useRightHandedSystem;
  17701. },
  17702. set: function (value) {
  17703. if (this._useRightHandedSystem === value) {
  17704. return;
  17705. }
  17706. this._useRightHandedSystem = value;
  17707. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Scene.prototype.setStepId = function (newStepId) {
  17713. this._currentStepId = newStepId;
  17714. };
  17715. ;
  17716. Scene.prototype.getStepId = function () {
  17717. return this._currentStepId;
  17718. };
  17719. ;
  17720. Scene.prototype.getInternalStep = function () {
  17721. return this._currentInternalStep;
  17722. };
  17723. ;
  17724. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17725. get: function () {
  17726. return this._fogEnabled;
  17727. },
  17728. /**
  17729. * is fog enabled on this scene.
  17730. */
  17731. set: function (value) {
  17732. if (this._fogEnabled === value) {
  17733. return;
  17734. }
  17735. this._fogEnabled = value;
  17736. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17737. },
  17738. enumerable: true,
  17739. configurable: true
  17740. });
  17741. Object.defineProperty(Scene.prototype, "fogMode", {
  17742. get: function () {
  17743. return this._fogMode;
  17744. },
  17745. set: function (value) {
  17746. if (this._fogMode === value) {
  17747. return;
  17748. }
  17749. this._fogMode = value;
  17750. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17751. },
  17752. enumerable: true,
  17753. configurable: true
  17754. });
  17755. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17756. get: function () {
  17757. return this._shadowsEnabled;
  17758. },
  17759. set: function (value) {
  17760. if (this._shadowsEnabled === value) {
  17761. return;
  17762. }
  17763. this._shadowsEnabled = value;
  17764. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17765. },
  17766. enumerable: true,
  17767. configurable: true
  17768. });
  17769. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17770. get: function () {
  17771. return this._lightsEnabled;
  17772. },
  17773. set: function (value) {
  17774. if (this._lightsEnabled === value) {
  17775. return;
  17776. }
  17777. this._lightsEnabled = value;
  17778. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17779. },
  17780. enumerable: true,
  17781. configurable: true
  17782. });
  17783. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17784. /** The default material used on meshes when no material is affected */
  17785. get: function () {
  17786. if (!this._defaultMaterial) {
  17787. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17788. }
  17789. return this._defaultMaterial;
  17790. },
  17791. /** The default material used on meshes when no material is affected */
  17792. set: function (value) {
  17793. this._defaultMaterial = value;
  17794. },
  17795. enumerable: true,
  17796. configurable: true
  17797. });
  17798. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17799. get: function () {
  17800. return this._texturesEnabled;
  17801. },
  17802. set: function (value) {
  17803. if (this._texturesEnabled === value) {
  17804. return;
  17805. }
  17806. this._texturesEnabled = value;
  17807. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17808. },
  17809. enumerable: true,
  17810. configurable: true
  17811. });
  17812. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17813. get: function () {
  17814. return this._skeletonsEnabled;
  17815. },
  17816. set: function (value) {
  17817. if (this._skeletonsEnabled === value) {
  17818. return;
  17819. }
  17820. this._skeletonsEnabled = value;
  17821. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17822. },
  17823. enumerable: true,
  17824. configurable: true
  17825. });
  17826. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17827. get: function () {
  17828. if (!this._postProcessRenderPipelineManager) {
  17829. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17830. }
  17831. return this._postProcessRenderPipelineManager;
  17832. },
  17833. enumerable: true,
  17834. configurable: true
  17835. });
  17836. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17837. get: function () {
  17838. if (!this._mainSoundTrack) {
  17839. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17840. }
  17841. return this._mainSoundTrack;
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17847. get: function () {
  17848. return this._alternateRendering;
  17849. },
  17850. enumerable: true,
  17851. configurable: true
  17852. });
  17853. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17854. get: function () {
  17855. return this._frustumPlanes;
  17856. },
  17857. enumerable: true,
  17858. configurable: true
  17859. });
  17860. Object.defineProperty(Scene.prototype, "debugLayer", {
  17861. // Properties
  17862. get: function () {
  17863. if (!this._debugLayer) {
  17864. this._debugLayer = new BABYLON.DebugLayer(this);
  17865. }
  17866. return this._debugLayer;
  17867. },
  17868. enumerable: true,
  17869. configurable: true
  17870. });
  17871. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17872. get: function () {
  17873. return this._workerCollisions;
  17874. },
  17875. set: function (enabled) {
  17876. if (!BABYLON.CollisionCoordinatorLegacy) {
  17877. return;
  17878. }
  17879. enabled = (enabled && !!Worker);
  17880. this._workerCollisions = enabled;
  17881. if (this.collisionCoordinator) {
  17882. this.collisionCoordinator.destroy();
  17883. }
  17884. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17885. this.collisionCoordinator.init(this);
  17886. },
  17887. enumerable: true,
  17888. configurable: true
  17889. });
  17890. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17891. get: function () {
  17892. return this._selectionOctree;
  17893. },
  17894. enumerable: true,
  17895. configurable: true
  17896. });
  17897. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17898. /**
  17899. * The mesh that is currently under the pointer.
  17900. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17901. */
  17902. get: function () {
  17903. return this._pointerOverMesh;
  17904. },
  17905. enumerable: true,
  17906. configurable: true
  17907. });
  17908. Object.defineProperty(Scene.prototype, "pointerX", {
  17909. /**
  17910. * Current on-screen X position of the pointer
  17911. * @return {number} X position of the pointer
  17912. */
  17913. get: function () {
  17914. return this._pointerX;
  17915. },
  17916. enumerable: true,
  17917. configurable: true
  17918. });
  17919. Object.defineProperty(Scene.prototype, "pointerY", {
  17920. /**
  17921. * Current on-screen Y position of the pointer
  17922. * @return {number} Y position of the pointer
  17923. */
  17924. get: function () {
  17925. return this._pointerY;
  17926. },
  17927. enumerable: true,
  17928. configurable: true
  17929. });
  17930. Scene.prototype.getCachedMaterial = function () {
  17931. return this._cachedMaterial;
  17932. };
  17933. Scene.prototype.getCachedEffect = function () {
  17934. return this._cachedEffect;
  17935. };
  17936. Scene.prototype.getCachedVisibility = function () {
  17937. return this._cachedVisibility;
  17938. };
  17939. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17940. if (visibility === void 0) { visibility = 1; }
  17941. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17942. };
  17943. Scene.prototype.getBoundingBoxRenderer = function () {
  17944. if (!this._boundingBoxRenderer) {
  17945. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17946. }
  17947. return this._boundingBoxRenderer;
  17948. };
  17949. Scene.prototype.getOutlineRenderer = function () {
  17950. return this._outlineRenderer;
  17951. };
  17952. Scene.prototype.getEngine = function () {
  17953. return this._engine;
  17954. };
  17955. Scene.prototype.getTotalVertices = function () {
  17956. return this._totalVertices.current;
  17957. };
  17958. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17959. get: function () {
  17960. return this._totalVertices;
  17961. },
  17962. enumerable: true,
  17963. configurable: true
  17964. });
  17965. Scene.prototype.getActiveIndices = function () {
  17966. return this._activeIndices.current;
  17967. };
  17968. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17969. get: function () {
  17970. return this._activeIndices;
  17971. },
  17972. enumerable: true,
  17973. configurable: true
  17974. });
  17975. Scene.prototype.getActiveParticles = function () {
  17976. return this._activeParticles.current;
  17977. };
  17978. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17979. get: function () {
  17980. return this._activeParticles;
  17981. },
  17982. enumerable: true,
  17983. configurable: true
  17984. });
  17985. Scene.prototype.getActiveBones = function () {
  17986. return this._activeBones.current;
  17987. };
  17988. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17989. get: function () {
  17990. return this._activeBones;
  17991. },
  17992. enumerable: true,
  17993. configurable: true
  17994. });
  17995. // Stats
  17996. Scene.prototype.getInterFramePerfCounter = function () {
  17997. return this._interFrameDuration.current;
  17998. };
  17999. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18000. get: function () {
  18001. return this._interFrameDuration;
  18002. },
  18003. enumerable: true,
  18004. configurable: true
  18005. });
  18006. Scene.prototype.getLastFrameDuration = function () {
  18007. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18008. return 0;
  18009. };
  18010. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18011. get: function () {
  18012. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18013. return null;
  18014. },
  18015. enumerable: true,
  18016. configurable: true
  18017. });
  18018. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18019. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18020. return 0;
  18021. };
  18022. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18023. get: function () {
  18024. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18025. return null;
  18026. },
  18027. enumerable: true,
  18028. configurable: true
  18029. });
  18030. Scene.prototype.getActiveMeshes = function () {
  18031. return this._activeMeshes;
  18032. };
  18033. Scene.prototype.getRenderTargetsDuration = function () {
  18034. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18035. return 0;
  18036. };
  18037. Scene.prototype.getRenderDuration = function () {
  18038. return this._renderDuration.current;
  18039. };
  18040. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18041. get: function () {
  18042. return this._renderDuration;
  18043. },
  18044. enumerable: true,
  18045. configurable: true
  18046. });
  18047. Scene.prototype.getParticlesDuration = function () {
  18048. return this._particlesDuration.current;
  18049. };
  18050. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18051. get: function () {
  18052. return this._particlesDuration;
  18053. },
  18054. enumerable: true,
  18055. configurable: true
  18056. });
  18057. Scene.prototype.getSpritesDuration = function () {
  18058. return this._spritesDuration.current;
  18059. };
  18060. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18061. get: function () {
  18062. return this._spritesDuration;
  18063. },
  18064. enumerable: true,
  18065. configurable: true
  18066. });
  18067. Scene.prototype.getAnimationRatio = function () {
  18068. return this._animationRatio;
  18069. };
  18070. Scene.prototype.getRenderId = function () {
  18071. return this._renderId;
  18072. };
  18073. Scene.prototype.incrementRenderId = function () {
  18074. this._renderId++;
  18075. };
  18076. Scene.prototype._updatePointerPosition = function (evt) {
  18077. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18078. if (!canvasRect) {
  18079. return;
  18080. }
  18081. this._pointerX = evt.clientX - canvasRect.left;
  18082. this._pointerY = evt.clientY - canvasRect.top;
  18083. this._unTranslatedPointerX = this._pointerX;
  18084. this._unTranslatedPointerY = this._pointerY;
  18085. };
  18086. Scene.prototype._createUbo = function () {
  18087. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18088. this._sceneUbo.addUniform("viewProjection", 16);
  18089. this._sceneUbo.addUniform("view", 16);
  18090. };
  18091. Scene.prototype._createAlternateUbo = function () {
  18092. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18093. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18094. this._alternateSceneUbo.addUniform("view", 16);
  18095. };
  18096. // Pointers handling
  18097. /**
  18098. * Use this method to simulate a pointer move on a mesh
  18099. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18100. */
  18101. Scene.prototype.simulatePointerMove = function (pickResult) {
  18102. var evt = new PointerEvent("pointermove");
  18103. return this._processPointerMove(pickResult, evt);
  18104. };
  18105. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18106. var canvas = this._engine.getRenderingCanvas();
  18107. if (!canvas) {
  18108. return this;
  18109. }
  18110. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18111. this.setPointerOverSprite(null);
  18112. this.setPointerOverMesh(pickResult.pickedMesh);
  18113. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18114. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18115. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18116. }
  18117. else {
  18118. canvas.style.cursor = this.hoverCursor;
  18119. }
  18120. }
  18121. else {
  18122. canvas.style.cursor = this.defaultCursor;
  18123. }
  18124. }
  18125. else {
  18126. this.setPointerOverMesh(null);
  18127. // Sprites
  18128. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18129. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18130. this.setPointerOverSprite(pickResult.pickedSprite);
  18131. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18132. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18133. }
  18134. else {
  18135. canvas.style.cursor = this.hoverCursor;
  18136. }
  18137. }
  18138. else {
  18139. this.setPointerOverSprite(null);
  18140. // Restore pointer
  18141. canvas.style.cursor = this.defaultCursor;
  18142. }
  18143. }
  18144. if (pickResult) {
  18145. if (this.onPointerMove) {
  18146. this.onPointerMove(evt, pickResult);
  18147. }
  18148. if (this.onPointerObservable.hasObservers()) {
  18149. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18150. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18151. this.onPointerObservable.notifyObservers(pi, type);
  18152. }
  18153. }
  18154. return this;
  18155. };
  18156. /**
  18157. * Use this method to simulate a pointer down on a mesh
  18158. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18159. */
  18160. Scene.prototype.simulatePointerDown = function (pickResult) {
  18161. var evt = new PointerEvent("pointerdown");
  18162. return this._processPointerDown(pickResult, evt);
  18163. };
  18164. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18165. var _this = this;
  18166. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18167. this._pickedDownMesh = pickResult.pickedMesh;
  18168. var actionManager = pickResult.pickedMesh.actionManager;
  18169. if (actionManager) {
  18170. if (actionManager.hasPickTriggers) {
  18171. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18172. switch (evt.button) {
  18173. case 0:
  18174. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18175. break;
  18176. case 1:
  18177. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18178. break;
  18179. case 2:
  18180. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18181. break;
  18182. }
  18183. }
  18184. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18185. window.setTimeout(function () {
  18186. 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);
  18187. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18188. if (_this._totalPointersPressed !== 0 &&
  18189. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18190. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18191. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18192. _this._startingPointerTime = 0;
  18193. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18194. }
  18195. }
  18196. }, Scene.LongPressDelay);
  18197. }
  18198. }
  18199. }
  18200. if (pickResult) {
  18201. if (this.onPointerDown) {
  18202. this.onPointerDown(evt, pickResult);
  18203. }
  18204. if (this.onPointerObservable.hasObservers()) {
  18205. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18206. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18207. this.onPointerObservable.notifyObservers(pi, type);
  18208. }
  18209. }
  18210. return this;
  18211. };
  18212. /**
  18213. * Use this method to simulate a pointer up on a mesh
  18214. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18215. */
  18216. Scene.prototype.simulatePointerUp = function (pickResult) {
  18217. var evt = new PointerEvent("pointerup");
  18218. var clickInfo = new ClickInfo();
  18219. clickInfo.singleClick = true;
  18220. return this._processPointerUp(pickResult, evt, clickInfo);
  18221. };
  18222. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18223. if (pickResult && pickResult && pickResult.pickedMesh) {
  18224. this._pickedUpMesh = pickResult.pickedMesh;
  18225. if (this._pickedDownMesh === this._pickedUpMesh) {
  18226. if (this.onPointerPick) {
  18227. this.onPointerPick(evt, pickResult);
  18228. }
  18229. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18230. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18231. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18232. this.onPointerObservable.notifyObservers(pi, type);
  18233. }
  18234. }
  18235. if (pickResult.pickedMesh.actionManager) {
  18236. if (clickInfo.ignore) {
  18237. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18238. }
  18239. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18240. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18241. }
  18242. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18243. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18244. }
  18245. }
  18246. }
  18247. if (this._pickedDownMesh &&
  18248. this._pickedDownMesh.actionManager &&
  18249. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18250. this._pickedDownMesh !== this._pickedUpMesh) {
  18251. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18252. }
  18253. if (this.onPointerUp) {
  18254. this.onPointerUp(evt, pickResult);
  18255. }
  18256. if (this.onPointerObservable.hasObservers()) {
  18257. if (!clickInfo.ignore) {
  18258. if (!clickInfo.hasSwiped) {
  18259. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18260. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18261. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18262. this.onPointerObservable.notifyObservers(pi, type);
  18263. }
  18264. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18265. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18266. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18267. this.onPointerObservable.notifyObservers(pi, type);
  18268. }
  18269. }
  18270. }
  18271. else {
  18272. var type = BABYLON.PointerEventTypes.POINTERUP;
  18273. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18274. this.onPointerObservable.notifyObservers(pi, type);
  18275. }
  18276. }
  18277. return this;
  18278. };
  18279. /**
  18280. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18281. * @param attachUp defines if you want to attach events to pointerup
  18282. * @param attachDown defines if you want to attach events to pointerdown
  18283. * @param attachMove defines if you want to attach events to pointermove
  18284. */
  18285. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18286. var _this = this;
  18287. if (attachUp === void 0) { attachUp = true; }
  18288. if (attachDown === void 0) { attachDown = true; }
  18289. if (attachMove === void 0) { attachMove = true; }
  18290. this._initActionManager = function (act, clickInfo) {
  18291. if (!_this._meshPickProceed) {
  18292. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18293. _this._currentPickResult = pickResult;
  18294. if (pickResult) {
  18295. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18296. }
  18297. _this._meshPickProceed = true;
  18298. }
  18299. return act;
  18300. };
  18301. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18302. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18303. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18304. btn !== _this._previousButtonPressed) {
  18305. _this._doubleClickOccured = false;
  18306. clickInfo.singleClick = true;
  18307. clickInfo.ignore = false;
  18308. cb(clickInfo, _this._currentPickResult);
  18309. }
  18310. };
  18311. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18312. var clickInfo = new ClickInfo();
  18313. _this._currentPickResult = null;
  18314. var act = null;
  18315. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18316. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18317. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18318. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18319. act = _this._initActionManager(act, clickInfo);
  18320. if (act)
  18321. checkPicking = act.hasPickTriggers;
  18322. }
  18323. if (checkPicking) {
  18324. var btn = evt.button;
  18325. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18326. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18327. if (!clickInfo.hasSwiped) {
  18328. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18329. if (!checkSingleClickImmediately) {
  18330. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18331. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18332. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18333. act = _this._initActionManager(act, clickInfo);
  18334. if (act)
  18335. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18336. }
  18337. }
  18338. if (checkSingleClickImmediately) {
  18339. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18340. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18341. btn !== _this._previousButtonPressed) {
  18342. clickInfo.singleClick = true;
  18343. cb(clickInfo, _this._currentPickResult);
  18344. }
  18345. }
  18346. else {
  18347. // wait that no double click has been raised during the double click delay
  18348. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18349. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18350. }
  18351. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18352. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18353. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18354. act = _this._initActionManager(act, clickInfo);
  18355. if (act)
  18356. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18357. }
  18358. if (checkDoubleClick) {
  18359. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18360. if (btn === _this._previousButtonPressed &&
  18361. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18362. !_this._doubleClickOccured) {
  18363. // pointer has not moved for 2 clicks, it's a double click
  18364. if (!clickInfo.hasSwiped &&
  18365. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18366. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18367. _this._previousStartingPointerTime = 0;
  18368. _this._doubleClickOccured = true;
  18369. clickInfo.doubleClick = true;
  18370. clickInfo.ignore = false;
  18371. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18372. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18373. }
  18374. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18375. cb(clickInfo, _this._currentPickResult);
  18376. }
  18377. else {
  18378. _this._doubleClickOccured = false;
  18379. _this._previousStartingPointerTime = _this._startingPointerTime;
  18380. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18381. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18382. _this._previousButtonPressed = btn;
  18383. _this._previousHasSwiped = clickInfo.hasSwiped;
  18384. if (Scene.ExclusiveDoubleClickMode) {
  18385. if (_this._previousDelayedSimpleClickTimeout) {
  18386. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18387. }
  18388. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18389. cb(clickInfo, _this._previousPickResult);
  18390. }
  18391. else {
  18392. cb(clickInfo, _this._currentPickResult);
  18393. }
  18394. }
  18395. }
  18396. else {
  18397. _this._doubleClickOccured = false;
  18398. _this._previousStartingPointerTime = _this._startingPointerTime;
  18399. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18400. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18401. _this._previousButtonPressed = btn;
  18402. _this._previousHasSwiped = clickInfo.hasSwiped;
  18403. }
  18404. }
  18405. }
  18406. }
  18407. clickInfo.ignore = true;
  18408. cb(clickInfo, _this._currentPickResult);
  18409. };
  18410. this._spritePredicate = function (sprite) {
  18411. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18412. };
  18413. this._onPointerMove = function (evt) {
  18414. _this._updatePointerPosition(evt);
  18415. // PreObservable support
  18416. if (_this.onPrePointerObservable.hasObservers()) {
  18417. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18418. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18419. _this.onPrePointerObservable.notifyObservers(pi, type);
  18420. if (pi.skipOnPointerObservable) {
  18421. return;
  18422. }
  18423. }
  18424. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18425. return;
  18426. }
  18427. if (!_this.pointerMovePredicate) {
  18428. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18429. }
  18430. // Meshes
  18431. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18432. _this._processPointerMove(pickResult, evt);
  18433. };
  18434. this._onPointerDown = function (evt) {
  18435. _this._totalPointersPressed++;
  18436. _this._pickedDownMesh = null;
  18437. _this._meshPickProceed = false;
  18438. _this._updatePointerPosition(evt);
  18439. if (_this.preventDefaultOnPointerDown && canvas) {
  18440. evt.preventDefault();
  18441. canvas.focus();
  18442. }
  18443. // PreObservable support
  18444. if (_this.onPrePointerObservable.hasObservers()) {
  18445. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18446. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18447. _this.onPrePointerObservable.notifyObservers(pi, type);
  18448. if (pi.skipOnPointerObservable) {
  18449. return;
  18450. }
  18451. }
  18452. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18453. return;
  18454. }
  18455. _this._startingPointerPosition.x = _this._pointerX;
  18456. _this._startingPointerPosition.y = _this._pointerY;
  18457. _this._startingPointerTime = new Date().getTime();
  18458. if (!_this.pointerDownPredicate) {
  18459. _this.pointerDownPredicate = function (mesh) {
  18460. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18461. };
  18462. }
  18463. // Meshes
  18464. _this._pickedDownMesh = null;
  18465. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18466. _this._processPointerDown(pickResult, evt);
  18467. // Sprites
  18468. _this._pickedDownSprite = null;
  18469. if (_this.spriteManagers.length > 0) {
  18470. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18471. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18472. if (pickResult.pickedSprite.actionManager) {
  18473. _this._pickedDownSprite = pickResult.pickedSprite;
  18474. switch (evt.button) {
  18475. case 0:
  18476. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18477. break;
  18478. case 1:
  18479. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18480. break;
  18481. case 2:
  18482. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18483. break;
  18484. }
  18485. if (pickResult.pickedSprite.actionManager) {
  18486. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18487. }
  18488. }
  18489. }
  18490. }
  18491. };
  18492. this._onPointerUp = function (evt) {
  18493. if (_this._totalPointersPressed === 0) {
  18494. return; // So we need to test it the pointer down was pressed before.
  18495. }
  18496. _this._totalPointersPressed--;
  18497. _this._pickedUpMesh = null;
  18498. _this._meshPickProceed = false;
  18499. _this._updatePointerPosition(evt);
  18500. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18501. // PreObservable support
  18502. if (_this.onPrePointerObservable.hasObservers()) {
  18503. if (!clickInfo.ignore) {
  18504. if (!clickInfo.hasSwiped) {
  18505. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18506. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18507. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18508. _this.onPrePointerObservable.notifyObservers(pi, type);
  18509. if (pi.skipOnPointerObservable) {
  18510. return;
  18511. }
  18512. }
  18513. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18514. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18515. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18516. _this.onPrePointerObservable.notifyObservers(pi, type);
  18517. if (pi.skipOnPointerObservable) {
  18518. return;
  18519. }
  18520. }
  18521. }
  18522. }
  18523. else {
  18524. var type = BABYLON.PointerEventTypes.POINTERUP;
  18525. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18526. _this.onPrePointerObservable.notifyObservers(pi, type);
  18527. if (pi.skipOnPointerObservable) {
  18528. return;
  18529. }
  18530. }
  18531. }
  18532. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18533. return;
  18534. }
  18535. if (!_this.pointerUpPredicate) {
  18536. _this.pointerUpPredicate = function (mesh) {
  18537. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18538. };
  18539. }
  18540. // Meshes
  18541. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18542. _this._initActionManager(null, clickInfo);
  18543. }
  18544. if (!pickResult) {
  18545. pickResult = _this._currentPickResult;
  18546. }
  18547. _this._processPointerUp(pickResult, evt, clickInfo);
  18548. // Sprites
  18549. if (_this.spriteManagers.length > 0) {
  18550. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18551. if (spritePickResult) {
  18552. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18553. if (spritePickResult.pickedSprite.actionManager) {
  18554. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18555. if (spritePickResult.pickedSprite.actionManager) {
  18556. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18557. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18558. }
  18559. }
  18560. }
  18561. }
  18562. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18563. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18564. }
  18565. }
  18566. }
  18567. _this._previousPickResult = _this._currentPickResult;
  18568. });
  18569. };
  18570. this._onKeyDown = function (evt) {
  18571. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18572. if (_this.onPreKeyboardObservable.hasObservers()) {
  18573. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18574. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18575. if (pi.skipOnPointerObservable) {
  18576. return;
  18577. }
  18578. }
  18579. if (_this.onKeyboardObservable.hasObservers()) {
  18580. var pi = new BABYLON.KeyboardInfo(type, evt);
  18581. _this.onKeyboardObservable.notifyObservers(pi, type);
  18582. }
  18583. if (_this.actionManager) {
  18584. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18585. }
  18586. };
  18587. this._onKeyUp = function (evt) {
  18588. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18589. if (_this.onPreKeyboardObservable.hasObservers()) {
  18590. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18591. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18592. if (pi.skipOnPointerObservable) {
  18593. return;
  18594. }
  18595. }
  18596. if (_this.onKeyboardObservable.hasObservers()) {
  18597. var pi = new BABYLON.KeyboardInfo(type, evt);
  18598. _this.onKeyboardObservable.notifyObservers(pi, type);
  18599. }
  18600. if (_this.actionManager) {
  18601. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18602. }
  18603. };
  18604. var engine = this.getEngine();
  18605. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18606. if (!canvas) {
  18607. return;
  18608. }
  18609. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18610. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18611. });
  18612. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18613. if (!canvas) {
  18614. return;
  18615. }
  18616. canvas.removeEventListener("keydown", _this._onKeyDown);
  18617. canvas.removeEventListener("keyup", _this._onKeyUp);
  18618. });
  18619. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18620. var canvas = this._engine.getRenderingCanvas();
  18621. if (!canvas) {
  18622. return;
  18623. }
  18624. if (attachMove) {
  18625. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18626. // Wheel
  18627. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18628. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18629. }
  18630. if (attachDown) {
  18631. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18632. }
  18633. if (attachUp) {
  18634. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18635. }
  18636. canvas.tabIndex = 1;
  18637. };
  18638. Scene.prototype.detachControl = function () {
  18639. var engine = this.getEngine();
  18640. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18641. var canvas = engine.getRenderingCanvas();
  18642. if (!canvas) {
  18643. return;
  18644. }
  18645. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18646. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18647. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18648. if (this._onCanvasBlurObserver) {
  18649. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18650. }
  18651. if (this._onCanvasFocusObserver) {
  18652. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18653. }
  18654. // Wheel
  18655. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18656. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18657. // Keyboard
  18658. canvas.removeEventListener("keydown", this._onKeyDown);
  18659. canvas.removeEventListener("keyup", this._onKeyUp);
  18660. // Observables
  18661. this.onKeyboardObservable.clear();
  18662. this.onPreKeyboardObservable.clear();
  18663. this.onPointerObservable.clear();
  18664. this.onPrePointerObservable.clear();
  18665. };
  18666. // Ready
  18667. Scene.prototype.isReady = function () {
  18668. if (this._isDisposed) {
  18669. return false;
  18670. }
  18671. if (this._pendingData.length > 0) {
  18672. return false;
  18673. }
  18674. var index;
  18675. // Geometries
  18676. for (index = 0; index < this._geometries.length; index++) {
  18677. var geometry = this._geometries[index];
  18678. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18679. return false;
  18680. }
  18681. }
  18682. // Meshes
  18683. for (index = 0; index < this.meshes.length; index++) {
  18684. var mesh = this.meshes[index];
  18685. if (!mesh.isEnabled()) {
  18686. continue;
  18687. }
  18688. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18689. continue;
  18690. }
  18691. if (!mesh.isReady()) {
  18692. return false;
  18693. }
  18694. var mat = mesh.material;
  18695. if (mat) {
  18696. if (!mat.isReady(mesh)) {
  18697. return false;
  18698. }
  18699. }
  18700. }
  18701. return true;
  18702. };
  18703. Scene.prototype.resetCachedMaterial = function () {
  18704. this._cachedMaterial = null;
  18705. this._cachedEffect = null;
  18706. this._cachedVisibility = null;
  18707. };
  18708. Scene.prototype.registerBeforeRender = function (func) {
  18709. this.onBeforeRenderObservable.add(func);
  18710. };
  18711. Scene.prototype.unregisterBeforeRender = function (func) {
  18712. this.onBeforeRenderObservable.removeCallback(func);
  18713. };
  18714. Scene.prototype.registerAfterRender = function (func) {
  18715. this.onAfterRenderObservable.add(func);
  18716. };
  18717. Scene.prototype.unregisterAfterRender = function (func) {
  18718. this.onAfterRenderObservable.removeCallback(func);
  18719. };
  18720. Scene.prototype._addPendingData = function (data) {
  18721. this._pendingData.push(data);
  18722. };
  18723. Scene.prototype._removePendingData = function (data) {
  18724. var index = this._pendingData.indexOf(data);
  18725. if (index !== -1) {
  18726. this._pendingData.splice(index, 1);
  18727. }
  18728. };
  18729. Scene.prototype.getWaitingItemsCount = function () {
  18730. return this._pendingData.length;
  18731. };
  18732. /**
  18733. * Registers a function to be executed when the scene is ready.
  18734. * @param {Function} func - the function to be executed.
  18735. */
  18736. Scene.prototype.executeWhenReady = function (func) {
  18737. var _this = this;
  18738. this.onReadyObservable.add(func);
  18739. if (this._executeWhenReadyTimeoutId !== -1) {
  18740. return;
  18741. }
  18742. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18743. _this._checkIsReady();
  18744. }, 150);
  18745. };
  18746. Scene.prototype._checkIsReady = function () {
  18747. var _this = this;
  18748. if (this.isReady()) {
  18749. this.onReadyObservable.notifyObservers(this);
  18750. this.onReadyObservable.clear();
  18751. this._executeWhenReadyTimeoutId = -1;
  18752. return;
  18753. }
  18754. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18755. _this._checkIsReady();
  18756. }, 150);
  18757. };
  18758. // Animations
  18759. /**
  18760. * Will start the animation sequence of a given target
  18761. * @param target - the target
  18762. * @param {number} from - from which frame should animation start
  18763. * @param {number} to - till which frame should animation run.
  18764. * @param {boolean} [loop] - should the animation loop
  18765. * @param {number} [speedRatio] - the speed in which to run the animation
  18766. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18767. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18768. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18769. * See BABYLON.Animatable
  18770. */
  18771. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18772. if (speedRatio === void 0) { speedRatio = 1.0; }
  18773. if (from > to && speedRatio > 0) {
  18774. speedRatio *= -1;
  18775. }
  18776. this.stopAnimation(target);
  18777. if (!animatable) {
  18778. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18779. }
  18780. // Local animations
  18781. if (target.animations) {
  18782. animatable.appendAnimations(target, target.animations);
  18783. }
  18784. // Children animations
  18785. if (target.getAnimatables) {
  18786. var animatables = target.getAnimatables();
  18787. for (var index = 0; index < animatables.length; index++) {
  18788. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18789. }
  18790. }
  18791. animatable.reset();
  18792. return animatable;
  18793. };
  18794. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18795. if (speedRatio === undefined) {
  18796. speedRatio = 1.0;
  18797. }
  18798. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18799. return animatable;
  18800. };
  18801. Scene.prototype.getAnimatableByTarget = function (target) {
  18802. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18803. if (this._activeAnimatables[index].target === target) {
  18804. return this._activeAnimatables[index];
  18805. }
  18806. }
  18807. return null;
  18808. };
  18809. Object.defineProperty(Scene.prototype, "Animatables", {
  18810. get: function () {
  18811. return this._activeAnimatables;
  18812. },
  18813. enumerable: true,
  18814. configurable: true
  18815. });
  18816. /**
  18817. * Will stop the animation of the given target
  18818. * @param target - the target
  18819. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18820. * @see beginAnimation
  18821. */
  18822. Scene.prototype.stopAnimation = function (target, animationName) {
  18823. var animatable = this.getAnimatableByTarget(target);
  18824. if (animatable) {
  18825. animatable.stop(animationName);
  18826. }
  18827. };
  18828. Scene.prototype._animate = function () {
  18829. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18830. return;
  18831. }
  18832. // Getting time
  18833. var now = BABYLON.Tools.Now;
  18834. if (!this._animationTimeLast) {
  18835. if (this._pendingData.length > 0) {
  18836. return;
  18837. }
  18838. this._animationTimeLast = now;
  18839. }
  18840. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18841. this._animationTime += deltaTime;
  18842. this._animationTimeLast = now;
  18843. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18844. this._activeAnimatables[index]._animate(this._animationTime);
  18845. }
  18846. };
  18847. // Matrix
  18848. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18849. this._useAlternateCameraConfiguration = active;
  18850. };
  18851. Scene.prototype.getViewMatrix = function () {
  18852. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18853. };
  18854. Scene.prototype.getProjectionMatrix = function () {
  18855. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18856. };
  18857. Scene.prototype.getTransformMatrix = function () {
  18858. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18859. };
  18860. Scene.prototype.setTransformMatrix = function (view, projection) {
  18861. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18862. return;
  18863. }
  18864. this._viewUpdateFlag = view.updateFlag;
  18865. this._projectionUpdateFlag = projection.updateFlag;
  18866. this._viewMatrix = view;
  18867. this._projectionMatrix = projection;
  18868. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18869. // Update frustum
  18870. if (!this._frustumPlanes) {
  18871. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18872. }
  18873. else {
  18874. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18875. }
  18876. if (this.activeCamera && this.activeCamera._alternateCamera) {
  18877. var otherCamera = this.activeCamera._alternateCamera;
  18878. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  18879. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  18880. }
  18881. if (this._sceneUbo.useUbo) {
  18882. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18883. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18884. this._sceneUbo.update();
  18885. }
  18886. };
  18887. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18888. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18889. return;
  18890. }
  18891. this._alternateViewUpdateFlag = view.updateFlag;
  18892. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18893. this._alternateViewMatrix = view;
  18894. this._alternateProjectionMatrix = projection;
  18895. if (!this._alternateTransformMatrix) {
  18896. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18897. }
  18898. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18899. if (!this._alternateSceneUbo) {
  18900. this._createAlternateUbo();
  18901. }
  18902. if (this._alternateSceneUbo.useUbo) {
  18903. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18904. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18905. this._alternateSceneUbo.update();
  18906. }
  18907. };
  18908. Scene.prototype.getSceneUniformBuffer = function () {
  18909. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18910. };
  18911. // Methods
  18912. Scene.prototype.getUniqueId = function () {
  18913. var result = Scene._uniqueIdCounter;
  18914. Scene._uniqueIdCounter++;
  18915. return result;
  18916. };
  18917. Scene.prototype.addMesh = function (newMesh) {
  18918. this.meshes.push(newMesh);
  18919. //notify the collision coordinator
  18920. if (this.collisionCoordinator) {
  18921. this.collisionCoordinator.onMeshAdded(newMesh);
  18922. }
  18923. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18924. };
  18925. Scene.prototype.removeMesh = function (toRemove) {
  18926. var index = this.meshes.indexOf(toRemove);
  18927. if (index !== -1) {
  18928. // Remove from the scene if mesh found
  18929. this.meshes.splice(index, 1);
  18930. }
  18931. //notify the collision coordinator
  18932. if (this.collisionCoordinator) {
  18933. this.collisionCoordinator.onMeshRemoved(toRemove);
  18934. }
  18935. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18936. return index;
  18937. };
  18938. Scene.prototype.removeSkeleton = function (toRemove) {
  18939. var index = this.skeletons.indexOf(toRemove);
  18940. if (index !== -1) {
  18941. // Remove from the scene if found
  18942. this.skeletons.splice(index, 1);
  18943. }
  18944. return index;
  18945. };
  18946. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18947. var index = this.morphTargetManagers.indexOf(toRemove);
  18948. if (index !== -1) {
  18949. // Remove from the scene if found
  18950. this.morphTargetManagers.splice(index, 1);
  18951. }
  18952. return index;
  18953. };
  18954. Scene.prototype.removeLight = function (toRemove) {
  18955. var index = this.lights.indexOf(toRemove);
  18956. if (index !== -1) {
  18957. // Remove from the scene if mesh found
  18958. this.lights.splice(index, 1);
  18959. this.sortLightsByPriority();
  18960. }
  18961. this.onLightRemovedObservable.notifyObservers(toRemove);
  18962. return index;
  18963. };
  18964. Scene.prototype.removeCamera = function (toRemove) {
  18965. var index = this.cameras.indexOf(toRemove);
  18966. if (index !== -1) {
  18967. // Remove from the scene if mesh found
  18968. this.cameras.splice(index, 1);
  18969. }
  18970. // Remove from activeCameras
  18971. var index2 = this.activeCameras.indexOf(toRemove);
  18972. if (index2 !== -1) {
  18973. // Remove from the scene if mesh found
  18974. this.activeCameras.splice(index2, 1);
  18975. }
  18976. // Reset the activeCamera
  18977. if (this.activeCamera === toRemove) {
  18978. if (this.cameras.length > 0) {
  18979. this.activeCamera = this.cameras[0];
  18980. }
  18981. else {
  18982. this.activeCamera = null;
  18983. }
  18984. }
  18985. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18986. return index;
  18987. };
  18988. Scene.prototype.addLight = function (newLight) {
  18989. this.lights.push(newLight);
  18990. this.sortLightsByPriority();
  18991. this.onNewLightAddedObservable.notifyObservers(newLight);
  18992. };
  18993. Scene.prototype.sortLightsByPriority = function () {
  18994. if (this.requireLightSorting) {
  18995. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18996. }
  18997. };
  18998. Scene.prototype.addCamera = function (newCamera) {
  18999. this.cameras.push(newCamera);
  19000. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19001. };
  19002. /**
  19003. * Switch active camera
  19004. * @param {Camera} newCamera - new active camera
  19005. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19006. */
  19007. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19008. if (attachControl === void 0) { attachControl = true; }
  19009. var canvas = this._engine.getRenderingCanvas();
  19010. if (!canvas) {
  19011. return;
  19012. }
  19013. if (this.activeCamera) {
  19014. this.activeCamera.detachControl(canvas);
  19015. }
  19016. this.activeCamera = newCamera;
  19017. if (attachControl) {
  19018. newCamera.attachControl(canvas);
  19019. }
  19020. };
  19021. /**
  19022. * sets the active camera of the scene using its ID
  19023. * @param {string} id - the camera's ID
  19024. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19025. * @see activeCamera
  19026. */
  19027. Scene.prototype.setActiveCameraByID = function (id) {
  19028. var camera = this.getCameraByID(id);
  19029. if (camera) {
  19030. this.activeCamera = camera;
  19031. return camera;
  19032. }
  19033. return null;
  19034. };
  19035. /**
  19036. * sets the active camera of the scene using its name
  19037. * @param {string} name - the camera's name
  19038. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19039. * @see activeCamera
  19040. */
  19041. Scene.prototype.setActiveCameraByName = function (name) {
  19042. var camera = this.getCameraByName(name);
  19043. if (camera) {
  19044. this.activeCamera = camera;
  19045. return camera;
  19046. }
  19047. return null;
  19048. };
  19049. /**
  19050. * get a material using its id
  19051. * @param {string} the material's ID
  19052. * @return {BABYLON.Material|null} the material or null if none found.
  19053. */
  19054. Scene.prototype.getMaterialByID = function (id) {
  19055. for (var index = 0; index < this.materials.length; index++) {
  19056. if (this.materials[index].id === id) {
  19057. return this.materials[index];
  19058. }
  19059. }
  19060. return null;
  19061. };
  19062. /**
  19063. * get a material using its name
  19064. * @param {string} the material's name
  19065. * @return {BABYLON.Material|null} the material or null if none found.
  19066. */
  19067. Scene.prototype.getMaterialByName = function (name) {
  19068. for (var index = 0; index < this.materials.length; index++) {
  19069. if (this.materials[index].name === name) {
  19070. return this.materials[index];
  19071. }
  19072. }
  19073. return null;
  19074. };
  19075. Scene.prototype.getLensFlareSystemByName = function (name) {
  19076. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19077. if (this.lensFlareSystems[index].name === name) {
  19078. return this.lensFlareSystems[index];
  19079. }
  19080. }
  19081. return null;
  19082. };
  19083. Scene.prototype.getLensFlareSystemByID = function (id) {
  19084. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19085. if (this.lensFlareSystems[index].id === id) {
  19086. return this.lensFlareSystems[index];
  19087. }
  19088. }
  19089. return null;
  19090. };
  19091. Scene.prototype.getCameraByID = function (id) {
  19092. for (var index = 0; index < this.cameras.length; index++) {
  19093. if (this.cameras[index].id === id) {
  19094. return this.cameras[index];
  19095. }
  19096. }
  19097. return null;
  19098. };
  19099. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19100. for (var index = 0; index < this.cameras.length; index++) {
  19101. if (this.cameras[index].uniqueId === uniqueId) {
  19102. return this.cameras[index];
  19103. }
  19104. }
  19105. return null;
  19106. };
  19107. /**
  19108. * get a camera using its name
  19109. * @param {string} the camera's name
  19110. * @return {BABYLON.Camera|null} the camera or null if none found.
  19111. */
  19112. Scene.prototype.getCameraByName = function (name) {
  19113. for (var index = 0; index < this.cameras.length; index++) {
  19114. if (this.cameras[index].name === name) {
  19115. return this.cameras[index];
  19116. }
  19117. }
  19118. return null;
  19119. };
  19120. /**
  19121. * get a bone using its id
  19122. * @param {string} the bone's id
  19123. * @return {BABYLON.Bone|null} the bone or null if not found
  19124. */
  19125. Scene.prototype.getBoneByID = function (id) {
  19126. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19127. var skeleton = this.skeletons[skeletonIndex];
  19128. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19129. if (skeleton.bones[boneIndex].id === id) {
  19130. return skeleton.bones[boneIndex];
  19131. }
  19132. }
  19133. }
  19134. return null;
  19135. };
  19136. /**
  19137. * get a bone using its id
  19138. * @param {string} the bone's name
  19139. * @return {BABYLON.Bone|null} the bone or null if not found
  19140. */
  19141. Scene.prototype.getBoneByName = function (name) {
  19142. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19143. var skeleton = this.skeletons[skeletonIndex];
  19144. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19145. if (skeleton.bones[boneIndex].name === name) {
  19146. return skeleton.bones[boneIndex];
  19147. }
  19148. }
  19149. }
  19150. return null;
  19151. };
  19152. /**
  19153. * get a light node using its name
  19154. * @param {string} the light's name
  19155. * @return {BABYLON.Light|null} the light or null if none found.
  19156. */
  19157. Scene.prototype.getLightByName = function (name) {
  19158. for (var index = 0; index < this.lights.length; index++) {
  19159. if (this.lights[index].name === name) {
  19160. return this.lights[index];
  19161. }
  19162. }
  19163. return null;
  19164. };
  19165. /**
  19166. * get a light node using its ID
  19167. * @param {string} the light's id
  19168. * @return {BABYLON.Light|null} the light or null if none found.
  19169. */
  19170. Scene.prototype.getLightByID = function (id) {
  19171. for (var index = 0; index < this.lights.length; index++) {
  19172. if (this.lights[index].id === id) {
  19173. return this.lights[index];
  19174. }
  19175. }
  19176. return null;
  19177. };
  19178. /**
  19179. * get a light node using its scene-generated unique ID
  19180. * @param {number} the light's unique id
  19181. * @return {BABYLON.Light|null} the light or null if none found.
  19182. */
  19183. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19184. for (var index = 0; index < this.lights.length; index++) {
  19185. if (this.lights[index].uniqueId === uniqueId) {
  19186. return this.lights[index];
  19187. }
  19188. }
  19189. return null;
  19190. };
  19191. /**
  19192. * get a particle system by id
  19193. * @param id {number} the particle system id
  19194. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19195. */
  19196. Scene.prototype.getParticleSystemByID = function (id) {
  19197. for (var index = 0; index < this.particleSystems.length; index++) {
  19198. if (this.particleSystems[index].id === id) {
  19199. return this.particleSystems[index];
  19200. }
  19201. }
  19202. return null;
  19203. };
  19204. /**
  19205. * get a geometry using its ID
  19206. * @param {string} the geometry's id
  19207. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19208. */
  19209. Scene.prototype.getGeometryByID = function (id) {
  19210. for (var index = 0; index < this._geometries.length; index++) {
  19211. if (this._geometries[index].id === id) {
  19212. return this._geometries[index];
  19213. }
  19214. }
  19215. return null;
  19216. };
  19217. /**
  19218. * add a new geometry to this scene.
  19219. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19220. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19221. * @return {boolean} was the geometry added or not
  19222. */
  19223. Scene.prototype.pushGeometry = function (geometry, force) {
  19224. if (!force && this.getGeometryByID(geometry.id)) {
  19225. return false;
  19226. }
  19227. this._geometries.push(geometry);
  19228. //notify the collision coordinator
  19229. if (this.collisionCoordinator) {
  19230. this.collisionCoordinator.onGeometryAdded(geometry);
  19231. }
  19232. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19233. return true;
  19234. };
  19235. /**
  19236. * Removes an existing geometry
  19237. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19238. * @return {boolean} was the geometry removed or not
  19239. */
  19240. Scene.prototype.removeGeometry = function (geometry) {
  19241. var index = this._geometries.indexOf(geometry);
  19242. if (index > -1) {
  19243. this._geometries.splice(index, 1);
  19244. //notify the collision coordinator
  19245. if (this.collisionCoordinator) {
  19246. this.collisionCoordinator.onGeometryDeleted(geometry);
  19247. }
  19248. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19249. return true;
  19250. }
  19251. return false;
  19252. };
  19253. Scene.prototype.getGeometries = function () {
  19254. return this._geometries;
  19255. };
  19256. /**
  19257. * Get the first added mesh found of a given ID
  19258. * @param {string} id - the id to search for
  19259. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19260. */
  19261. Scene.prototype.getMeshByID = function (id) {
  19262. for (var index = 0; index < this.meshes.length; index++) {
  19263. if (this.meshes[index].id === id) {
  19264. return this.meshes[index];
  19265. }
  19266. }
  19267. return null;
  19268. };
  19269. Scene.prototype.getMeshesByID = function (id) {
  19270. return this.meshes.filter(function (m) {
  19271. return m.id === id;
  19272. });
  19273. };
  19274. /**
  19275. * Get a mesh with its auto-generated unique id
  19276. * @param {number} uniqueId - the unique id to search for
  19277. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19278. */
  19279. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19280. for (var index = 0; index < this.meshes.length; index++) {
  19281. if (this.meshes[index].uniqueId === uniqueId) {
  19282. return this.meshes[index];
  19283. }
  19284. }
  19285. return null;
  19286. };
  19287. /**
  19288. * Get a the last added mesh found of a given ID
  19289. * @param {string} id - the id to search for
  19290. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19291. */
  19292. Scene.prototype.getLastMeshByID = function (id) {
  19293. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19294. if (this.meshes[index].id === id) {
  19295. return this.meshes[index];
  19296. }
  19297. }
  19298. return null;
  19299. };
  19300. /**
  19301. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19302. * @param {string} id - the id to search for
  19303. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19304. */
  19305. Scene.prototype.getLastEntryByID = function (id) {
  19306. var index;
  19307. for (index = this.meshes.length - 1; index >= 0; index--) {
  19308. if (this.meshes[index].id === id) {
  19309. return this.meshes[index];
  19310. }
  19311. }
  19312. for (index = this.cameras.length - 1; index >= 0; index--) {
  19313. if (this.cameras[index].id === id) {
  19314. return this.cameras[index];
  19315. }
  19316. }
  19317. for (index = this.lights.length - 1; index >= 0; index--) {
  19318. if (this.lights[index].id === id) {
  19319. return this.lights[index];
  19320. }
  19321. }
  19322. return null;
  19323. };
  19324. Scene.prototype.getNodeByID = function (id) {
  19325. var mesh = this.getMeshByID(id);
  19326. if (mesh) {
  19327. return mesh;
  19328. }
  19329. var light = this.getLightByID(id);
  19330. if (light) {
  19331. return light;
  19332. }
  19333. var camera = this.getCameraByID(id);
  19334. if (camera) {
  19335. return camera;
  19336. }
  19337. var bone = this.getBoneByID(id);
  19338. return bone;
  19339. };
  19340. Scene.prototype.getNodeByName = function (name) {
  19341. var mesh = this.getMeshByName(name);
  19342. if (mesh) {
  19343. return mesh;
  19344. }
  19345. var light = this.getLightByName(name);
  19346. if (light) {
  19347. return light;
  19348. }
  19349. var camera = this.getCameraByName(name);
  19350. if (camera) {
  19351. return camera;
  19352. }
  19353. var bone = this.getBoneByName(name);
  19354. return bone;
  19355. };
  19356. Scene.prototype.getMeshByName = function (name) {
  19357. for (var index = 0; index < this.meshes.length; index++) {
  19358. if (this.meshes[index].name === name) {
  19359. return this.meshes[index];
  19360. }
  19361. }
  19362. return null;
  19363. };
  19364. Scene.prototype.getSoundByName = function (name) {
  19365. var index;
  19366. if (BABYLON.AudioEngine) {
  19367. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19368. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19369. return this.mainSoundTrack.soundCollection[index];
  19370. }
  19371. }
  19372. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19373. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19374. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19375. return this.soundTracks[sdIndex].soundCollection[index];
  19376. }
  19377. }
  19378. }
  19379. }
  19380. return null;
  19381. };
  19382. Scene.prototype.getLastSkeletonByID = function (id) {
  19383. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19384. if (this.skeletons[index].id === id) {
  19385. return this.skeletons[index];
  19386. }
  19387. }
  19388. return null;
  19389. };
  19390. Scene.prototype.getSkeletonById = function (id) {
  19391. for (var index = 0; index < this.skeletons.length; index++) {
  19392. if (this.skeletons[index].id === id) {
  19393. return this.skeletons[index];
  19394. }
  19395. }
  19396. return null;
  19397. };
  19398. Scene.prototype.getSkeletonByName = function (name) {
  19399. for (var index = 0; index < this.skeletons.length; index++) {
  19400. if (this.skeletons[index].name === name) {
  19401. return this.skeletons[index];
  19402. }
  19403. }
  19404. return null;
  19405. };
  19406. Scene.prototype.getMorphTargetManagerById = function (id) {
  19407. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19408. if (this.morphTargetManagers[index].uniqueId === id) {
  19409. return this.morphTargetManagers[index];
  19410. }
  19411. }
  19412. return null;
  19413. };
  19414. Scene.prototype.isActiveMesh = function (mesh) {
  19415. return (this._activeMeshes.indexOf(mesh) !== -1);
  19416. };
  19417. /**
  19418. * Return a the first highlight layer of the scene with a given name.
  19419. * @param name The name of the highlight layer to look for.
  19420. * @return The highlight layer if found otherwise null.
  19421. */
  19422. Scene.prototype.getHighlightLayerByName = function (name) {
  19423. for (var index = 0; index < this.highlightLayers.length; index++) {
  19424. if (this.highlightLayers[index].name === name) {
  19425. return this.highlightLayers[index];
  19426. }
  19427. }
  19428. return null;
  19429. };
  19430. Object.defineProperty(Scene.prototype, "uid", {
  19431. /**
  19432. * Return a unique id as a string which can serve as an identifier for the scene
  19433. */
  19434. get: function () {
  19435. if (!this._uid) {
  19436. this._uid = BABYLON.Tools.RandomId();
  19437. }
  19438. return this._uid;
  19439. },
  19440. enumerable: true,
  19441. configurable: true
  19442. });
  19443. /**
  19444. * Add an externaly attached data from its key.
  19445. * This method call will fail and return false, if such key already exists.
  19446. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19447. * @param key the unique key that identifies the data
  19448. * @param data the data object to associate to the key for this Engine instance
  19449. * @return true if no such key were already present and the data was added successfully, false otherwise
  19450. */
  19451. Scene.prototype.addExternalData = function (key, data) {
  19452. if (!this._externalData) {
  19453. this._externalData = new BABYLON.StringDictionary();
  19454. }
  19455. return this._externalData.add(key, data);
  19456. };
  19457. /**
  19458. * Get an externaly attached data from its key
  19459. * @param key the unique key that identifies the data
  19460. * @return the associated data, if present (can be null), or undefined if not present
  19461. */
  19462. Scene.prototype.getExternalData = function (key) {
  19463. if (!this._externalData) {
  19464. return null;
  19465. }
  19466. return this._externalData.get(key);
  19467. };
  19468. /**
  19469. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19470. * @param key the unique key that identifies the data
  19471. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19472. * @return the associated data, can be null if the factory returned null.
  19473. */
  19474. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19475. if (!this._externalData) {
  19476. this._externalData = new BABYLON.StringDictionary();
  19477. }
  19478. return this._externalData.getOrAddWithFactory(key, factory);
  19479. };
  19480. /**
  19481. * Remove an externaly attached data from the Engine instance
  19482. * @param key the unique key that identifies the data
  19483. * @return true if the data was successfully removed, false if it doesn't exist
  19484. */
  19485. Scene.prototype.removeExternalData = function (key) {
  19486. return this._externalData.remove(key);
  19487. };
  19488. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19489. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19490. var material = subMesh.getMaterial();
  19491. if (mesh.showSubMeshesBoundingBox) {
  19492. var boundingInfo = subMesh.getBoundingInfo();
  19493. if (boundingInfo) {
  19494. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19495. }
  19496. }
  19497. if (material) {
  19498. // Render targets
  19499. if (material.getRenderTargetTextures) {
  19500. if (this._processedMaterials.indexOf(material) === -1) {
  19501. this._processedMaterials.push(material);
  19502. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19503. }
  19504. }
  19505. // Dispatch
  19506. this._activeIndices.addCount(subMesh.indexCount, false);
  19507. this._renderingManager.dispatch(subMesh);
  19508. }
  19509. }
  19510. };
  19511. Scene.prototype._isInIntermediateRendering = function () {
  19512. return this._intermediateRendering;
  19513. };
  19514. /**
  19515. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19516. */
  19517. Scene.prototype.freezeActiveMeshes = function () {
  19518. this._evaluateActiveMeshes();
  19519. this._activeMeshesFrozen = true;
  19520. return this;
  19521. };
  19522. /**
  19523. * Use this function to restart evaluating active meshes on every frame
  19524. */
  19525. Scene.prototype.unfreezeActiveMeshes = function () {
  19526. this._activeMeshesFrozen = false;
  19527. return this;
  19528. };
  19529. Scene.prototype._evaluateActiveMeshes = function () {
  19530. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19531. return;
  19532. }
  19533. if (!this.activeCamera) {
  19534. return;
  19535. }
  19536. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  19537. this.activeCamera._activeMeshes.reset();
  19538. this._activeMeshes.reset();
  19539. this._renderingManager.reset();
  19540. this._processedMaterials.reset();
  19541. this._activeParticleSystems.reset();
  19542. this._activeSkeletons.reset();
  19543. this._softwareSkinnedMeshes.reset();
  19544. if (this._boundingBoxRenderer) {
  19545. this._boundingBoxRenderer.reset();
  19546. }
  19547. // Meshes
  19548. var meshes;
  19549. var len;
  19550. if (this._selectionOctree) {
  19551. var selection = this._selectionOctree.select(this._frustumPlanes);
  19552. meshes = selection.data;
  19553. len = selection.length;
  19554. }
  19555. else {
  19556. len = this.meshes.length;
  19557. meshes = this.meshes;
  19558. }
  19559. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19560. var mesh = meshes[meshIndex];
  19561. if (mesh.isBlocked) {
  19562. continue;
  19563. }
  19564. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19565. if (!mesh.isReady() || !mesh.isEnabled()) {
  19566. continue;
  19567. }
  19568. mesh.computeWorldMatrix();
  19569. // Intersections
  19570. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19571. this._meshesForIntersections.pushNoDuplicate(mesh);
  19572. }
  19573. // Switch to current LOD
  19574. var meshLOD = mesh.getLOD(this.activeCamera);
  19575. if (!meshLOD) {
  19576. continue;
  19577. }
  19578. mesh._preActivate();
  19579. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19580. this._activeMeshes.push(mesh);
  19581. this.activeCamera._activeMeshes.push(mesh);
  19582. mesh._activate(this._renderId);
  19583. if (meshLOD !== mesh) {
  19584. meshLOD._activate(this._renderId);
  19585. }
  19586. this._activeMesh(mesh, meshLOD);
  19587. }
  19588. }
  19589. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  19590. // Particle systems
  19591. this._particlesDuration.beginMonitoring();
  19592. if (this.particlesEnabled) {
  19593. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  19594. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19595. var particleSystem = this.particleSystems[particleIndex];
  19596. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19597. continue;
  19598. }
  19599. var emitter = particleSystem.emitter;
  19600. if (!emitter.position || emitter.isEnabled()) {
  19601. this._activeParticleSystems.push(particleSystem);
  19602. particleSystem.animate();
  19603. this._renderingManager.dispatchParticles(particleSystem);
  19604. }
  19605. }
  19606. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  19607. }
  19608. this._particlesDuration.endMonitoring(false);
  19609. };
  19610. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19611. if (mesh.skeleton && this.skeletonsEnabled) {
  19612. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19613. mesh.skeleton.prepare();
  19614. }
  19615. if (!mesh.computeBonesUsingShaders) {
  19616. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19617. }
  19618. }
  19619. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19620. var boundingInfo = sourceMesh.getBoundingInfo();
  19621. if (boundingInfo) {
  19622. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19623. }
  19624. }
  19625. if (mesh && mesh.subMeshes) {
  19626. // Submeshes Octrees
  19627. var len;
  19628. var subMeshes;
  19629. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19630. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19631. len = intersections.length;
  19632. subMeshes = intersections.data;
  19633. }
  19634. else {
  19635. subMeshes = mesh.subMeshes;
  19636. len = subMeshes.length;
  19637. }
  19638. for (var subIndex = 0; subIndex < len; subIndex++) {
  19639. var subMesh = subMeshes[subIndex];
  19640. this._evaluateSubMesh(subMesh, mesh);
  19641. }
  19642. }
  19643. };
  19644. Scene.prototype.updateTransformMatrix = function (force) {
  19645. if (!this.activeCamera) {
  19646. return;
  19647. }
  19648. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19649. };
  19650. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19651. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19652. };
  19653. Scene.prototype._renderForCamera = function (camera) {
  19654. if (camera && camera._skipRendering) {
  19655. return;
  19656. }
  19657. var engine = this._engine;
  19658. this.activeCamera = camera;
  19659. if (!this.activeCamera)
  19660. throw new Error("Active camera not set");
  19661. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19662. // Viewport
  19663. engine.setViewport(this.activeCamera.viewport);
  19664. // Camera
  19665. this.resetCachedMaterial();
  19666. this._renderId++;
  19667. this.activeCamera.update();
  19668. this.updateTransformMatrix();
  19669. if (camera._alternateCamera) {
  19670. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19671. this._alternateRendering = true;
  19672. }
  19673. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19674. // Meshes
  19675. this._evaluateActiveMeshes();
  19676. // Software skinning
  19677. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19678. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19679. mesh.applySkeleton(mesh.skeleton);
  19680. }
  19681. // Render targets
  19682. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19683. var needsRestoreFrameBuffer = false;
  19684. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19685. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19686. }
  19687. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19688. this._intermediateRendering = true;
  19689. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19690. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19691. var renderTarget = this._renderTargets.data[renderIndex];
  19692. if (renderTarget._shouldRender()) {
  19693. this._renderId++;
  19694. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19695. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19696. }
  19697. }
  19698. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19699. this._intermediateRendering = false;
  19700. this._renderId++;
  19701. needsRestoreFrameBuffer = true; // Restore back buffer
  19702. }
  19703. // Render HighlightLayer Texture
  19704. var stencilState = this._engine.getStencilBuffer();
  19705. var renderhighlights = false;
  19706. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19707. this._intermediateRendering = true;
  19708. for (var i = 0; i < this.highlightLayers.length; i++) {
  19709. var highlightLayer = this.highlightLayers[i];
  19710. if (highlightLayer.shouldRender() &&
  19711. (!highlightLayer.camera ||
  19712. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19713. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19714. renderhighlights = true;
  19715. var renderTarget = highlightLayer._mainTexture;
  19716. if (renderTarget._shouldRender()) {
  19717. this._renderId++;
  19718. renderTarget.render(false, false);
  19719. needsRestoreFrameBuffer = true;
  19720. }
  19721. }
  19722. }
  19723. this._intermediateRendering = false;
  19724. this._renderId++;
  19725. }
  19726. if (needsRestoreFrameBuffer) {
  19727. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19728. }
  19729. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19730. // Prepare Frame
  19731. this.postProcessManager._prepareFrame();
  19732. this._renderDuration.beginMonitoring();
  19733. // Backgrounds
  19734. var layerIndex;
  19735. var layer;
  19736. if (this.layers.length) {
  19737. engine.setDepthBuffer(false);
  19738. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19739. layer = this.layers[layerIndex];
  19740. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19741. layer.render();
  19742. }
  19743. }
  19744. engine.setDepthBuffer(true);
  19745. }
  19746. // Render
  19747. BABYLON.Tools.StartPerformanceCounter("Main render");
  19748. // Activate HighlightLayer stencil
  19749. if (renderhighlights) {
  19750. this._engine.setStencilBuffer(true);
  19751. }
  19752. this._renderingManager.render(null, null, true, true);
  19753. // Restore HighlightLayer stencil
  19754. if (renderhighlights) {
  19755. this._engine.setStencilBuffer(stencilState);
  19756. }
  19757. BABYLON.Tools.EndPerformanceCounter("Main render");
  19758. // Bounding boxes
  19759. if (this._boundingBoxRenderer) {
  19760. this._boundingBoxRenderer.render();
  19761. }
  19762. // Lens flares
  19763. if (this.lensFlaresEnabled) {
  19764. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19765. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19766. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19767. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19768. lensFlareSystem.render();
  19769. }
  19770. }
  19771. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19772. }
  19773. // Foregrounds
  19774. if (this.layers.length) {
  19775. engine.setDepthBuffer(false);
  19776. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19777. layer = this.layers[layerIndex];
  19778. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19779. layer.render();
  19780. }
  19781. }
  19782. engine.setDepthBuffer(true);
  19783. }
  19784. // Highlight Layer
  19785. if (renderhighlights) {
  19786. engine.setDepthBuffer(false);
  19787. for (var i = 0; i < this.highlightLayers.length; i++) {
  19788. if (this.highlightLayers[i].shouldRender()) {
  19789. this.highlightLayers[i].render();
  19790. }
  19791. }
  19792. engine.setDepthBuffer(true);
  19793. }
  19794. this._renderDuration.endMonitoring(false);
  19795. // Finalize frame
  19796. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19797. // Reset some special arrays
  19798. this._renderTargets.reset();
  19799. this._alternateRendering = false;
  19800. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19801. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19802. };
  19803. Scene.prototype._processSubCameras = function (camera) {
  19804. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19805. this._renderForCamera(camera);
  19806. return;
  19807. }
  19808. // Update camera
  19809. if (this.activeCamera) {
  19810. this.activeCamera.update();
  19811. }
  19812. // rig cameras
  19813. for (var index = 0; index < camera._rigCameras.length; index++) {
  19814. this._renderForCamera(camera._rigCameras[index]);
  19815. }
  19816. this.activeCamera = camera;
  19817. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19818. };
  19819. Scene.prototype._checkIntersections = function () {
  19820. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19821. var sourceMesh = this._meshesForIntersections.data[index];
  19822. if (!sourceMesh.actionManager) {
  19823. continue;
  19824. }
  19825. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19826. var action = sourceMesh.actionManager.actions[actionIndex];
  19827. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19828. var parameters = action.getTriggerParameter();
  19829. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19830. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19831. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19832. if (areIntersecting && currentIntersectionInProgress === -1) {
  19833. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19834. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19835. sourceMesh._intersectionsInProgress.push(otherMesh);
  19836. }
  19837. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19838. sourceMesh._intersectionsInProgress.push(otherMesh);
  19839. }
  19840. }
  19841. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19842. //They intersected, and now they don't.
  19843. //is this trigger an exit trigger? execute an event.
  19844. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19845. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19846. }
  19847. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19848. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19849. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19850. }
  19851. }
  19852. }
  19853. }
  19854. }
  19855. };
  19856. Scene.prototype.render = function () {
  19857. if (this.isDisposed) {
  19858. return;
  19859. }
  19860. this._interFrameDuration.endMonitoring();
  19861. this._particlesDuration.fetchNewFrame();
  19862. this._spritesDuration.fetchNewFrame();
  19863. this._activeParticles.fetchNewFrame();
  19864. this._renderDuration.fetchNewFrame();
  19865. this._totalVertices.fetchNewFrame();
  19866. this._activeIndices.fetchNewFrame();
  19867. this._activeBones.fetchNewFrame();
  19868. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19869. this._meshesForIntersections.reset();
  19870. this.resetCachedMaterial();
  19871. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19872. // Actions
  19873. if (this.actionManager) {
  19874. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  19875. }
  19876. //Simplification Queue
  19877. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19878. this.simplificationQueue.executeNext();
  19879. }
  19880. if (this._engine.isDeterministicLockStep()) {
  19881. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19882. var defaultTimeStep = (60.0 / 1000.0);
  19883. if (this._physicsEngine) {
  19884. defaultTimeStep = this._physicsEngine.getTimeStep();
  19885. }
  19886. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19887. this._timeAccumulator += deltaTime;
  19888. // compute the amount of fixed steps we should have taken since the last step
  19889. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19890. internalSteps = Math.min(internalSteps, maxSubSteps);
  19891. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19892. this.onBeforeStepObservable.notifyObservers(this);
  19893. // Animations
  19894. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19895. this._animate();
  19896. // Physics
  19897. if (this._physicsEngine) {
  19898. BABYLON.Tools.StartPerformanceCounter("Physics");
  19899. this._physicsEngine._step(defaultTimeStep);
  19900. BABYLON.Tools.EndPerformanceCounter("Physics");
  19901. }
  19902. this._timeAccumulator -= defaultTimeStep;
  19903. this.onAfterStepObservable.notifyObservers(this);
  19904. this._currentStepId++;
  19905. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19906. this._evaluateActiveMeshes();
  19907. }
  19908. }
  19909. }
  19910. else {
  19911. // Animations
  19912. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19913. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19914. this._animate();
  19915. // Physics
  19916. if (this._physicsEngine) {
  19917. BABYLON.Tools.StartPerformanceCounter("Physics");
  19918. this._physicsEngine._step(deltaTime / 1000.0);
  19919. BABYLON.Tools.EndPerformanceCounter("Physics");
  19920. }
  19921. }
  19922. // Before render
  19923. this.onBeforeRenderObservable.notifyObservers(this);
  19924. // Customs render targets
  19925. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19926. var engine = this.getEngine();
  19927. var currentActiveCamera = this.activeCamera;
  19928. if (this.renderTargetsEnabled) {
  19929. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19930. this._intermediateRendering = true;
  19931. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19932. var renderTarget = this.customRenderTargets[customIndex];
  19933. if (renderTarget._shouldRender()) {
  19934. this._renderId++;
  19935. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19936. if (!this.activeCamera)
  19937. throw new Error("Active camera not set");
  19938. // Viewport
  19939. engine.setViewport(this.activeCamera.viewport);
  19940. // Camera
  19941. this.updateTransformMatrix();
  19942. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19943. }
  19944. }
  19945. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19946. this._intermediateRendering = false;
  19947. this._renderId++;
  19948. }
  19949. // Restore back buffer
  19950. if (this.customRenderTargets.length > 0) {
  19951. engine.restoreDefaultFramebuffer();
  19952. }
  19953. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19954. this.activeCamera = currentActiveCamera;
  19955. // Procedural textures
  19956. if (this.proceduralTexturesEnabled) {
  19957. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19958. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19959. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19960. if (proceduralTexture._shouldRender()) {
  19961. proceduralTexture.render();
  19962. }
  19963. }
  19964. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19965. }
  19966. // Clear
  19967. if (this.autoClearDepthAndStencil || this.autoClear) {
  19968. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19969. }
  19970. // Shadows
  19971. if (this.shadowsEnabled) {
  19972. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19973. var light = this.lights[lightIndex];
  19974. var shadowGenerator = light.getShadowGenerator();
  19975. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19976. var shadowMap = (shadowGenerator.getShadowMap());
  19977. if (this.textures.indexOf(shadowMap) !== -1) {
  19978. this._renderTargets.push(shadowMap);
  19979. }
  19980. }
  19981. }
  19982. }
  19983. // Depth renderer
  19984. if (this._depthRenderer) {
  19985. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19986. }
  19987. // Geometry renderer
  19988. if (this._geometryBufferRenderer) {
  19989. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19990. }
  19991. // RenderPipeline
  19992. if (this._postProcessRenderPipelineManager) {
  19993. this._postProcessRenderPipelineManager.update();
  19994. }
  19995. // Multi-cameras?
  19996. if (this.activeCameras.length > 0) {
  19997. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19998. if (cameraIndex > 0) {
  19999. this._engine.clear(null, false, true, true);
  20000. }
  20001. this._processSubCameras(this.activeCameras[cameraIndex]);
  20002. }
  20003. }
  20004. else {
  20005. if (!this.activeCamera) {
  20006. throw new Error("No camera defined");
  20007. }
  20008. this._processSubCameras(this.activeCamera);
  20009. }
  20010. // Intersection checks
  20011. this._checkIntersections();
  20012. // Update the audio listener attached to the camera
  20013. if (BABYLON.AudioEngine) {
  20014. this._updateAudioParameters();
  20015. }
  20016. // After render
  20017. if (this.afterRender) {
  20018. this.afterRender();
  20019. }
  20020. this.onAfterRenderObservable.notifyObservers(this);
  20021. // Cleaning
  20022. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20023. var data = this._toBeDisposed.data[index];
  20024. if (data) {
  20025. data.dispose();
  20026. }
  20027. this._toBeDisposed[index] = null;
  20028. }
  20029. this._toBeDisposed.reset();
  20030. if (this.dumpNextRenderTargets) {
  20031. this.dumpNextRenderTargets = false;
  20032. }
  20033. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  20034. this._interFrameDuration.beginMonitoring();
  20035. this._activeBones.addCount(0, true);
  20036. this._activeIndices.addCount(0, true);
  20037. this._activeParticles.addCount(0, true);
  20038. };
  20039. Scene.prototype._updateAudioParameters = function () {
  20040. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20041. return;
  20042. }
  20043. var listeningCamera;
  20044. var audioEngine = BABYLON.Engine.audioEngine;
  20045. if (this.activeCameras.length > 0) {
  20046. listeningCamera = this.activeCameras[0];
  20047. }
  20048. else {
  20049. listeningCamera = this.activeCamera;
  20050. }
  20051. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20052. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20053. // for VR cameras
  20054. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20055. listeningCamera = listeningCamera.rigCameras[0];
  20056. }
  20057. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20058. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20059. cameraDirection.normalize();
  20060. // To avoid some errors on GearVR
  20061. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20062. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20063. }
  20064. var i;
  20065. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20066. var sound = this.mainSoundTrack.soundCollection[i];
  20067. if (sound.useCustomAttenuation) {
  20068. sound.updateDistanceFromListener();
  20069. }
  20070. }
  20071. for (i = 0; i < this.soundTracks.length; i++) {
  20072. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20073. sound = this.soundTracks[i].soundCollection[j];
  20074. if (sound.useCustomAttenuation) {
  20075. sound.updateDistanceFromListener();
  20076. }
  20077. }
  20078. }
  20079. }
  20080. };
  20081. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20082. // Audio
  20083. get: function () {
  20084. return this._audioEnabled;
  20085. },
  20086. set: function (value) {
  20087. this._audioEnabled = value;
  20088. if (BABYLON.AudioEngine) {
  20089. if (this._audioEnabled) {
  20090. this._enableAudio();
  20091. }
  20092. else {
  20093. this._disableAudio();
  20094. }
  20095. }
  20096. },
  20097. enumerable: true,
  20098. configurable: true
  20099. });
  20100. Scene.prototype._disableAudio = function () {
  20101. var i;
  20102. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20103. this.mainSoundTrack.soundCollection[i].pause();
  20104. }
  20105. for (i = 0; i < this.soundTracks.length; i++) {
  20106. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20107. this.soundTracks[i].soundCollection[j].pause();
  20108. }
  20109. }
  20110. };
  20111. Scene.prototype._enableAudio = function () {
  20112. var i;
  20113. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20114. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20115. this.mainSoundTrack.soundCollection[i].play();
  20116. }
  20117. }
  20118. for (i = 0; i < this.soundTracks.length; i++) {
  20119. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20120. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20121. this.soundTracks[i].soundCollection[j].play();
  20122. }
  20123. }
  20124. }
  20125. };
  20126. Object.defineProperty(Scene.prototype, "headphone", {
  20127. get: function () {
  20128. return this._headphone;
  20129. },
  20130. set: function (value) {
  20131. this._headphone = value;
  20132. if (BABYLON.AudioEngine) {
  20133. if (this._headphone) {
  20134. this._switchAudioModeForHeadphones();
  20135. }
  20136. else {
  20137. this._switchAudioModeForNormalSpeakers();
  20138. }
  20139. }
  20140. },
  20141. enumerable: true,
  20142. configurable: true
  20143. });
  20144. Scene.prototype._switchAudioModeForHeadphones = function () {
  20145. this.mainSoundTrack.switchPanningModelToHRTF();
  20146. for (var i = 0; i < this.soundTracks.length; i++) {
  20147. this.soundTracks[i].switchPanningModelToHRTF();
  20148. }
  20149. };
  20150. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20151. this.mainSoundTrack.switchPanningModelToEqualPower();
  20152. for (var i = 0; i < this.soundTracks.length; i++) {
  20153. this.soundTracks[i].switchPanningModelToEqualPower();
  20154. }
  20155. };
  20156. Scene.prototype.enableDepthRenderer = function () {
  20157. if (this._depthRenderer) {
  20158. return this._depthRenderer;
  20159. }
  20160. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20161. return this._depthRenderer;
  20162. };
  20163. Scene.prototype.disableDepthRenderer = function () {
  20164. if (!this._depthRenderer) {
  20165. return;
  20166. }
  20167. this._depthRenderer.dispose();
  20168. this._depthRenderer = null;
  20169. };
  20170. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20171. if (ratio === void 0) { ratio = 1; }
  20172. if (this._geometryBufferRenderer) {
  20173. return this._geometryBufferRenderer;
  20174. }
  20175. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20176. if (!this._geometryBufferRenderer.isSupported) {
  20177. this._geometryBufferRenderer = null;
  20178. }
  20179. return this._geometryBufferRenderer;
  20180. };
  20181. Scene.prototype.disableGeometryBufferRenderer = function () {
  20182. if (!this._geometryBufferRenderer) {
  20183. return;
  20184. }
  20185. this._geometryBufferRenderer.dispose();
  20186. this._geometryBufferRenderer = null;
  20187. };
  20188. Scene.prototype.freezeMaterials = function () {
  20189. for (var i = 0; i < this.materials.length; i++) {
  20190. this.materials[i].freeze();
  20191. }
  20192. };
  20193. Scene.prototype.unfreezeMaterials = function () {
  20194. for (var i = 0; i < this.materials.length; i++) {
  20195. this.materials[i].unfreeze();
  20196. }
  20197. };
  20198. Scene.prototype.dispose = function () {
  20199. this.beforeRender = null;
  20200. this.afterRender = null;
  20201. this.skeletons = [];
  20202. this.morphTargetManagers = [];
  20203. this.importedMeshesFiles = new Array();
  20204. this.resetCachedMaterial();
  20205. if (this._depthRenderer) {
  20206. this._depthRenderer.dispose();
  20207. }
  20208. if (this._gamepadManager) {
  20209. this._gamepadManager.dispose();
  20210. this._gamepadManager = null;
  20211. }
  20212. // Smart arrays
  20213. if (this.activeCamera) {
  20214. this.activeCamera._activeMeshes.dispose();
  20215. this.activeCamera = null;
  20216. }
  20217. this._activeMeshes.dispose();
  20218. this._renderingManager.dispose();
  20219. this._processedMaterials.dispose();
  20220. this._activeParticleSystems.dispose();
  20221. this._activeSkeletons.dispose();
  20222. this._softwareSkinnedMeshes.dispose();
  20223. this._renderTargets.dispose();
  20224. if (this._boundingBoxRenderer) {
  20225. this._boundingBoxRenderer.dispose();
  20226. }
  20227. this._meshesForIntersections.dispose();
  20228. this._toBeDisposed.dispose();
  20229. // Debug layer
  20230. if (this._debugLayer) {
  20231. this._debugLayer.hide();
  20232. }
  20233. // Events
  20234. this.onDisposeObservable.notifyObservers(this);
  20235. this.onDisposeObservable.clear();
  20236. this.onBeforeRenderObservable.clear();
  20237. this.onAfterRenderObservable.clear();
  20238. this.OnBeforeRenderTargetsRenderObservable.clear();
  20239. this.OnAfterRenderTargetsRenderObservable.clear();
  20240. this.onAfterStepObservable.clear();
  20241. this.onBeforeStepObservable.clear();
  20242. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20243. this.onAfterActiveMeshesEvaluationObservable.clear();
  20244. this.detachControl();
  20245. // Release sounds & sounds tracks
  20246. if (BABYLON.AudioEngine) {
  20247. this.disposeSounds();
  20248. }
  20249. // VR Helper
  20250. if (this.VRHelper) {
  20251. this.VRHelper.dispose();
  20252. }
  20253. // Detach cameras
  20254. var canvas = this._engine.getRenderingCanvas();
  20255. if (canvas) {
  20256. var index;
  20257. for (index = 0; index < this.cameras.length; index++) {
  20258. this.cameras[index].detachControl(canvas);
  20259. }
  20260. }
  20261. // Release lights
  20262. while (this.lights.length) {
  20263. this.lights[0].dispose();
  20264. }
  20265. // Release meshes
  20266. while (this.meshes.length) {
  20267. this.meshes[0].dispose(true);
  20268. }
  20269. // Release cameras
  20270. while (this.cameras.length) {
  20271. this.cameras[0].dispose();
  20272. }
  20273. // Release materials
  20274. if (this.defaultMaterial) {
  20275. this.defaultMaterial.dispose();
  20276. }
  20277. while (this.multiMaterials.length) {
  20278. this.multiMaterials[0].dispose();
  20279. }
  20280. while (this.materials.length) {
  20281. this.materials[0].dispose();
  20282. }
  20283. // Release particles
  20284. while (this.particleSystems.length) {
  20285. this.particleSystems[0].dispose();
  20286. }
  20287. // Release sprites
  20288. while (this.spriteManagers.length) {
  20289. this.spriteManagers[0].dispose();
  20290. }
  20291. // Release postProcesses
  20292. while (this.postProcesses.length) {
  20293. this.postProcesses[0].dispose();
  20294. }
  20295. // Release layers
  20296. while (this.layers.length) {
  20297. this.layers[0].dispose();
  20298. }
  20299. while (this.highlightLayers.length) {
  20300. this.highlightLayers[0].dispose();
  20301. }
  20302. // Release textures
  20303. while (this.textures.length) {
  20304. this.textures[0].dispose();
  20305. }
  20306. // Release UBO
  20307. this._sceneUbo.dispose();
  20308. if (this._alternateSceneUbo) {
  20309. this._alternateSceneUbo.dispose();
  20310. }
  20311. // Post-processes
  20312. this.postProcessManager.dispose();
  20313. if (this._postProcessRenderPipelineManager) {
  20314. this._postProcessRenderPipelineManager.dispose();
  20315. }
  20316. // Physics
  20317. if (this._physicsEngine) {
  20318. this.disablePhysicsEngine();
  20319. }
  20320. // Remove from engine
  20321. index = this._engine.scenes.indexOf(this);
  20322. if (index > -1) {
  20323. this._engine.scenes.splice(index, 1);
  20324. }
  20325. this._engine.wipeCaches();
  20326. this._isDisposed = true;
  20327. };
  20328. Object.defineProperty(Scene.prototype, "isDisposed", {
  20329. get: function () {
  20330. return this._isDisposed;
  20331. },
  20332. enumerable: true,
  20333. configurable: true
  20334. });
  20335. // Release sounds & sounds tracks
  20336. Scene.prototype.disposeSounds = function () {
  20337. if (!this._mainSoundTrack) {
  20338. return;
  20339. }
  20340. this.mainSoundTrack.dispose();
  20341. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20342. this.soundTracks[scIndex].dispose();
  20343. }
  20344. };
  20345. // Octrees
  20346. Scene.prototype.getWorldExtends = function () {
  20347. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20348. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20349. for (var index = 0; index < this.meshes.length; index++) {
  20350. var mesh = this.meshes[index];
  20351. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20352. continue;
  20353. }
  20354. mesh.computeWorldMatrix(true);
  20355. var boundingInfo = mesh.getBoundingInfo();
  20356. if (boundingInfo) {
  20357. var minBox = boundingInfo.boundingBox.minimumWorld;
  20358. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20359. BABYLON.Tools.CheckExtends(minBox, min, max);
  20360. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20361. }
  20362. }
  20363. return {
  20364. min: min,
  20365. max: max
  20366. };
  20367. };
  20368. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20369. if (maxCapacity === void 0) { maxCapacity = 64; }
  20370. if (maxDepth === void 0) { maxDepth = 2; }
  20371. if (!this._selectionOctree) {
  20372. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20373. }
  20374. var worldExtends = this.getWorldExtends();
  20375. // Update octree
  20376. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20377. return this._selectionOctree;
  20378. };
  20379. // Picking
  20380. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20381. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20382. var engine = this._engine;
  20383. if (!camera) {
  20384. if (!this.activeCamera)
  20385. throw new Error("Active camera not set");
  20386. camera = this.activeCamera;
  20387. }
  20388. var cameraViewport = camera.viewport;
  20389. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20390. // Moving coordinates to local viewport world
  20391. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20392. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20393. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20394. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20395. };
  20396. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20397. if (!BABYLON.PickingInfo) {
  20398. return null;
  20399. }
  20400. var engine = this._engine;
  20401. if (!camera) {
  20402. if (!this.activeCamera)
  20403. throw new Error("Active camera not set");
  20404. camera = this.activeCamera;
  20405. }
  20406. var cameraViewport = camera.viewport;
  20407. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20408. var identity = BABYLON.Matrix.Identity();
  20409. // Moving coordinates to local viewport world
  20410. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20411. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20412. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20413. };
  20414. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20415. if (!BABYLON.PickingInfo) {
  20416. return null;
  20417. }
  20418. var pickingInfo = null;
  20419. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20420. var mesh = this.meshes[meshIndex];
  20421. if (predicate) {
  20422. if (!predicate(mesh)) {
  20423. continue;
  20424. }
  20425. }
  20426. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20427. continue;
  20428. }
  20429. var world = mesh.getWorldMatrix();
  20430. var ray = rayFunction(world);
  20431. var result = mesh.intersects(ray, fastCheck);
  20432. if (!result || !result.hit)
  20433. continue;
  20434. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20435. continue;
  20436. pickingInfo = result;
  20437. if (fastCheck) {
  20438. break;
  20439. }
  20440. }
  20441. return pickingInfo || new BABYLON.PickingInfo();
  20442. };
  20443. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20444. if (!BABYLON.PickingInfo) {
  20445. return null;
  20446. }
  20447. var pickingInfos = new Array();
  20448. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20449. var mesh = this.meshes[meshIndex];
  20450. if (predicate) {
  20451. if (!predicate(mesh)) {
  20452. continue;
  20453. }
  20454. }
  20455. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20456. continue;
  20457. }
  20458. var world = mesh.getWorldMatrix();
  20459. var ray = rayFunction(world);
  20460. var result = mesh.intersects(ray, false);
  20461. if (!result || !result.hit)
  20462. continue;
  20463. pickingInfos.push(result);
  20464. }
  20465. return pickingInfos;
  20466. };
  20467. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20468. if (!BABYLON.PickingInfo) {
  20469. return null;
  20470. }
  20471. var pickingInfo = null;
  20472. if (!camera) {
  20473. if (!this.activeCamera) {
  20474. return null;
  20475. }
  20476. camera = this.activeCamera;
  20477. }
  20478. if (this.spriteManagers.length > 0) {
  20479. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20480. var spriteManager = this.spriteManagers[spriteIndex];
  20481. if (!spriteManager.isPickable) {
  20482. continue;
  20483. }
  20484. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20485. if (!result || !result.hit)
  20486. continue;
  20487. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20488. continue;
  20489. pickingInfo = result;
  20490. if (fastCheck) {
  20491. break;
  20492. }
  20493. }
  20494. }
  20495. return pickingInfo || new BABYLON.PickingInfo();
  20496. };
  20497. /** Launch a ray to try to pick a mesh in the scene
  20498. * @param x position on screen
  20499. * @param y position on screen
  20500. * @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
  20501. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20502. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20503. */
  20504. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20505. var _this = this;
  20506. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20507. };
  20508. /** Launch a ray to try to pick a sprite in the scene
  20509. * @param x position on screen
  20510. * @param y position on screen
  20511. * @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
  20512. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20513. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20514. */
  20515. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20516. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20517. if (!ray) {
  20518. return null;
  20519. }
  20520. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20521. };
  20522. /** Use the given ray to pick a mesh in the scene
  20523. * @param ray The ray to use to pick meshes
  20524. * @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
  20525. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20526. */
  20527. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20528. var _this = this;
  20529. return this._internalPick(function (world) {
  20530. if (!_this._pickWithRayInverseMatrix) {
  20531. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20532. }
  20533. world.invertToRef(_this._pickWithRayInverseMatrix);
  20534. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20535. }, predicate, fastCheck);
  20536. };
  20537. /**
  20538. * Launch a ray to try to pick a mesh in the scene
  20539. * @param x X position on screen
  20540. * @param y Y position on screen
  20541. * @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
  20542. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20543. */
  20544. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20545. var _this = this;
  20546. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20547. };
  20548. /**
  20549. * Launch a ray to try to pick a mesh in the scene
  20550. * @param ray Ray to use
  20551. * @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
  20552. */
  20553. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20554. var _this = this;
  20555. return this._internalMultiPick(function (world) {
  20556. if (!_this._pickWithRayInverseMatrix) {
  20557. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20558. }
  20559. world.invertToRef(_this._pickWithRayInverseMatrix);
  20560. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20561. }, predicate);
  20562. };
  20563. Scene.prototype.setPointerOverMesh = function (mesh) {
  20564. if (this._pointerOverMesh === mesh) {
  20565. return;
  20566. }
  20567. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20568. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20569. }
  20570. this._pointerOverMesh = mesh;
  20571. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20572. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20573. }
  20574. };
  20575. Scene.prototype.getPointerOverMesh = function () {
  20576. return this._pointerOverMesh;
  20577. };
  20578. Scene.prototype.setPointerOverSprite = function (sprite) {
  20579. if (this._pointerOverSprite === sprite) {
  20580. return;
  20581. }
  20582. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20583. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20584. }
  20585. this._pointerOverSprite = sprite;
  20586. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20587. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20588. }
  20589. };
  20590. Scene.prototype.getPointerOverSprite = function () {
  20591. return this._pointerOverSprite;
  20592. };
  20593. // Physics
  20594. Scene.prototype.getPhysicsEngine = function () {
  20595. return this._physicsEngine;
  20596. };
  20597. /**
  20598. * Enables physics to the current scene
  20599. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20600. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20601. * @return {boolean} was the physics engine initialized
  20602. */
  20603. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20604. if (gravity === void 0) { gravity = null; }
  20605. if (this._physicsEngine) {
  20606. return true;
  20607. }
  20608. try {
  20609. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20610. return true;
  20611. }
  20612. catch (e) {
  20613. BABYLON.Tools.Error(e.message);
  20614. return false;
  20615. }
  20616. };
  20617. Scene.prototype.disablePhysicsEngine = function () {
  20618. if (!this._physicsEngine) {
  20619. return;
  20620. }
  20621. this._physicsEngine.dispose();
  20622. this._physicsEngine = null;
  20623. };
  20624. Scene.prototype.isPhysicsEnabled = function () {
  20625. return this._physicsEngine !== undefined;
  20626. };
  20627. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20628. var mesh = compound.parts[0].mesh;
  20629. if (mesh.physicsImpostor) {
  20630. mesh.physicsImpostor.dispose();
  20631. mesh.physicsImpostor = null;
  20632. }
  20633. };
  20634. // Misc.
  20635. Scene.prototype._rebuildGeometries = function () {
  20636. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20637. var geometry = _a[_i];
  20638. geometry._rebuild();
  20639. }
  20640. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20641. var mesh = _c[_b];
  20642. mesh._rebuild();
  20643. }
  20644. if (this.postProcessManager) {
  20645. this.postProcessManager._rebuild();
  20646. }
  20647. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20648. var layer = _e[_d];
  20649. layer._rebuild();
  20650. }
  20651. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20652. var highlightLayer = _g[_f];
  20653. highlightLayer._rebuild();
  20654. }
  20655. if (this._boundingBoxRenderer) {
  20656. this._boundingBoxRenderer._rebuild();
  20657. }
  20658. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20659. var system = _j[_h];
  20660. system.rebuild();
  20661. }
  20662. if (this._postProcessRenderPipelineManager) {
  20663. this._postProcessRenderPipelineManager._rebuild();
  20664. }
  20665. };
  20666. Scene.prototype._rebuildTextures = function () {
  20667. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20668. var texture = _a[_i];
  20669. texture._rebuild();
  20670. }
  20671. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20672. };
  20673. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20674. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20675. if (replace === void 0) { replace = false; }
  20676. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20677. // Dispose existing camera or light in replace mode.
  20678. if (replace) {
  20679. if (this.activeCamera) {
  20680. this.activeCamera.dispose();
  20681. this.activeCamera = null;
  20682. }
  20683. if (this.lights) {
  20684. for (var i = 0; i < this.lights.length; i++) {
  20685. this.lights[i].dispose();
  20686. }
  20687. }
  20688. }
  20689. // Light
  20690. if (this.lights.length === 0) {
  20691. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20692. }
  20693. // Camera
  20694. if (!this.activeCamera) {
  20695. var worldExtends = this.getWorldExtends();
  20696. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20697. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20698. var camera;
  20699. var radius = worldSize.length() * 1.5;
  20700. if (createArcRotateCamera) {
  20701. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20702. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20703. arcRotateCamera.wheelPrecision = 100 / radius;
  20704. camera = arcRotateCamera;
  20705. }
  20706. else {
  20707. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20708. freeCamera.setTarget(worldCenter);
  20709. camera = freeCamera;
  20710. }
  20711. camera.minZ = radius * 0.01;
  20712. camera.maxZ = radius * 100;
  20713. camera.speed = radius * 0.2;
  20714. this.activeCamera = camera;
  20715. var canvas = this.getEngine().getRenderingCanvas();
  20716. if (attachCameraControls && canvas) {
  20717. camera.attachControl(canvas);
  20718. }
  20719. }
  20720. };
  20721. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20722. if (pbr === void 0) { pbr = false; }
  20723. if (scale === void 0) { scale = 1000; }
  20724. if (blur === void 0) { blur = 0; }
  20725. if (environmentTexture) {
  20726. this.environmentTexture = environmentTexture;
  20727. }
  20728. if (!this.environmentTexture) {
  20729. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20730. return null;
  20731. }
  20732. // Skybox
  20733. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20734. if (pbr) {
  20735. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20736. hdrSkyboxMaterial.backFaceCulling = false;
  20737. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20738. if (hdrSkyboxMaterial.reflectionTexture) {
  20739. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20740. }
  20741. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20742. hdrSkyboxMaterial.disableLighting = true;
  20743. hdrSkyboxMaterial.twoSidedLighting = true;
  20744. hdrSkybox.infiniteDistance = true;
  20745. hdrSkybox.material = hdrSkyboxMaterial;
  20746. }
  20747. else {
  20748. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20749. skyboxMaterial.backFaceCulling = false;
  20750. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20751. if (skyboxMaterial.reflectionTexture) {
  20752. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20753. }
  20754. skyboxMaterial.disableLighting = true;
  20755. hdrSkybox.infiniteDistance = true;
  20756. hdrSkybox.material = skyboxMaterial;
  20757. }
  20758. return hdrSkybox;
  20759. };
  20760. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20761. if (webVROptions === void 0) { webVROptions = {}; }
  20762. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20763. };
  20764. // Tags
  20765. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20766. if (tagsQuery === undefined) {
  20767. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20768. return list;
  20769. }
  20770. var listByTags = [];
  20771. forEach = forEach || (function (item) { return; });
  20772. for (var i in list) {
  20773. var item = list[i];
  20774. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20775. listByTags.push(item);
  20776. forEach(item);
  20777. }
  20778. }
  20779. return listByTags;
  20780. };
  20781. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20782. return this._getByTags(this.meshes, tagsQuery, forEach);
  20783. };
  20784. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20785. return this._getByTags(this.cameras, tagsQuery, forEach);
  20786. };
  20787. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20788. return this._getByTags(this.lights, tagsQuery, forEach);
  20789. };
  20790. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20791. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20792. };
  20793. /**
  20794. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20795. * This allowed control for front to back rendering or reversly depending of the special needs.
  20796. *
  20797. * @param renderingGroupId The rendering group id corresponding to its index
  20798. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20799. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20800. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20801. */
  20802. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20803. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20804. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20805. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20806. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20807. };
  20808. /**
  20809. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20810. *
  20811. * @param renderingGroupId The rendering group id corresponding to its index
  20812. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20813. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20814. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20815. */
  20816. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20817. if (depth === void 0) { depth = true; }
  20818. if (stencil === void 0) { stencil = true; }
  20819. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20820. };
  20821. /**
  20822. * Will flag all materials as dirty to trigger new shader compilation
  20823. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20824. */
  20825. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20826. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20827. var material = _a[_i];
  20828. if (predicate && !predicate(material)) {
  20829. continue;
  20830. }
  20831. material.markAsDirty(flag);
  20832. }
  20833. };
  20834. // Statics
  20835. Scene._FOGMODE_NONE = 0;
  20836. Scene._FOGMODE_EXP = 1;
  20837. Scene._FOGMODE_EXP2 = 2;
  20838. Scene._FOGMODE_LINEAR = 3;
  20839. Scene._uniqueIdCounter = 0;
  20840. Scene.MinDeltaTime = 1.0;
  20841. Scene.MaxDeltaTime = 1000.0;
  20842. /** The distance in pixel that you have to move to prevent some events */
  20843. Scene.DragMovementThreshold = 10; // in pixels
  20844. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20845. Scene.LongPressDelay = 500; // in milliseconds
  20846. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20847. Scene.DoubleClickDelay = 300; // in milliseconds
  20848. /** If you need to check double click without raising a single click at first click, enable this flag */
  20849. Scene.ExclusiveDoubleClickMode = false;
  20850. return Scene;
  20851. }());
  20852. BABYLON.Scene = Scene;
  20853. })(BABYLON || (BABYLON = {}));
  20854. //# sourceMappingURL=babylon.scene.js.map
  20855. var BABYLON;
  20856. (function (BABYLON) {
  20857. var Buffer = /** @class */ (function () {
  20858. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20859. if (instanced === void 0) { instanced = false; }
  20860. if (engine instanceof BABYLON.Mesh) {
  20861. this._engine = engine.getScene().getEngine();
  20862. }
  20863. else {
  20864. this._engine = engine;
  20865. }
  20866. this._updatable = updatable;
  20867. this._data = data;
  20868. this._strideSize = stride;
  20869. if (!postponeInternalCreation) {
  20870. this.create();
  20871. }
  20872. this._instanced = instanced;
  20873. this._instanceDivisor = instanced ? 1 : 0;
  20874. }
  20875. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20876. // a lot of these parameters are ignored as they are overriden by the buffer
  20877. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20878. };
  20879. // Properties
  20880. Buffer.prototype.isUpdatable = function () {
  20881. return this._updatable;
  20882. };
  20883. Buffer.prototype.getData = function () {
  20884. return this._data;
  20885. };
  20886. Buffer.prototype.getBuffer = function () {
  20887. return this._buffer;
  20888. };
  20889. Buffer.prototype.getStrideSize = function () {
  20890. return this._strideSize;
  20891. };
  20892. Buffer.prototype.getIsInstanced = function () {
  20893. return this._instanced;
  20894. };
  20895. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  20896. get: function () {
  20897. return this._instanceDivisor;
  20898. },
  20899. set: function (value) {
  20900. this._instanceDivisor = value;
  20901. if (value == 0) {
  20902. this._instanced = false;
  20903. }
  20904. else {
  20905. this._instanced = true;
  20906. }
  20907. },
  20908. enumerable: true,
  20909. configurable: true
  20910. });
  20911. // Methods
  20912. Buffer.prototype.create = function (data) {
  20913. if (data === void 0) { data = null; }
  20914. if (!data && this._buffer) {
  20915. return; // nothing to do
  20916. }
  20917. data = data || this._data;
  20918. if (!data) {
  20919. return;
  20920. }
  20921. if (!this._buffer) {
  20922. if (this._updatable) {
  20923. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20924. this._data = data;
  20925. }
  20926. else {
  20927. this._buffer = this._engine.createVertexBuffer(data);
  20928. }
  20929. }
  20930. else if (this._updatable) {
  20931. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20932. this._data = data;
  20933. }
  20934. };
  20935. Buffer.prototype._rebuild = function () {
  20936. this._buffer = null;
  20937. this.create(this._data);
  20938. };
  20939. Buffer.prototype.update = function (data) {
  20940. this.create(data);
  20941. };
  20942. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20943. if (!this._buffer) {
  20944. return;
  20945. }
  20946. if (this._updatable) {
  20947. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20948. this._data = null;
  20949. }
  20950. };
  20951. Buffer.prototype.dispose = function () {
  20952. if (!this._buffer) {
  20953. return;
  20954. }
  20955. if (this._engine._releaseBuffer(this._buffer)) {
  20956. this._buffer = null;
  20957. }
  20958. };
  20959. return Buffer;
  20960. }());
  20961. BABYLON.Buffer = Buffer;
  20962. })(BABYLON || (BABYLON = {}));
  20963. //# sourceMappingURL=babylon.buffer.js.map
  20964. var BABYLON;
  20965. (function (BABYLON) {
  20966. var VertexBuffer = /** @class */ (function () {
  20967. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20968. if (!stride) {
  20969. // Deduce stride from kind
  20970. switch (kind) {
  20971. case VertexBuffer.PositionKind:
  20972. stride = 3;
  20973. break;
  20974. case VertexBuffer.NormalKind:
  20975. stride = 3;
  20976. break;
  20977. case VertexBuffer.UVKind:
  20978. case VertexBuffer.UV2Kind:
  20979. case VertexBuffer.UV3Kind:
  20980. case VertexBuffer.UV4Kind:
  20981. case VertexBuffer.UV5Kind:
  20982. case VertexBuffer.UV6Kind:
  20983. stride = 2;
  20984. break;
  20985. case VertexBuffer.TangentKind:
  20986. case VertexBuffer.ColorKind:
  20987. stride = 4;
  20988. break;
  20989. case VertexBuffer.MatricesIndicesKind:
  20990. case VertexBuffer.MatricesIndicesExtraKind:
  20991. stride = 4;
  20992. break;
  20993. case VertexBuffer.MatricesWeightsKind:
  20994. case VertexBuffer.MatricesWeightsExtraKind:
  20995. default:
  20996. stride = 4;
  20997. break;
  20998. }
  20999. }
  21000. if (data instanceof BABYLON.Buffer) {
  21001. if (!stride) {
  21002. stride = data.getStrideSize();
  21003. }
  21004. this._buffer = data;
  21005. this._ownsBuffer = false;
  21006. }
  21007. else {
  21008. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21009. this._ownsBuffer = true;
  21010. }
  21011. this._stride = stride;
  21012. this._offset = offset ? offset : 0;
  21013. this._size = size ? size : stride;
  21014. this._kind = kind;
  21015. }
  21016. VertexBuffer.prototype._rebuild = function () {
  21017. if (!this._buffer) {
  21018. return;
  21019. }
  21020. this._buffer._rebuild();
  21021. };
  21022. /**
  21023. * Returns the kind of the VertexBuffer (string).
  21024. */
  21025. VertexBuffer.prototype.getKind = function () {
  21026. return this._kind;
  21027. };
  21028. // Properties
  21029. /**
  21030. * Boolean : is the VertexBuffer updatable ?
  21031. */
  21032. VertexBuffer.prototype.isUpdatable = function () {
  21033. return this._buffer.isUpdatable();
  21034. };
  21035. /**
  21036. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21037. */
  21038. VertexBuffer.prototype.getData = function () {
  21039. return this._buffer.getData();
  21040. };
  21041. /**
  21042. * Returns the WebGLBuffer associated to the VertexBuffer.
  21043. */
  21044. VertexBuffer.prototype.getBuffer = function () {
  21045. return this._buffer.getBuffer();
  21046. };
  21047. /**
  21048. * Returns the stride of the VertexBuffer (integer).
  21049. */
  21050. VertexBuffer.prototype.getStrideSize = function () {
  21051. return this._stride;
  21052. };
  21053. /**
  21054. * Returns the offset (integer).
  21055. */
  21056. VertexBuffer.prototype.getOffset = function () {
  21057. return this._offset;
  21058. };
  21059. /**
  21060. * Returns the VertexBuffer total size (integer).
  21061. */
  21062. VertexBuffer.prototype.getSize = function () {
  21063. return this._size;
  21064. };
  21065. /**
  21066. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21067. */
  21068. VertexBuffer.prototype.getIsInstanced = function () {
  21069. return this._buffer.getIsInstanced();
  21070. };
  21071. /**
  21072. * Returns the instancing divisor, zero for non-instanced (integer).
  21073. */
  21074. VertexBuffer.prototype.getInstanceDivisor = function () {
  21075. return this._buffer.instanceDivisor;
  21076. };
  21077. // Methods
  21078. /**
  21079. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21080. * Returns the created WebGLBuffer.
  21081. */
  21082. VertexBuffer.prototype.create = function (data) {
  21083. return this._buffer.create(data);
  21084. };
  21085. /**
  21086. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21087. * Returns the updated WebGLBuffer.
  21088. */
  21089. VertexBuffer.prototype.update = function (data) {
  21090. return this._buffer.update(data);
  21091. };
  21092. /**
  21093. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21094. * Returns the directly updated WebGLBuffer.
  21095. */
  21096. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21097. return this._buffer.updateDirectly(data, offset);
  21098. };
  21099. /**
  21100. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21101. */
  21102. VertexBuffer.prototype.dispose = function () {
  21103. if (this._ownsBuffer) {
  21104. this._buffer.dispose();
  21105. }
  21106. };
  21107. Object.defineProperty(VertexBuffer, "PositionKind", {
  21108. get: function () {
  21109. return VertexBuffer._PositionKind;
  21110. },
  21111. enumerable: true,
  21112. configurable: true
  21113. });
  21114. Object.defineProperty(VertexBuffer, "NormalKind", {
  21115. get: function () {
  21116. return VertexBuffer._NormalKind;
  21117. },
  21118. enumerable: true,
  21119. configurable: true
  21120. });
  21121. Object.defineProperty(VertexBuffer, "TangentKind", {
  21122. get: function () {
  21123. return VertexBuffer._TangentKind;
  21124. },
  21125. enumerable: true,
  21126. configurable: true
  21127. });
  21128. Object.defineProperty(VertexBuffer, "UVKind", {
  21129. get: function () {
  21130. return VertexBuffer._UVKind;
  21131. },
  21132. enumerable: true,
  21133. configurable: true
  21134. });
  21135. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21136. get: function () {
  21137. return VertexBuffer._UV2Kind;
  21138. },
  21139. enumerable: true,
  21140. configurable: true
  21141. });
  21142. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21143. get: function () {
  21144. return VertexBuffer._UV3Kind;
  21145. },
  21146. enumerable: true,
  21147. configurable: true
  21148. });
  21149. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21150. get: function () {
  21151. return VertexBuffer._UV4Kind;
  21152. },
  21153. enumerable: true,
  21154. configurable: true
  21155. });
  21156. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21157. get: function () {
  21158. return VertexBuffer._UV5Kind;
  21159. },
  21160. enumerable: true,
  21161. configurable: true
  21162. });
  21163. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21164. get: function () {
  21165. return VertexBuffer._UV6Kind;
  21166. },
  21167. enumerable: true,
  21168. configurable: true
  21169. });
  21170. Object.defineProperty(VertexBuffer, "ColorKind", {
  21171. get: function () {
  21172. return VertexBuffer._ColorKind;
  21173. },
  21174. enumerable: true,
  21175. configurable: true
  21176. });
  21177. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21178. get: function () {
  21179. return VertexBuffer._MatricesIndicesKind;
  21180. },
  21181. enumerable: true,
  21182. configurable: true
  21183. });
  21184. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21185. get: function () {
  21186. return VertexBuffer._MatricesWeightsKind;
  21187. },
  21188. enumerable: true,
  21189. configurable: true
  21190. });
  21191. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21192. get: function () {
  21193. return VertexBuffer._MatricesIndicesExtraKind;
  21194. },
  21195. enumerable: true,
  21196. configurable: true
  21197. });
  21198. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21199. get: function () {
  21200. return VertexBuffer._MatricesWeightsExtraKind;
  21201. },
  21202. enumerable: true,
  21203. configurable: true
  21204. });
  21205. // Enums
  21206. VertexBuffer._PositionKind = "position";
  21207. VertexBuffer._NormalKind = "normal";
  21208. VertexBuffer._TangentKind = "tangent";
  21209. VertexBuffer._UVKind = "uv";
  21210. VertexBuffer._UV2Kind = "uv2";
  21211. VertexBuffer._UV3Kind = "uv3";
  21212. VertexBuffer._UV4Kind = "uv4";
  21213. VertexBuffer._UV5Kind = "uv5";
  21214. VertexBuffer._UV6Kind = "uv6";
  21215. VertexBuffer._ColorKind = "color";
  21216. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21217. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21218. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21219. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21220. return VertexBuffer;
  21221. }());
  21222. BABYLON.VertexBuffer = VertexBuffer;
  21223. })(BABYLON || (BABYLON = {}));
  21224. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21225. var BABYLON;
  21226. (function (BABYLON) {
  21227. var InternalTexture = /** @class */ (function () {
  21228. function InternalTexture(engine, dataSource) {
  21229. this.onLoadedObservable = new BABYLON.Observable();
  21230. // Private
  21231. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21232. this._references = 1;
  21233. this._engine = engine;
  21234. this._dataSource = dataSource;
  21235. this._webGLTexture = engine._createTexture();
  21236. }
  21237. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21238. get: function () {
  21239. return this._dataSource;
  21240. },
  21241. enumerable: true,
  21242. configurable: true
  21243. });
  21244. InternalTexture.prototype.incrementReferences = function () {
  21245. this._references++;
  21246. };
  21247. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21248. if (depth === void 0) { depth = 1; }
  21249. this.width = width;
  21250. this.height = height;
  21251. this.depth = depth;
  21252. this.baseWidth = width;
  21253. this.baseHeight = height;
  21254. this.baseDepth = depth;
  21255. this._size = width * height * depth;
  21256. };
  21257. InternalTexture.prototype._rebuild = function () {
  21258. var _this = this;
  21259. var proxy;
  21260. this.isReady = false;
  21261. this._cachedCoordinatesMode = null;
  21262. this._cachedWrapU = null;
  21263. this._cachedWrapV = null;
  21264. this._cachedAnisotropicFilteringLevel = null;
  21265. switch (this._dataSource) {
  21266. case InternalTexture.DATASOURCE_TEMP:
  21267. return;
  21268. case InternalTexture.DATASOURCE_URL:
  21269. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21270. _this.isReady = true;
  21271. }, null, this._buffer, undefined, this.format);
  21272. proxy._swapAndDie(this);
  21273. return;
  21274. case InternalTexture.DATASOURCE_RAW:
  21275. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21276. proxy._swapAndDie(this);
  21277. this.isReady = true;
  21278. return;
  21279. case InternalTexture.DATASOURCE_RAW3D:
  21280. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21281. proxy._swapAndDie(this);
  21282. this.isReady = true;
  21283. return;
  21284. case InternalTexture.DATASOURCE_DYNAMIC:
  21285. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21286. proxy._swapAndDie(this);
  21287. // The engine will make sure to update content so no need to flag it as isReady = true
  21288. return;
  21289. case InternalTexture.DATASOURCE_RENDERTARGET:
  21290. var options = new BABYLON.RenderTargetCreationOptions();
  21291. options.generateDepthBuffer = this._generateDepthBuffer;
  21292. options.generateMipMaps = this.generateMipMaps;
  21293. options.generateStencilBuffer = this._generateStencilBuffer;
  21294. options.samplingMode = this.samplingMode;
  21295. options.type = this.type;
  21296. if (this.isCube) {
  21297. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21298. }
  21299. else {
  21300. var size = {
  21301. width: this.width,
  21302. height: this.height
  21303. };
  21304. proxy = this._engine.createRenderTargetTexture(size, options);
  21305. }
  21306. proxy._swapAndDie(this);
  21307. this.isReady = true;
  21308. return;
  21309. case InternalTexture.DATASOURCE_CUBE:
  21310. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21311. _this.isReady = true;
  21312. }, null, this.format, this._extension);
  21313. proxy._swapAndDie(this);
  21314. return;
  21315. case InternalTexture.DATASOURCE_CUBERAW:
  21316. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21317. proxy._swapAndDie(this);
  21318. this.isReady = true;
  21319. return;
  21320. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21321. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21322. if (proxy) {
  21323. proxy._swapAndDie(_this);
  21324. }
  21325. _this.isReady = true;
  21326. }, null, this.format, this._extension);
  21327. return;
  21328. }
  21329. };
  21330. InternalTexture.prototype._swapAndDie = function (target) {
  21331. target._webGLTexture = this._webGLTexture;
  21332. if (this._framebuffer) {
  21333. target._framebuffer = this._framebuffer;
  21334. }
  21335. if (this._depthStencilBuffer) {
  21336. target._depthStencilBuffer = this._depthStencilBuffer;
  21337. }
  21338. if (this._lodTextureHigh) {
  21339. if (target._lodTextureHigh) {
  21340. target._lodTextureHigh.dispose();
  21341. }
  21342. target._lodTextureHigh = this._lodTextureHigh;
  21343. }
  21344. if (this._lodTextureMid) {
  21345. if (target._lodTextureMid) {
  21346. target._lodTextureMid.dispose();
  21347. }
  21348. target._lodTextureMid = this._lodTextureMid;
  21349. }
  21350. if (this._lodTextureLow) {
  21351. if (target._lodTextureLow) {
  21352. target._lodTextureLow.dispose();
  21353. }
  21354. target._lodTextureLow = this._lodTextureLow;
  21355. }
  21356. var cache = this._engine.getLoadedTexturesCache();
  21357. var index = cache.indexOf(this);
  21358. if (index !== -1) {
  21359. cache.splice(index, 1);
  21360. }
  21361. };
  21362. InternalTexture.prototype.dispose = function () {
  21363. if (!this._webGLTexture) {
  21364. return;
  21365. }
  21366. this._references--;
  21367. if (this._references === 0) {
  21368. this._engine._releaseTexture(this);
  21369. this._webGLTexture = null;
  21370. }
  21371. };
  21372. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21373. InternalTexture.DATASOURCE_URL = 1;
  21374. InternalTexture.DATASOURCE_TEMP = 2;
  21375. InternalTexture.DATASOURCE_RAW = 3;
  21376. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21377. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21378. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21379. InternalTexture.DATASOURCE_CUBE = 7;
  21380. InternalTexture.DATASOURCE_CUBERAW = 8;
  21381. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21382. InternalTexture.DATASOURCE_RAW3D = 10;
  21383. return InternalTexture;
  21384. }());
  21385. BABYLON.InternalTexture = InternalTexture;
  21386. })(BABYLON || (BABYLON = {}));
  21387. //# sourceMappingURL=babylon.internalTexture.js.map
  21388. var BABYLON;
  21389. (function (BABYLON) {
  21390. var BaseTexture = /** @class */ (function () {
  21391. function BaseTexture(scene) {
  21392. this._hasAlpha = false;
  21393. this.getAlphaFromRGB = false;
  21394. this.level = 1;
  21395. this.coordinatesIndex = 0;
  21396. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21397. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21398. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21399. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  21400. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21401. this.isCube = false;
  21402. this.is3D = false;
  21403. this.gammaSpace = true;
  21404. this.invertZ = false;
  21405. this.lodLevelInAlpha = false;
  21406. this.lodGenerationOffset = 0.0;
  21407. this.lodGenerationScale = 0.8;
  21408. this.isRenderTarget = false;
  21409. this.animations = new Array();
  21410. /**
  21411. * An event triggered when the texture is disposed.
  21412. * @type {BABYLON.Observable}
  21413. */
  21414. this.onDisposeObservable = new BABYLON.Observable();
  21415. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21416. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21417. if (this._scene) {
  21418. this._scene.textures.push(this);
  21419. }
  21420. this._uid = null;
  21421. }
  21422. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21423. get: function () {
  21424. return this._hasAlpha;
  21425. },
  21426. set: function (value) {
  21427. if (this._hasAlpha === value) {
  21428. return;
  21429. }
  21430. this._hasAlpha = value;
  21431. if (this._scene) {
  21432. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21433. }
  21434. },
  21435. enumerable: true,
  21436. configurable: true
  21437. });
  21438. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  21439. get: function () {
  21440. return this._coordinatesMode;
  21441. },
  21442. set: function (value) {
  21443. if (this._coordinatesMode === value) {
  21444. return;
  21445. }
  21446. this._coordinatesMode = value;
  21447. if (this._scene) {
  21448. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21449. }
  21450. },
  21451. enumerable: true,
  21452. configurable: true
  21453. });
  21454. Object.defineProperty(BaseTexture.prototype, "uid", {
  21455. get: function () {
  21456. if (!this._uid) {
  21457. this._uid = BABYLON.Tools.RandomId();
  21458. }
  21459. return this._uid;
  21460. },
  21461. enumerable: true,
  21462. configurable: true
  21463. });
  21464. BaseTexture.prototype.toString = function () {
  21465. return this.name;
  21466. };
  21467. BaseTexture.prototype.getClassName = function () {
  21468. return "BaseTexture";
  21469. };
  21470. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21471. set: function (callback) {
  21472. if (this._onDisposeObserver) {
  21473. this.onDisposeObservable.remove(this._onDisposeObserver);
  21474. }
  21475. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21476. },
  21477. enumerable: true,
  21478. configurable: true
  21479. });
  21480. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21481. get: function () {
  21482. return true;
  21483. },
  21484. enumerable: true,
  21485. configurable: true
  21486. });
  21487. BaseTexture.prototype.getScene = function () {
  21488. return this._scene;
  21489. };
  21490. BaseTexture.prototype.getTextureMatrix = function () {
  21491. return BABYLON.Matrix.IdentityReadOnly;
  21492. };
  21493. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21494. return BABYLON.Matrix.IdentityReadOnly;
  21495. };
  21496. BaseTexture.prototype.getInternalTexture = function () {
  21497. return this._texture;
  21498. };
  21499. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21500. return !this.isBlocking || this.isReady();
  21501. };
  21502. BaseTexture.prototype.isReady = function () {
  21503. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21504. this.delayLoad();
  21505. return false;
  21506. }
  21507. if (this._texture) {
  21508. return this._texture.isReady;
  21509. }
  21510. return false;
  21511. };
  21512. BaseTexture.prototype.getSize = function () {
  21513. if (this._texture && this._texture.width) {
  21514. return new BABYLON.Size(this._texture.width, this._texture.height);
  21515. }
  21516. if (this._texture && this._texture._size) {
  21517. return new BABYLON.Size(this._texture._size, this._texture._size);
  21518. }
  21519. return BABYLON.Size.Zero();
  21520. };
  21521. BaseTexture.prototype.getBaseSize = function () {
  21522. if (!this.isReady() || !this._texture)
  21523. return BABYLON.Size.Zero();
  21524. if (this._texture._size) {
  21525. return new BABYLON.Size(this._texture._size, this._texture._size);
  21526. }
  21527. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21528. };
  21529. BaseTexture.prototype.scale = function (ratio) {
  21530. };
  21531. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21532. get: function () {
  21533. return false;
  21534. },
  21535. enumerable: true,
  21536. configurable: true
  21537. });
  21538. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21539. if (!this._scene) {
  21540. return null;
  21541. }
  21542. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21543. for (var index = 0; index < texturesCache.length; index++) {
  21544. var texturesCacheEntry = texturesCache[index];
  21545. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21546. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21547. texturesCacheEntry.incrementReferences();
  21548. return texturesCacheEntry;
  21549. }
  21550. }
  21551. }
  21552. return null;
  21553. };
  21554. BaseTexture.prototype._rebuild = function () {
  21555. };
  21556. BaseTexture.prototype.delayLoad = function () {
  21557. };
  21558. BaseTexture.prototype.clone = function () {
  21559. return null;
  21560. };
  21561. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21562. get: function () {
  21563. if (!this._texture) {
  21564. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21565. }
  21566. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21567. },
  21568. enumerable: true,
  21569. configurable: true
  21570. });
  21571. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21572. get: function () {
  21573. if (!this._texture) {
  21574. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21575. }
  21576. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21577. },
  21578. enumerable: true,
  21579. configurable: true
  21580. });
  21581. BaseTexture.prototype.readPixels = function (faceIndex) {
  21582. if (faceIndex === void 0) { faceIndex = 0; }
  21583. if (!this._texture) {
  21584. return null;
  21585. }
  21586. var size = this.getSize();
  21587. var scene = this.getScene();
  21588. if (!scene) {
  21589. return null;
  21590. }
  21591. var engine = scene.getEngine();
  21592. if (this._texture.isCube) {
  21593. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21594. }
  21595. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21596. };
  21597. BaseTexture.prototype.releaseInternalTexture = function () {
  21598. if (this._texture) {
  21599. this._texture.dispose();
  21600. this._texture = null;
  21601. }
  21602. };
  21603. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21604. get: function () {
  21605. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21606. return null;
  21607. }
  21608. if (!this._texture._sphericalPolynomial) {
  21609. this._texture._sphericalPolynomial =
  21610. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21611. }
  21612. return this._texture._sphericalPolynomial;
  21613. },
  21614. set: function (value) {
  21615. if (this._texture) {
  21616. this._texture._sphericalPolynomial = value;
  21617. }
  21618. },
  21619. enumerable: true,
  21620. configurable: true
  21621. });
  21622. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21623. get: function () {
  21624. if (this._texture) {
  21625. return this._texture._lodTextureHigh;
  21626. }
  21627. return null;
  21628. },
  21629. enumerable: true,
  21630. configurable: true
  21631. });
  21632. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21633. get: function () {
  21634. if (this._texture) {
  21635. return this._texture._lodTextureMid;
  21636. }
  21637. return null;
  21638. },
  21639. enumerable: true,
  21640. configurable: true
  21641. });
  21642. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21643. get: function () {
  21644. if (this._texture) {
  21645. return this._texture._lodTextureLow;
  21646. }
  21647. return null;
  21648. },
  21649. enumerable: true,
  21650. configurable: true
  21651. });
  21652. BaseTexture.prototype.dispose = function () {
  21653. if (!this._scene) {
  21654. return;
  21655. }
  21656. // Animations
  21657. this._scene.stopAnimation(this);
  21658. // Remove from scene
  21659. this._scene._removePendingData(this);
  21660. var index = this._scene.textures.indexOf(this);
  21661. if (index >= 0) {
  21662. this._scene.textures.splice(index, 1);
  21663. }
  21664. if (this._texture === undefined) {
  21665. return;
  21666. }
  21667. // Release
  21668. this.releaseInternalTexture();
  21669. // Callback
  21670. this.onDisposeObservable.notifyObservers(this);
  21671. this.onDisposeObservable.clear();
  21672. };
  21673. BaseTexture.prototype.serialize = function () {
  21674. if (!this.name) {
  21675. return null;
  21676. }
  21677. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21678. // Animations
  21679. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21680. return serializationObject;
  21681. };
  21682. BaseTexture.WhenAllReady = function (textures, callback) {
  21683. var numRemaining = textures.length;
  21684. if (numRemaining === 0) {
  21685. callback();
  21686. return;
  21687. }
  21688. var _loop_1 = function () {
  21689. texture = textures[i];
  21690. if (texture.isReady()) {
  21691. if (--numRemaining === 0) {
  21692. callback();
  21693. }
  21694. }
  21695. else {
  21696. onLoadObservable = texture.onLoadObservable;
  21697. var onLoadCallback_1 = function () {
  21698. onLoadObservable.removeCallback(onLoadCallback_1);
  21699. if (--numRemaining === 0) {
  21700. callback();
  21701. }
  21702. };
  21703. onLoadObservable.add(onLoadCallback_1);
  21704. }
  21705. };
  21706. var texture, onLoadObservable;
  21707. for (var i = 0; i < textures.length; i++) {
  21708. _loop_1();
  21709. }
  21710. };
  21711. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21712. __decorate([
  21713. BABYLON.serialize()
  21714. ], BaseTexture.prototype, "name", void 0);
  21715. __decorate([
  21716. BABYLON.serialize("hasAlpha")
  21717. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21718. __decorate([
  21719. BABYLON.serialize()
  21720. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21721. __decorate([
  21722. BABYLON.serialize()
  21723. ], BaseTexture.prototype, "level", void 0);
  21724. __decorate([
  21725. BABYLON.serialize()
  21726. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21727. __decorate([
  21728. BABYLON.serialize("coordinatesMode")
  21729. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21730. __decorate([
  21731. BABYLON.serialize()
  21732. ], BaseTexture.prototype, "wrapU", void 0);
  21733. __decorate([
  21734. BABYLON.serialize()
  21735. ], BaseTexture.prototype, "wrapV", void 0);
  21736. __decorate([
  21737. BABYLON.serialize()
  21738. ], BaseTexture.prototype, "wrapR", void 0);
  21739. __decorate([
  21740. BABYLON.serialize()
  21741. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21742. __decorate([
  21743. BABYLON.serialize()
  21744. ], BaseTexture.prototype, "isCube", void 0);
  21745. __decorate([
  21746. BABYLON.serialize()
  21747. ], BaseTexture.prototype, "is3D", void 0);
  21748. __decorate([
  21749. BABYLON.serialize()
  21750. ], BaseTexture.prototype, "gammaSpace", void 0);
  21751. __decorate([
  21752. BABYLON.serialize()
  21753. ], BaseTexture.prototype, "invertZ", void 0);
  21754. __decorate([
  21755. BABYLON.serialize()
  21756. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21757. __decorate([
  21758. BABYLON.serialize()
  21759. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21760. __decorate([
  21761. BABYLON.serialize()
  21762. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21763. __decorate([
  21764. BABYLON.serialize()
  21765. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21766. return BaseTexture;
  21767. }());
  21768. BABYLON.BaseTexture = BaseTexture;
  21769. })(BABYLON || (BABYLON = {}));
  21770. //# sourceMappingURL=babylon.baseTexture.js.map
  21771. var BABYLON;
  21772. (function (BABYLON) {
  21773. var Texture = /** @class */ (function (_super) {
  21774. __extends(Texture, _super);
  21775. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21776. if (noMipmap === void 0) { noMipmap = false; }
  21777. if (invertY === void 0) { invertY = true; }
  21778. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21779. if (onLoad === void 0) { onLoad = null; }
  21780. if (onError === void 0) { onError = null; }
  21781. if (buffer === void 0) { buffer = null; }
  21782. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21783. var _this = _super.call(this, scene) || this;
  21784. _this.uOffset = 0;
  21785. _this.vOffset = 0;
  21786. _this.uScale = 1.0;
  21787. _this.vScale = 1.0;
  21788. _this.uAng = 0;
  21789. _this.vAng = 0;
  21790. _this.wAng = 0;
  21791. _this._isBlocking = true;
  21792. _this.name = url || "";
  21793. _this.url = url;
  21794. _this._noMipmap = noMipmap;
  21795. _this._invertY = invertY;
  21796. _this._samplingMode = samplingMode;
  21797. _this._buffer = buffer;
  21798. _this._deleteBuffer = deleteBuffer;
  21799. if (format) {
  21800. _this._format = format;
  21801. }
  21802. scene = _this.getScene();
  21803. if (!scene) {
  21804. return _this;
  21805. }
  21806. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21807. var load = function () {
  21808. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21809. _this.onLoadObservable.notifyObservers(_this);
  21810. }
  21811. if (onLoad) {
  21812. onLoad();
  21813. }
  21814. if (!_this.isBlocking && scene) {
  21815. scene.resetCachedMaterial();
  21816. }
  21817. };
  21818. if (!_this.url) {
  21819. _this._delayedOnLoad = load;
  21820. _this._delayedOnError = onError;
  21821. return _this;
  21822. }
  21823. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21824. if (!_this._texture) {
  21825. if (!scene.useDelayedTextureLoading) {
  21826. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  21827. if (deleteBuffer) {
  21828. delete _this._buffer;
  21829. }
  21830. }
  21831. else {
  21832. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21833. _this._delayedOnLoad = load;
  21834. _this._delayedOnError = onError;
  21835. }
  21836. }
  21837. else {
  21838. if (_this._texture.isReady) {
  21839. BABYLON.Tools.SetImmediate(function () { return load(); });
  21840. }
  21841. else {
  21842. _this._texture.onLoadedObservable.add(load);
  21843. }
  21844. }
  21845. return _this;
  21846. }
  21847. Object.defineProperty(Texture.prototype, "noMipmap", {
  21848. get: function () {
  21849. return this._noMipmap;
  21850. },
  21851. enumerable: true,
  21852. configurable: true
  21853. });
  21854. Object.defineProperty(Texture.prototype, "isBlocking", {
  21855. get: function () {
  21856. return this._isBlocking;
  21857. },
  21858. set: function (value) {
  21859. this._isBlocking = value;
  21860. },
  21861. enumerable: true,
  21862. configurable: true
  21863. });
  21864. Object.defineProperty(Texture.prototype, "samplingMode", {
  21865. get: function () {
  21866. return this._samplingMode;
  21867. },
  21868. enumerable: true,
  21869. configurable: true
  21870. });
  21871. Texture.prototype.updateURL = function (url) {
  21872. this.url = url;
  21873. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21874. this.delayLoad();
  21875. };
  21876. Texture.prototype.delayLoad = function () {
  21877. var _this = this;
  21878. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21879. return;
  21880. }
  21881. var scene = this.getScene();
  21882. if (!scene) {
  21883. return;
  21884. }
  21885. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21886. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21887. if (!this._texture) {
  21888. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  21889. if (this._deleteBuffer) {
  21890. delete this._buffer;
  21891. }
  21892. }
  21893. else {
  21894. if (this._texture.isReady) {
  21895. BABYLON.Tools.SetImmediate(function () {
  21896. if (!_this._delayedOnLoad) {
  21897. return;
  21898. }
  21899. _this._delayedOnLoad();
  21900. });
  21901. }
  21902. else {
  21903. if (this._delayedOnLoad) {
  21904. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  21905. }
  21906. }
  21907. }
  21908. };
  21909. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21910. if (!this._texture) {
  21911. return;
  21912. }
  21913. var scene = this.getScene();
  21914. if (!scene) {
  21915. return;
  21916. }
  21917. this._samplingMode = samplingMode;
  21918. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21919. };
  21920. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21921. x *= this.uScale;
  21922. y *= this.vScale;
  21923. x -= 0.5 * this.uScale;
  21924. y -= 0.5 * this.vScale;
  21925. z -= 0.5;
  21926. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21927. t.x += 0.5 * this.uScale + this.uOffset;
  21928. t.y += 0.5 * this.vScale + this.vOffset;
  21929. t.z += 0.5;
  21930. };
  21931. Texture.prototype.getTextureMatrix = function () {
  21932. var _this = this;
  21933. if (this.uOffset === this._cachedUOffset &&
  21934. this.vOffset === this._cachedVOffset &&
  21935. this.uScale === this._cachedUScale &&
  21936. this.vScale === this._cachedVScale &&
  21937. this.uAng === this._cachedUAng &&
  21938. this.vAng === this._cachedVAng &&
  21939. this.wAng === this._cachedWAng) {
  21940. return this._cachedTextureMatrix;
  21941. }
  21942. this._cachedUOffset = this.uOffset;
  21943. this._cachedVOffset = this.vOffset;
  21944. this._cachedUScale = this.uScale;
  21945. this._cachedVScale = this.vScale;
  21946. this._cachedUAng = this.uAng;
  21947. this._cachedVAng = this.vAng;
  21948. this._cachedWAng = this.wAng;
  21949. if (!this._cachedTextureMatrix) {
  21950. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21951. this._rowGenerationMatrix = new BABYLON.Matrix();
  21952. this._t0 = BABYLON.Vector3.Zero();
  21953. this._t1 = BABYLON.Vector3.Zero();
  21954. this._t2 = BABYLON.Vector3.Zero();
  21955. }
  21956. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21957. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21958. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21959. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21960. this._t1.subtractInPlace(this._t0);
  21961. this._t2.subtractInPlace(this._t0);
  21962. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21963. this._cachedTextureMatrix.m[0] = this._t1.x;
  21964. this._cachedTextureMatrix.m[1] = this._t1.y;
  21965. this._cachedTextureMatrix.m[2] = this._t1.z;
  21966. this._cachedTextureMatrix.m[4] = this._t2.x;
  21967. this._cachedTextureMatrix.m[5] = this._t2.y;
  21968. this._cachedTextureMatrix.m[6] = this._t2.z;
  21969. this._cachedTextureMatrix.m[8] = this._t0.x;
  21970. this._cachedTextureMatrix.m[9] = this._t0.y;
  21971. this._cachedTextureMatrix.m[10] = this._t0.z;
  21972. var scene = this.getScene();
  21973. if (!scene) {
  21974. return this._cachedTextureMatrix;
  21975. }
  21976. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21977. return mat.hasTexture(_this);
  21978. });
  21979. return this._cachedTextureMatrix;
  21980. };
  21981. Texture.prototype.getReflectionTextureMatrix = function () {
  21982. var _this = this;
  21983. var scene = this.getScene();
  21984. if (!scene) {
  21985. return this._cachedTextureMatrix;
  21986. }
  21987. if (this.uOffset === this._cachedUOffset &&
  21988. this.vOffset === this._cachedVOffset &&
  21989. this.uScale === this._cachedUScale &&
  21990. this.vScale === this._cachedVScale &&
  21991. this.coordinatesMode === this._cachedCoordinatesMode) {
  21992. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21993. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21994. return this._cachedTextureMatrix;
  21995. }
  21996. }
  21997. else {
  21998. return this._cachedTextureMatrix;
  21999. }
  22000. }
  22001. if (!this._cachedTextureMatrix) {
  22002. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22003. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22004. }
  22005. this._cachedUOffset = this.uOffset;
  22006. this._cachedVOffset = this.vOffset;
  22007. this._cachedUScale = this.uScale;
  22008. this._cachedVScale = this.vScale;
  22009. this._cachedCoordinatesMode = this.coordinatesMode;
  22010. switch (this.coordinatesMode) {
  22011. case Texture.PLANAR_MODE:
  22012. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22013. this._cachedTextureMatrix[0] = this.uScale;
  22014. this._cachedTextureMatrix[5] = this.vScale;
  22015. this._cachedTextureMatrix[12] = this.uOffset;
  22016. this._cachedTextureMatrix[13] = this.vOffset;
  22017. break;
  22018. case Texture.PROJECTION_MODE:
  22019. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22020. this._projectionModeMatrix.m[0] = 0.5;
  22021. this._projectionModeMatrix.m[5] = -0.5;
  22022. this._projectionModeMatrix.m[10] = 0.0;
  22023. this._projectionModeMatrix.m[12] = 0.5;
  22024. this._projectionModeMatrix.m[13] = 0.5;
  22025. this._projectionModeMatrix.m[14] = 1.0;
  22026. this._projectionModeMatrix.m[15] = 1.0;
  22027. var projectionMatrix = scene.getProjectionMatrix();
  22028. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22029. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22030. break;
  22031. default:
  22032. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22033. break;
  22034. }
  22035. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22036. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22037. });
  22038. return this._cachedTextureMatrix;
  22039. };
  22040. Texture.prototype.clone = function () {
  22041. var _this = this;
  22042. return BABYLON.SerializationHelper.Clone(function () {
  22043. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22044. }, this);
  22045. };
  22046. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22047. get: function () {
  22048. if (!this._onLoadObservable) {
  22049. this._onLoadObservable = new BABYLON.Observable();
  22050. }
  22051. return this._onLoadObservable;
  22052. },
  22053. enumerable: true,
  22054. configurable: true
  22055. });
  22056. Texture.prototype.serialize = function () {
  22057. var serializationObject = _super.prototype.serialize.call(this);
  22058. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22059. serializationObject.base64String = this._buffer;
  22060. serializationObject.name = serializationObject.name.replace("data:", "");
  22061. }
  22062. return serializationObject;
  22063. };
  22064. Texture.prototype.getClassName = function () {
  22065. return "Texture";
  22066. };
  22067. Texture.prototype.dispose = function () {
  22068. _super.prototype.dispose.call(this);
  22069. if (this.onLoadObservable) {
  22070. this.onLoadObservable.clear();
  22071. this._onLoadObservable = null;
  22072. }
  22073. this._delayedOnLoad = null;
  22074. this._delayedOnError = null;
  22075. };
  22076. // Statics
  22077. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22078. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22079. if (onLoad === void 0) { onLoad = null; }
  22080. if (onError === void 0) { onError = null; }
  22081. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22082. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22083. };
  22084. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22085. if (parsedTexture.customType) {
  22086. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22087. // Update Sampling Mode
  22088. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22089. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22090. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22091. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22092. }
  22093. }
  22094. return parsedCustomTexture;
  22095. }
  22096. if (parsedTexture.isCube) {
  22097. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22098. }
  22099. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22100. return null;
  22101. }
  22102. var texture = BABYLON.SerializationHelper.Parse(function () {
  22103. if (parsedTexture.mirrorPlane) {
  22104. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22105. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22106. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22107. return mirrorTexture;
  22108. }
  22109. else if (parsedTexture.isRenderTarget) {
  22110. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22111. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22112. return renderTargetTexture;
  22113. }
  22114. else {
  22115. var texture;
  22116. if (parsedTexture.base64String) {
  22117. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22118. }
  22119. else {
  22120. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22121. }
  22122. return texture;
  22123. }
  22124. }, parsedTexture, scene);
  22125. // Update Sampling Mode
  22126. if (parsedTexture.samplingMode) {
  22127. var sampling = parsedTexture.samplingMode;
  22128. if (texture._samplingMode !== sampling) {
  22129. texture.updateSamplingMode(sampling);
  22130. }
  22131. }
  22132. // Animations
  22133. if (parsedTexture.animations) {
  22134. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22135. var parsedAnimation = parsedTexture.animations[animationIndex];
  22136. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22137. }
  22138. }
  22139. return texture;
  22140. };
  22141. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22142. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22143. if (noMipmap === void 0) { noMipmap = false; }
  22144. if (invertY === void 0) { invertY = true; }
  22145. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22146. if (onLoad === void 0) { onLoad = null; }
  22147. if (onError === void 0) { onError = null; }
  22148. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22149. if (name.substr(0, 5) !== "data:") {
  22150. name = "data:" + name;
  22151. }
  22152. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22153. };
  22154. // Constants
  22155. Texture.NEAREST_SAMPLINGMODE = 1;
  22156. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22157. Texture.BILINEAR_SAMPLINGMODE = 2;
  22158. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22159. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22160. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22161. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22162. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22163. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22164. Texture.NEAREST_LINEAR = 7;
  22165. Texture.NEAREST_NEAREST = 8;
  22166. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22167. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22168. Texture.LINEAR_LINEAR = 11;
  22169. Texture.LINEAR_NEAREST = 12;
  22170. Texture.EXPLICIT_MODE = 0;
  22171. Texture.SPHERICAL_MODE = 1;
  22172. Texture.PLANAR_MODE = 2;
  22173. Texture.CUBIC_MODE = 3;
  22174. Texture.PROJECTION_MODE = 4;
  22175. Texture.SKYBOX_MODE = 5;
  22176. Texture.INVCUBIC_MODE = 6;
  22177. Texture.EQUIRECTANGULAR_MODE = 7;
  22178. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22179. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22180. Texture.CLAMP_ADDRESSMODE = 0;
  22181. Texture.WRAP_ADDRESSMODE = 1;
  22182. Texture.MIRROR_ADDRESSMODE = 2;
  22183. __decorate([
  22184. BABYLON.serialize()
  22185. ], Texture.prototype, "url", void 0);
  22186. __decorate([
  22187. BABYLON.serialize()
  22188. ], Texture.prototype, "uOffset", void 0);
  22189. __decorate([
  22190. BABYLON.serialize()
  22191. ], Texture.prototype, "vOffset", void 0);
  22192. __decorate([
  22193. BABYLON.serialize()
  22194. ], Texture.prototype, "uScale", void 0);
  22195. __decorate([
  22196. BABYLON.serialize()
  22197. ], Texture.prototype, "vScale", void 0);
  22198. __decorate([
  22199. BABYLON.serialize()
  22200. ], Texture.prototype, "uAng", void 0);
  22201. __decorate([
  22202. BABYLON.serialize()
  22203. ], Texture.prototype, "vAng", void 0);
  22204. __decorate([
  22205. BABYLON.serialize()
  22206. ], Texture.prototype, "wAng", void 0);
  22207. __decorate([
  22208. BABYLON.serialize()
  22209. ], Texture.prototype, "isBlocking", null);
  22210. return Texture;
  22211. }(BABYLON.BaseTexture));
  22212. BABYLON.Texture = Texture;
  22213. })(BABYLON || (BABYLON = {}));
  22214. //# sourceMappingURL=babylon.texture.js.map
  22215. var BABYLON;
  22216. (function (BABYLON) {
  22217. var _InstancesBatch = /** @class */ (function () {
  22218. function _InstancesBatch() {
  22219. this.mustReturn = false;
  22220. this.visibleInstances = new Array();
  22221. this.renderSelf = new Array();
  22222. }
  22223. return _InstancesBatch;
  22224. }());
  22225. BABYLON._InstancesBatch = _InstancesBatch;
  22226. var Mesh = /** @class */ (function (_super) {
  22227. __extends(Mesh, _super);
  22228. /**
  22229. * @constructor
  22230. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22231. * @param {Scene} scene The scene to add this mesh to.
  22232. * @param {Node} parent The parent of this mesh, if it has one
  22233. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22234. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22235. * When false, achieved by calling a clone(), also passing False.
  22236. * This will make creation of children, recursive.
  22237. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22238. */
  22239. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22240. if (scene === void 0) { scene = null; }
  22241. if (parent === void 0) { parent = null; }
  22242. if (source === void 0) { source = null; }
  22243. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22244. var _this = _super.call(this, name, scene) || this;
  22245. // Events
  22246. /**
  22247. * An event triggered before rendering the mesh
  22248. * @type {BABYLON.Observable}
  22249. */
  22250. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22251. /**
  22252. * An event triggered after rendering the mesh
  22253. * @type {BABYLON.Observable}
  22254. */
  22255. _this.onAfterRenderObservable = new BABYLON.Observable();
  22256. /**
  22257. * An event triggered before drawing the mesh
  22258. * @type {BABYLON.Observable}
  22259. */
  22260. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22261. // Members
  22262. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22263. _this.instances = new Array();
  22264. _this._LODLevels = new Array();
  22265. _this._visibleInstances = {};
  22266. _this._renderIdForInstances = new Array();
  22267. _this._batchCache = new _InstancesBatch();
  22268. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22269. // Use by builder only to know what orientation were the mesh build in.
  22270. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22271. _this.overrideMaterialSideOrientation = null;
  22272. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22273. // Will be used to save a source mesh reference, If any
  22274. _this._source = null;
  22275. scene = _this.getScene();
  22276. if (source) {
  22277. // Source mesh
  22278. _this._source = source;
  22279. // Geometry
  22280. if (source._geometry) {
  22281. source._geometry.applyToMesh(_this);
  22282. }
  22283. // Deep copy
  22284. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  22285. // Tags
  22286. if (BABYLON.Tags.HasTags(source)) {
  22287. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22288. }
  22289. _this.metadata = source.metadata;
  22290. // Parent
  22291. _this.parent = source.parent;
  22292. // Pivot
  22293. _this.setPivotMatrix(source.getPivotMatrix());
  22294. _this.id = name + "." + source.id;
  22295. // Material
  22296. _this.material = source.material;
  22297. var index;
  22298. if (!doNotCloneChildren) {
  22299. // Children
  22300. for (index = 0; index < scene.meshes.length; index++) {
  22301. var mesh = scene.meshes[index];
  22302. if (mesh.parent === source) {
  22303. // doNotCloneChildren is always going to be False
  22304. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22305. }
  22306. }
  22307. }
  22308. // Physics clone
  22309. var physicsEngine = _this.getScene().getPhysicsEngine();
  22310. if (clonePhysicsImpostor && physicsEngine) {
  22311. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22312. if (impostor) {
  22313. _this.physicsImpostor = impostor.clone(_this);
  22314. }
  22315. }
  22316. // Particles
  22317. for (index = 0; index < scene.particleSystems.length; index++) {
  22318. var system = scene.particleSystems[index];
  22319. if (system.emitter === source) {
  22320. system.clone(system.name, _this);
  22321. }
  22322. }
  22323. _this.computeWorldMatrix(true);
  22324. }
  22325. // Parent
  22326. if (parent !== null) {
  22327. _this.parent = parent;
  22328. }
  22329. return _this;
  22330. }
  22331. Object.defineProperty(Mesh, "FRONTSIDE", {
  22332. /**
  22333. * Mesh side orientation : usually the external or front surface
  22334. */
  22335. get: function () {
  22336. return Mesh._FRONTSIDE;
  22337. },
  22338. enumerable: true,
  22339. configurable: true
  22340. });
  22341. Object.defineProperty(Mesh, "BACKSIDE", {
  22342. /**
  22343. * Mesh side orientation : usually the internal or back surface
  22344. */
  22345. get: function () {
  22346. return Mesh._BACKSIDE;
  22347. },
  22348. enumerable: true,
  22349. configurable: true
  22350. });
  22351. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22352. /**
  22353. * Mesh side orientation : both internal and external or front and back surfaces
  22354. */
  22355. get: function () {
  22356. return Mesh._DOUBLESIDE;
  22357. },
  22358. enumerable: true,
  22359. configurable: true
  22360. });
  22361. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22362. /**
  22363. * Mesh side orientation : by default, `FRONTSIDE`
  22364. */
  22365. get: function () {
  22366. return Mesh._DEFAULTSIDE;
  22367. },
  22368. enumerable: true,
  22369. configurable: true
  22370. });
  22371. Object.defineProperty(Mesh, "NO_CAP", {
  22372. /**
  22373. * Mesh cap setting : no cap
  22374. */
  22375. get: function () {
  22376. return Mesh._NO_CAP;
  22377. },
  22378. enumerable: true,
  22379. configurable: true
  22380. });
  22381. Object.defineProperty(Mesh, "CAP_START", {
  22382. /**
  22383. * Mesh cap setting : one cap at the beginning of the mesh
  22384. */
  22385. get: function () {
  22386. return Mesh._CAP_START;
  22387. },
  22388. enumerable: true,
  22389. configurable: true
  22390. });
  22391. Object.defineProperty(Mesh, "CAP_END", {
  22392. /**
  22393. * Mesh cap setting : one cap at the end of the mesh
  22394. */
  22395. get: function () {
  22396. return Mesh._CAP_END;
  22397. },
  22398. enumerable: true,
  22399. configurable: true
  22400. });
  22401. Object.defineProperty(Mesh, "CAP_ALL", {
  22402. /**
  22403. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22404. */
  22405. get: function () {
  22406. return Mesh._CAP_ALL;
  22407. },
  22408. enumerable: true,
  22409. configurable: true
  22410. });
  22411. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22412. set: function (callback) {
  22413. if (this._onBeforeDrawObserver) {
  22414. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22415. }
  22416. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22417. },
  22418. enumerable: true,
  22419. configurable: true
  22420. });
  22421. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22422. get: function () {
  22423. return this._morphTargetManager;
  22424. },
  22425. set: function (value) {
  22426. if (this._morphTargetManager === value) {
  22427. return;
  22428. }
  22429. this._morphTargetManager = value;
  22430. this._syncGeometryWithMorphTargetManager();
  22431. },
  22432. enumerable: true,
  22433. configurable: true
  22434. });
  22435. Object.defineProperty(Mesh.prototype, "source", {
  22436. get: function () {
  22437. return this._source;
  22438. },
  22439. enumerable: true,
  22440. configurable: true
  22441. });
  22442. // Methods
  22443. /**
  22444. * Returns the string "Mesh".
  22445. */
  22446. Mesh.prototype.getClassName = function () {
  22447. return "Mesh";
  22448. };
  22449. /**
  22450. * Returns a string.
  22451. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22452. */
  22453. Mesh.prototype.toString = function (fullDetails) {
  22454. var ret = _super.prototype.toString.call(this, fullDetails);
  22455. ret += ", n vertices: " + this.getTotalVertices();
  22456. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22457. if (this.animations) {
  22458. for (var i = 0; i < this.animations.length; i++) {
  22459. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22460. }
  22461. }
  22462. if (fullDetails) {
  22463. if (this._geometry) {
  22464. var ib = this.getIndices();
  22465. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22466. if (vb && ib) {
  22467. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  22468. }
  22469. }
  22470. else {
  22471. ret += ", flat shading: UNKNOWN";
  22472. }
  22473. }
  22474. return ret;
  22475. };
  22476. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22477. /**
  22478. * True if the mesh has some Levels Of Details (LOD).
  22479. * Returns a boolean.
  22480. */
  22481. get: function () {
  22482. return this._LODLevels.length > 0;
  22483. },
  22484. enumerable: true,
  22485. configurable: true
  22486. });
  22487. Mesh.prototype._sortLODLevels = function () {
  22488. this._LODLevels.sort(function (a, b) {
  22489. if (a.distance < b.distance) {
  22490. return 1;
  22491. }
  22492. if (a.distance > b.distance) {
  22493. return -1;
  22494. }
  22495. return 0;
  22496. });
  22497. };
  22498. /**
  22499. * Add a mesh as LOD level triggered at the given distance.
  22500. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22501. * @param {number} distance The distance from the center of the object to show this level
  22502. * @param {Mesh} mesh The mesh to be added as LOD level
  22503. * @return {Mesh} This mesh (for chaining)
  22504. */
  22505. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22506. if (mesh && mesh._masterMesh) {
  22507. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22508. return this;
  22509. }
  22510. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22511. this._LODLevels.push(level);
  22512. if (mesh) {
  22513. mesh._masterMesh = this;
  22514. }
  22515. this._sortLODLevels();
  22516. return this;
  22517. };
  22518. /**
  22519. * Returns the LOD level mesh at the passed distance or null if not found.
  22520. * It is related to the method `addLODLevel(distance, mesh)`.
  22521. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22522. * Returns an object Mesh or `null`.
  22523. */
  22524. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22525. for (var index = 0; index < this._LODLevels.length; index++) {
  22526. var level = this._LODLevels[index];
  22527. if (level.distance === distance) {
  22528. return level.mesh;
  22529. }
  22530. }
  22531. return null;
  22532. };
  22533. /**
  22534. * Remove a mesh from the LOD array
  22535. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22536. * @param {Mesh} mesh The mesh to be removed.
  22537. * @return {Mesh} This mesh (for chaining)
  22538. */
  22539. Mesh.prototype.removeLODLevel = function (mesh) {
  22540. for (var index = 0; index < this._LODLevels.length; index++) {
  22541. if (this._LODLevels[index].mesh === mesh) {
  22542. this._LODLevels.splice(index, 1);
  22543. if (mesh) {
  22544. mesh._masterMesh = null;
  22545. }
  22546. }
  22547. }
  22548. this._sortLODLevels();
  22549. return this;
  22550. };
  22551. /**
  22552. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22553. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22554. */
  22555. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22556. if (!this._LODLevels || this._LODLevels.length === 0) {
  22557. return this;
  22558. }
  22559. var bSphere;
  22560. if (boundingSphere) {
  22561. bSphere = boundingSphere;
  22562. }
  22563. else {
  22564. var boundingInfo = this.getBoundingInfo();
  22565. if (!boundingInfo) {
  22566. return this;
  22567. }
  22568. bSphere = boundingInfo.boundingSphere;
  22569. }
  22570. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  22571. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22572. if (this.onLODLevelSelection) {
  22573. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22574. }
  22575. return this;
  22576. }
  22577. for (var index = 0; index < this._LODLevels.length; index++) {
  22578. var level = this._LODLevels[index];
  22579. if (level.distance < distanceToCamera) {
  22580. if (level.mesh) {
  22581. level.mesh._preActivate();
  22582. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22583. }
  22584. if (this.onLODLevelSelection) {
  22585. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22586. }
  22587. return level.mesh;
  22588. }
  22589. }
  22590. if (this.onLODLevelSelection) {
  22591. this.onLODLevelSelection(distanceToCamera, this, this);
  22592. }
  22593. return this;
  22594. };
  22595. Object.defineProperty(Mesh.prototype, "geometry", {
  22596. /**
  22597. * Returns the mesh internal Geometry object.
  22598. */
  22599. get: function () {
  22600. return this._geometry;
  22601. },
  22602. enumerable: true,
  22603. configurable: true
  22604. });
  22605. /**
  22606. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22607. */
  22608. Mesh.prototype.getTotalVertices = function () {
  22609. if (!this._geometry) {
  22610. return 0;
  22611. }
  22612. return this._geometry.getTotalVertices();
  22613. };
  22614. /**
  22615. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22616. * 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.
  22617. * You can force the copy with forceCopy === true
  22618. * Returns null if the mesh has no geometry or no vertex buffer.
  22619. * Possible `kind` values :
  22620. * - BABYLON.VertexBuffer.PositionKind
  22621. * - BABYLON.VertexBuffer.UVKind
  22622. * - BABYLON.VertexBuffer.UV2Kind
  22623. * - BABYLON.VertexBuffer.UV3Kind
  22624. * - BABYLON.VertexBuffer.UV4Kind
  22625. * - BABYLON.VertexBuffer.UV5Kind
  22626. * - BABYLON.VertexBuffer.UV6Kind
  22627. * - BABYLON.VertexBuffer.ColorKind
  22628. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22629. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22630. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22631. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22632. */
  22633. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22634. if (!this._geometry) {
  22635. return null;
  22636. }
  22637. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22638. };
  22639. /**
  22640. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22641. * Returns `null` if the mesh has no geometry.
  22642. * Possible `kind` values :
  22643. * - BABYLON.VertexBuffer.PositionKind
  22644. * - BABYLON.VertexBuffer.UVKind
  22645. * - BABYLON.VertexBuffer.UV2Kind
  22646. * - BABYLON.VertexBuffer.UV3Kind
  22647. * - BABYLON.VertexBuffer.UV4Kind
  22648. * - BABYLON.VertexBuffer.UV5Kind
  22649. * - BABYLON.VertexBuffer.UV6Kind
  22650. * - BABYLON.VertexBuffer.ColorKind
  22651. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22652. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22653. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22654. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22655. */
  22656. Mesh.prototype.getVertexBuffer = function (kind) {
  22657. if (!this._geometry) {
  22658. return null;
  22659. }
  22660. return this._geometry.getVertexBuffer(kind);
  22661. };
  22662. /**
  22663. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22664. * Possible `kind` values :
  22665. * - BABYLON.VertexBuffer.PositionKind
  22666. * - BABYLON.VertexBuffer.UVKind
  22667. * - BABYLON.VertexBuffer.UV2Kind
  22668. * - BABYLON.VertexBuffer.UV3Kind
  22669. * - BABYLON.VertexBuffer.UV4Kind
  22670. * - BABYLON.VertexBuffer.UV5Kind
  22671. * - BABYLON.VertexBuffer.UV6Kind
  22672. * - BABYLON.VertexBuffer.ColorKind
  22673. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22674. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22675. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22676. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22677. */
  22678. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22679. if (!this._geometry) {
  22680. if (this._delayInfo) {
  22681. return this._delayInfo.indexOf(kind) !== -1;
  22682. }
  22683. return false;
  22684. }
  22685. return this._geometry.isVerticesDataPresent(kind);
  22686. };
  22687. /**
  22688. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  22689. * Possible `kind` values :
  22690. * - BABYLON.VertexBuffer.PositionKind
  22691. * - BABYLON.VertexBuffer.UVKind
  22692. * - BABYLON.VertexBuffer.UV2Kind
  22693. * - BABYLON.VertexBuffer.UV3Kind
  22694. * - BABYLON.VertexBuffer.UV4Kind
  22695. * - BABYLON.VertexBuffer.UV5Kind
  22696. * - BABYLON.VertexBuffer.UV6Kind
  22697. * - BABYLON.VertexBuffer.ColorKind
  22698. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22699. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22700. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22701. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22702. */
  22703. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  22704. if (!this._geometry) {
  22705. if (this._delayInfo) {
  22706. return this._delayInfo.indexOf(kind) !== -1;
  22707. }
  22708. return false;
  22709. }
  22710. return this._geometry.isVertexBufferUpdatable(kind);
  22711. };
  22712. /**
  22713. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22714. * Possible `kind` values :
  22715. * - BABYLON.VertexBuffer.PositionKind
  22716. * - BABYLON.VertexBuffer.UVKind
  22717. * - BABYLON.VertexBuffer.UV2Kind
  22718. * - BABYLON.VertexBuffer.UV3Kind
  22719. * - BABYLON.VertexBuffer.UV4Kind
  22720. * - BABYLON.VertexBuffer.UV5Kind
  22721. * - BABYLON.VertexBuffer.UV6Kind
  22722. * - BABYLON.VertexBuffer.ColorKind
  22723. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22724. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22725. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22726. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22727. */
  22728. Mesh.prototype.getVerticesDataKinds = function () {
  22729. if (!this._geometry) {
  22730. var result = new Array();
  22731. if (this._delayInfo) {
  22732. this._delayInfo.forEach(function (kind, index, array) {
  22733. result.push(kind);
  22734. });
  22735. }
  22736. return result;
  22737. }
  22738. return this._geometry.getVerticesDataKinds();
  22739. };
  22740. /**
  22741. * Returns a positive integer : the total number of indices in this mesh geometry.
  22742. * Returns zero if the mesh has no geometry.
  22743. */
  22744. Mesh.prototype.getTotalIndices = function () {
  22745. if (!this._geometry) {
  22746. return 0;
  22747. }
  22748. return this._geometry.getTotalIndices();
  22749. };
  22750. /**
  22751. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22752. * 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.
  22753. * Returns an empty array if the mesh has no geometry.
  22754. */
  22755. Mesh.prototype.getIndices = function (copyWhenShared) {
  22756. if (!this._geometry) {
  22757. return [];
  22758. }
  22759. return this._geometry.getIndices(copyWhenShared);
  22760. };
  22761. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22762. get: function () {
  22763. return this._masterMesh !== null && this._masterMesh !== undefined;
  22764. },
  22765. enumerable: true,
  22766. configurable: true
  22767. });
  22768. /**
  22769. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22770. */
  22771. Mesh.prototype.isReady = function () {
  22772. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22773. return false;
  22774. }
  22775. return _super.prototype.isReady.call(this);
  22776. };
  22777. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22778. /**
  22779. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22780. * This property is pertinent only for updatable parametric shapes.
  22781. */
  22782. get: function () {
  22783. return this._areNormalsFrozen;
  22784. },
  22785. enumerable: true,
  22786. configurable: true
  22787. });
  22788. /**
  22789. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22790. * It has no effect at all on other shapes.
  22791. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22792. * Returns the Mesh.
  22793. */
  22794. Mesh.prototype.freezeNormals = function () {
  22795. this._areNormalsFrozen = true;
  22796. return this;
  22797. };
  22798. /**
  22799. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22800. * It has no effect at all on other shapes.
  22801. * It reactivates the mesh normals computation if it was previously frozen.
  22802. * Returns the Mesh.
  22803. */
  22804. Mesh.prototype.unfreezeNormals = function () {
  22805. this._areNormalsFrozen = false;
  22806. return this;
  22807. };
  22808. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22809. /**
  22810. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22811. */
  22812. set: function (count) {
  22813. this._overridenInstanceCount = count;
  22814. },
  22815. enumerable: true,
  22816. configurable: true
  22817. });
  22818. // Methods
  22819. Mesh.prototype._preActivate = function () {
  22820. var sceneRenderId = this.getScene().getRenderId();
  22821. if (this._preActivateId === sceneRenderId) {
  22822. return this;
  22823. }
  22824. this._preActivateId = sceneRenderId;
  22825. this._visibleInstances = null;
  22826. return this;
  22827. };
  22828. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22829. if (this._visibleInstances) {
  22830. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22831. }
  22832. return this;
  22833. };
  22834. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22835. if (!this._visibleInstances) {
  22836. this._visibleInstances = {};
  22837. this._visibleInstances.defaultRenderId = renderId;
  22838. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22839. }
  22840. if (!this._visibleInstances[renderId]) {
  22841. this._visibleInstances[renderId] = new Array();
  22842. }
  22843. this._visibleInstances[renderId].push(instance);
  22844. return this;
  22845. };
  22846. /**
  22847. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22848. * This means the mesh underlying bounding box and sphere are recomputed.
  22849. * Returns the Mesh.
  22850. */
  22851. Mesh.prototype.refreshBoundingInfo = function () {
  22852. if (this._boundingInfo && this._boundingInfo.isLocked) {
  22853. return this;
  22854. }
  22855. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22856. if (data) {
  22857. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22858. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22859. }
  22860. if (this.subMeshes) {
  22861. for (var index = 0; index < this.subMeshes.length; index++) {
  22862. this.subMeshes[index].refreshBoundingInfo();
  22863. }
  22864. }
  22865. this._updateBoundingInfo();
  22866. return this;
  22867. };
  22868. Mesh.prototype._createGlobalSubMesh = function (force) {
  22869. var totalVertices = this.getTotalVertices();
  22870. if (!totalVertices || !this.getIndices()) {
  22871. return null;
  22872. }
  22873. // Check if we need to recreate the submeshes
  22874. if (this.subMeshes && this.subMeshes.length > 0) {
  22875. var ib = this.getIndices();
  22876. if (!ib) {
  22877. return null;
  22878. }
  22879. var totalIndices = ib.length;
  22880. var needToRecreate = false;
  22881. if (force) {
  22882. needToRecreate = true;
  22883. }
  22884. else {
  22885. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  22886. var submesh = _a[_i];
  22887. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  22888. needToRecreate = true;
  22889. break;
  22890. }
  22891. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  22892. needToRecreate = true;
  22893. break;
  22894. }
  22895. }
  22896. }
  22897. if (!needToRecreate) {
  22898. return this.subMeshes[0];
  22899. }
  22900. }
  22901. this.releaseSubMeshes();
  22902. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22903. };
  22904. Mesh.prototype.subdivide = function (count) {
  22905. if (count < 1) {
  22906. return;
  22907. }
  22908. var totalIndices = this.getTotalIndices();
  22909. var subdivisionSize = (totalIndices / count) | 0;
  22910. var offset = 0;
  22911. // Ensure that subdivisionSize is a multiple of 3
  22912. while (subdivisionSize % 3 !== 0) {
  22913. subdivisionSize++;
  22914. }
  22915. this.releaseSubMeshes();
  22916. for (var index = 0; index < count; index++) {
  22917. if (offset >= totalIndices) {
  22918. break;
  22919. }
  22920. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22921. offset += subdivisionSize;
  22922. }
  22923. this.synchronizeInstances();
  22924. };
  22925. /**
  22926. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22927. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22928. * The `data` are either a numeric array either a Float32Array.
  22929. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22930. * 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).
  22931. * Note that a new underlying VertexBuffer object is created each call.
  22932. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22933. *
  22934. * Possible `kind` values :
  22935. * - BABYLON.VertexBuffer.PositionKind
  22936. * - BABYLON.VertexBuffer.UVKind
  22937. * - BABYLON.VertexBuffer.UV2Kind
  22938. * - BABYLON.VertexBuffer.UV3Kind
  22939. * - BABYLON.VertexBuffer.UV4Kind
  22940. * - BABYLON.VertexBuffer.UV5Kind
  22941. * - BABYLON.VertexBuffer.UV6Kind
  22942. * - BABYLON.VertexBuffer.ColorKind
  22943. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22944. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22945. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22946. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22947. *
  22948. * Returns the Mesh.
  22949. */
  22950. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22951. if (updatable === void 0) { updatable = false; }
  22952. if (!this._geometry) {
  22953. var vertexData = new BABYLON.VertexData();
  22954. vertexData.set(data, kind);
  22955. var scene = this.getScene();
  22956. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22957. }
  22958. else {
  22959. this._geometry.setVerticesData(kind, data, updatable, stride);
  22960. }
  22961. return this;
  22962. };
  22963. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  22964. if (updatable === void 0) { updatable = true; }
  22965. var vb = this.getVertexBuffer(kind);
  22966. if (!vb || vb.isUpdatable() === updatable) {
  22967. return;
  22968. }
  22969. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  22970. };
  22971. /**
  22972. * Sets the mesh VertexBuffer.
  22973. * Returns the Mesh.
  22974. */
  22975. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22976. if (!this._geometry) {
  22977. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  22978. }
  22979. this._geometry.setVerticesBuffer(buffer);
  22980. return this;
  22981. };
  22982. /**
  22983. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22984. * If the mesh has no geometry, it is simply returned as it is.
  22985. * The `data` are either a numeric array either a Float32Array.
  22986. * No new underlying VertexBuffer object is created.
  22987. * 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.
  22988. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22989. *
  22990. * Possible `kind` values :
  22991. * - BABYLON.VertexBuffer.PositionKind
  22992. * - BABYLON.VertexBuffer.UVKind
  22993. * - BABYLON.VertexBuffer.UV2Kind
  22994. * - BABYLON.VertexBuffer.UV3Kind
  22995. * - BABYLON.VertexBuffer.UV4Kind
  22996. * - BABYLON.VertexBuffer.UV5Kind
  22997. * - BABYLON.VertexBuffer.UV6Kind
  22998. * - BABYLON.VertexBuffer.ColorKind
  22999. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23000. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23001. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23002. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23003. *
  23004. * Returns the Mesh.
  23005. */
  23006. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23007. if (!this._geometry) {
  23008. return this;
  23009. }
  23010. if (!makeItUnique) {
  23011. this._geometry.updateVerticesData(kind, data, updateExtends);
  23012. }
  23013. else {
  23014. this.makeGeometryUnique();
  23015. this.updateVerticesData(kind, data, updateExtends, false);
  23016. }
  23017. return this;
  23018. };
  23019. /**
  23020. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23021. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23022. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23023. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23024. * Returns the Mesh.
  23025. */
  23026. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23027. if (computeNormals === void 0) { computeNormals = true; }
  23028. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23029. if (!positions) {
  23030. return this;
  23031. }
  23032. positionFunction(positions);
  23033. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23034. if (computeNormals) {
  23035. var indices = this.getIndices();
  23036. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23037. if (!normals) {
  23038. return this;
  23039. }
  23040. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23041. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23042. }
  23043. return this;
  23044. };
  23045. /**
  23046. * Creates a un-shared specific occurence of the geometry for the mesh.
  23047. * Returns the Mesh.
  23048. */
  23049. Mesh.prototype.makeGeometryUnique = function () {
  23050. if (!this._geometry) {
  23051. return this;
  23052. }
  23053. var oldGeometry = this._geometry;
  23054. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23055. oldGeometry.releaseForMesh(this, true);
  23056. geometry.applyToMesh(this);
  23057. return this;
  23058. };
  23059. /**
  23060. * Sets the mesh indices.
  23061. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23062. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23063. * This method creates a new index buffer each call.
  23064. * Returns the Mesh.
  23065. */
  23066. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23067. if (totalVertices === void 0) { totalVertices = null; }
  23068. if (updatable === void 0) { updatable = false; }
  23069. if (!this._geometry) {
  23070. var vertexData = new BABYLON.VertexData();
  23071. vertexData.indices = indices;
  23072. var scene = this.getScene();
  23073. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23074. }
  23075. else {
  23076. this._geometry.setIndices(indices, totalVertices, updatable);
  23077. }
  23078. return this;
  23079. };
  23080. /**
  23081. * Update the current index buffer
  23082. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23083. * Returns the Mesh.
  23084. */
  23085. Mesh.prototype.updateIndices = function (indices, offset) {
  23086. if (!this._geometry) {
  23087. return this;
  23088. }
  23089. this._geometry.updateIndices(indices, offset);
  23090. return this;
  23091. };
  23092. /**
  23093. * Invert the geometry to move from a right handed system to a left handed one.
  23094. * Returns the Mesh.
  23095. */
  23096. Mesh.prototype.toLeftHanded = function () {
  23097. if (!this._geometry) {
  23098. return this;
  23099. }
  23100. this._geometry.toLeftHanded();
  23101. return this;
  23102. };
  23103. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23104. if (!this._geometry) {
  23105. return this;
  23106. }
  23107. var engine = this.getScene().getEngine();
  23108. // Wireframe
  23109. var indexToBind;
  23110. if (this._unIndexed) {
  23111. indexToBind = null;
  23112. }
  23113. else {
  23114. switch (fillMode) {
  23115. case BABYLON.Material.PointFillMode:
  23116. indexToBind = null;
  23117. break;
  23118. case BABYLON.Material.WireFrameFillMode:
  23119. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23120. break;
  23121. default:
  23122. case BABYLON.Material.TriangleFillMode:
  23123. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23124. break;
  23125. }
  23126. }
  23127. // VBOs
  23128. this._geometry._bind(effect, indexToBind);
  23129. return this;
  23130. };
  23131. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23132. if (alternate === void 0) { alternate = false; }
  23133. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23134. return this;
  23135. }
  23136. this.onBeforeDrawObservable.notifyObservers(this);
  23137. var scene = this.getScene();
  23138. var engine = scene.getEngine();
  23139. // Draw order
  23140. switch (fillMode) {
  23141. case BABYLON.Material.PointFillMode:
  23142. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23143. break;
  23144. case BABYLON.Material.WireFrameFillMode:
  23145. if (this._unIndexed) {
  23146. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23147. }
  23148. else {
  23149. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23150. }
  23151. break;
  23152. default:
  23153. if (this._unIndexed) {
  23154. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23155. }
  23156. else {
  23157. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23158. }
  23159. }
  23160. if (scene._isAlternateRenderingEnabled && !alternate) {
  23161. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23162. if (!effect || !scene.activeCamera) {
  23163. return this;
  23164. }
  23165. scene._switchToAlternateCameraConfiguration(true);
  23166. this._effectiveMaterial.bindView(effect);
  23167. this._effectiveMaterial.bindViewProjection(effect);
  23168. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23169. this._draw(subMesh, fillMode, instancesCount, true);
  23170. engine.setViewport(scene.activeCamera.viewport);
  23171. scene._switchToAlternateCameraConfiguration(false);
  23172. this._effectiveMaterial.bindView(effect);
  23173. this._effectiveMaterial.bindViewProjection(effect);
  23174. }
  23175. return this;
  23176. };
  23177. /**
  23178. * Registers for this mesh a javascript function called just before the rendering process.
  23179. * This function is passed the current mesh.
  23180. * Return the Mesh.
  23181. */
  23182. Mesh.prototype.registerBeforeRender = function (func) {
  23183. this.onBeforeRenderObservable.add(func);
  23184. return this;
  23185. };
  23186. /**
  23187. * Disposes a previously registered javascript function called before the rendering.
  23188. * This function is passed the current mesh.
  23189. * Returns the Mesh.
  23190. */
  23191. Mesh.prototype.unregisterBeforeRender = function (func) {
  23192. this.onBeforeRenderObservable.removeCallback(func);
  23193. return this;
  23194. };
  23195. /**
  23196. * Registers for this mesh a javascript function called just after the rendering is complete.
  23197. * This function is passed the current mesh.
  23198. * Returns the Mesh.
  23199. */
  23200. Mesh.prototype.registerAfterRender = function (func) {
  23201. this.onAfterRenderObservable.add(func);
  23202. return this;
  23203. };
  23204. /**
  23205. * Disposes a previously registered javascript function called after the rendering.
  23206. * This function is passed the current mesh.
  23207. * Return the Mesh.
  23208. */
  23209. Mesh.prototype.unregisterAfterRender = function (func) {
  23210. this.onAfterRenderObservable.removeCallback(func);
  23211. return this;
  23212. };
  23213. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23214. var scene = this.getScene();
  23215. this._batchCache.mustReturn = false;
  23216. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23217. this._batchCache.visibleInstances[subMeshId] = null;
  23218. if (this._visibleInstances) {
  23219. var currentRenderId = scene.getRenderId();
  23220. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23221. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23222. var selfRenderId = this._renderId;
  23223. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23224. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23225. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23226. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23227. }
  23228. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23229. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23230. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23231. this._batchCache.mustReturn = true;
  23232. return this._batchCache;
  23233. }
  23234. if (currentRenderId !== selfRenderId) {
  23235. this._batchCache.renderSelf[subMeshId] = false;
  23236. }
  23237. }
  23238. this._renderIdForInstances[subMeshId] = currentRenderId;
  23239. }
  23240. return this._batchCache;
  23241. };
  23242. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23243. var visibleInstances = batch.visibleInstances[subMesh._id];
  23244. if (!visibleInstances) {
  23245. return this;
  23246. }
  23247. var matricesCount = visibleInstances.length + 1;
  23248. var bufferSize = matricesCount * 16 * 4;
  23249. var currentInstancesBufferSize = this._instancesBufferSize;
  23250. var instancesBuffer = this._instancesBuffer;
  23251. while (this._instancesBufferSize < bufferSize) {
  23252. this._instancesBufferSize *= 2;
  23253. }
  23254. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23255. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23256. }
  23257. var offset = 0;
  23258. var instancesCount = 0;
  23259. var world = this.getWorldMatrix();
  23260. if (batch.renderSelf[subMesh._id]) {
  23261. world.copyToArray(this._instancesData, offset);
  23262. offset += 16;
  23263. instancesCount++;
  23264. }
  23265. if (visibleInstances) {
  23266. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23267. var instance = visibleInstances[instanceIndex];
  23268. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23269. offset += 16;
  23270. instancesCount++;
  23271. }
  23272. }
  23273. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23274. if (instancesBuffer) {
  23275. instancesBuffer.dispose();
  23276. }
  23277. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23278. this._instancesBuffer = instancesBuffer;
  23279. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23280. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23281. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23282. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23283. }
  23284. else {
  23285. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23286. }
  23287. this._bind(subMesh, effect, fillMode);
  23288. this._draw(subMesh, fillMode, instancesCount);
  23289. engine.unbindInstanceAttributes();
  23290. return this;
  23291. };
  23292. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23293. var scene = this.getScene();
  23294. var engine = scene.getEngine();
  23295. if (hardwareInstancedRendering) {
  23296. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23297. }
  23298. else {
  23299. if (batch.renderSelf[subMesh._id]) {
  23300. // Draw
  23301. if (onBeforeDraw) {
  23302. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23303. }
  23304. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23305. }
  23306. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23307. if (visibleInstancesForSubMesh) {
  23308. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23309. var instance = visibleInstancesForSubMesh[instanceIndex];
  23310. // World
  23311. var world = instance.getWorldMatrix();
  23312. if (onBeforeDraw) {
  23313. onBeforeDraw(true, world, effectiveMaterial);
  23314. }
  23315. // Draw
  23316. this._draw(subMesh, fillMode);
  23317. }
  23318. }
  23319. }
  23320. return this;
  23321. };
  23322. /**
  23323. * Triggers the draw call for the mesh.
  23324. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23325. * Returns the Mesh.
  23326. */
  23327. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23328. this.checkOcclusionQuery();
  23329. if (this._isOccluded) {
  23330. return this;
  23331. }
  23332. var scene = this.getScene();
  23333. // Managing instances
  23334. var batch = this._getInstancesRenderList(subMesh._id);
  23335. if (batch.mustReturn) {
  23336. return this;
  23337. }
  23338. // Checking geometry state
  23339. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23340. return this;
  23341. }
  23342. this.onBeforeRenderObservable.notifyObservers(this);
  23343. var engine = scene.getEngine();
  23344. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23345. // Material
  23346. var material = subMesh.getMaterial();
  23347. if (!material) {
  23348. return this;
  23349. }
  23350. this._effectiveMaterial = material;
  23351. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23352. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23353. return this;
  23354. }
  23355. }
  23356. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23357. return this;
  23358. }
  23359. // Alpha mode
  23360. if (enableAlphaMode) {
  23361. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23362. }
  23363. // Outline - step 1
  23364. var savedDepthWrite = engine.getDepthWrite();
  23365. if (this.renderOutline) {
  23366. engine.setDepthWrite(false);
  23367. scene.getOutlineRenderer().render(subMesh, batch);
  23368. engine.setDepthWrite(savedDepthWrite);
  23369. }
  23370. var effect;
  23371. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23372. effect = subMesh.effect;
  23373. }
  23374. else {
  23375. effect = this._effectiveMaterial.getEffect();
  23376. }
  23377. if (!effect) {
  23378. return this;
  23379. }
  23380. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23381. if (this._effectiveMaterial.forceDepthWrite) {
  23382. engine.setDepthWrite(true);
  23383. }
  23384. // Bind
  23385. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  23386. if (!hardwareInstancedRendering) {
  23387. this._bind(subMesh, effect, fillMode);
  23388. }
  23389. var world = this.getWorldMatrix();
  23390. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23391. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  23392. }
  23393. else {
  23394. this._effectiveMaterial.bind(world, this);
  23395. }
  23396. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  23397. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  23398. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23399. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  23400. }
  23401. // Draw
  23402. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23403. // Unbind
  23404. this._effectiveMaterial.unbind();
  23405. // Outline - step 2
  23406. if (this.renderOutline && savedDepthWrite) {
  23407. engine.setDepthWrite(true);
  23408. engine.setColorWrite(false);
  23409. scene.getOutlineRenderer().render(subMesh, batch);
  23410. engine.setColorWrite(true);
  23411. }
  23412. // Overlay
  23413. if (this.renderOverlay) {
  23414. var currentMode = engine.getAlphaMode();
  23415. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23416. scene.getOutlineRenderer().render(subMesh, batch, true);
  23417. engine.setAlphaMode(currentMode);
  23418. }
  23419. this.onAfterRenderObservable.notifyObservers(this);
  23420. return this;
  23421. };
  23422. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23423. if (isInstance) {
  23424. effectiveMaterial.bindOnlyWorldMatrix(world);
  23425. }
  23426. return this;
  23427. };
  23428. /**
  23429. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23430. */
  23431. Mesh.prototype.getEmittedParticleSystems = function () {
  23432. var results = new Array();
  23433. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23434. var particleSystem = this.getScene().particleSystems[index];
  23435. if (particleSystem.emitter === this) {
  23436. results.push(particleSystem);
  23437. }
  23438. }
  23439. return results;
  23440. };
  23441. /**
  23442. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23443. */
  23444. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23445. var results = new Array();
  23446. var descendants = this.getDescendants();
  23447. descendants.push(this);
  23448. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23449. var particleSystem = this.getScene().particleSystems[index];
  23450. var emitter = particleSystem.emitter;
  23451. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23452. results.push(particleSystem);
  23453. }
  23454. }
  23455. return results;
  23456. };
  23457. Mesh.prototype._checkDelayState = function () {
  23458. var scene = this.getScene();
  23459. if (this._geometry) {
  23460. this._geometry.load(scene);
  23461. }
  23462. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23463. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23464. this._queueLoad(this, scene);
  23465. }
  23466. return this;
  23467. };
  23468. Mesh.prototype._queueLoad = function (mesh, scene) {
  23469. var _this = this;
  23470. scene._addPendingData(mesh);
  23471. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23472. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23473. if (data instanceof ArrayBuffer) {
  23474. _this._delayLoadingFunction(data, _this);
  23475. }
  23476. else {
  23477. _this._delayLoadingFunction(JSON.parse(data), _this);
  23478. }
  23479. _this.instances.forEach(function (instance) {
  23480. instance._syncSubMeshes();
  23481. });
  23482. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23483. scene._removePendingData(_this);
  23484. }, function () { }, scene.database, getBinaryData);
  23485. return this;
  23486. };
  23487. /**
  23488. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23489. */
  23490. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23491. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23492. return false;
  23493. }
  23494. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23495. return false;
  23496. }
  23497. this._checkDelayState();
  23498. return true;
  23499. };
  23500. /**
  23501. * Sets the mesh material by the material or multiMaterial `id` property.
  23502. * The material `id` is a string identifying the material or the multiMaterial.
  23503. * This method returns the Mesh.
  23504. */
  23505. Mesh.prototype.setMaterialByID = function (id) {
  23506. var materials = this.getScene().materials;
  23507. var index;
  23508. for (index = materials.length - 1; index > -1; index--) {
  23509. if (materials[index].id === id) {
  23510. this.material = materials[index];
  23511. return this;
  23512. }
  23513. }
  23514. // Multi
  23515. var multiMaterials = this.getScene().multiMaterials;
  23516. for (index = multiMaterials.length - 1; index > -1; index--) {
  23517. if (multiMaterials[index].id === id) {
  23518. this.material = multiMaterials[index];
  23519. return this;
  23520. }
  23521. }
  23522. return this;
  23523. };
  23524. /**
  23525. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23526. */
  23527. Mesh.prototype.getAnimatables = function () {
  23528. var results = new Array();
  23529. if (this.material) {
  23530. results.push(this.material);
  23531. }
  23532. if (this.skeleton) {
  23533. results.push(this.skeleton);
  23534. }
  23535. return results;
  23536. };
  23537. /**
  23538. * Modifies the mesh geometry according to the passed transformation matrix.
  23539. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23540. * The mesh normals are modified accordingly the same transformation.
  23541. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23542. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23543. * Returns the Mesh.
  23544. */
  23545. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23546. // Position
  23547. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23548. return this;
  23549. }
  23550. var submeshes = this.subMeshes.splice(0);
  23551. this._resetPointsArrayCache();
  23552. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23553. var temp = new Array();
  23554. var index;
  23555. for (index = 0; index < data.length; index += 3) {
  23556. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23557. }
  23558. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23559. // Normals
  23560. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23561. return this;
  23562. }
  23563. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23564. temp = [];
  23565. for (index = 0; index < data.length; index += 3) {
  23566. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23567. }
  23568. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23569. // flip faces?
  23570. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23571. this.flipFaces();
  23572. }
  23573. // Restore submeshes
  23574. this.releaseSubMeshes();
  23575. this.subMeshes = submeshes;
  23576. return this;
  23577. };
  23578. /**
  23579. * Modifies the mesh geometry according to its own current World Matrix.
  23580. * The mesh World Matrix is then reset.
  23581. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23582. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23583. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23584. * Returns the Mesh.
  23585. */
  23586. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23587. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23588. this.scaling.copyFromFloats(1, 1, 1);
  23589. this.position.copyFromFloats(0, 0, 0);
  23590. this.rotation.copyFromFloats(0, 0, 0);
  23591. //only if quaternion is already set
  23592. if (this.rotationQuaternion) {
  23593. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23594. }
  23595. this._worldMatrix = BABYLON.Matrix.Identity();
  23596. return this;
  23597. };
  23598. Object.defineProperty(Mesh.prototype, "_positions", {
  23599. // Cache
  23600. get: function () {
  23601. if (this._geometry) {
  23602. return this._geometry._positions;
  23603. }
  23604. return null;
  23605. },
  23606. enumerable: true,
  23607. configurable: true
  23608. });
  23609. Mesh.prototype._resetPointsArrayCache = function () {
  23610. if (this._geometry) {
  23611. this._geometry._resetPointsArrayCache();
  23612. }
  23613. return this;
  23614. };
  23615. Mesh.prototype._generatePointsArray = function () {
  23616. if (this._geometry) {
  23617. return this._geometry._generatePointsArray();
  23618. }
  23619. return false;
  23620. };
  23621. /**
  23622. * Returns a new Mesh object generated from the current mesh properties.
  23623. * This method must not get confused with createInstance().
  23624. * The parameter `name` is a string, the name given to the new mesh.
  23625. * The optional parameter `newParent` can be any Node object (default `null`).
  23626. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23627. * 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.
  23628. */
  23629. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23630. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23631. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23632. };
  23633. /**
  23634. * Disposes the mesh.
  23635. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23636. */
  23637. Mesh.prototype.dispose = function (doNotRecurse) {
  23638. var _this = this;
  23639. this.morphTargetManager = null;
  23640. if (this._geometry) {
  23641. this._geometry.releaseForMesh(this, true);
  23642. }
  23643. // Sources
  23644. var meshes = this.getScene().meshes;
  23645. meshes.forEach(function (mesh) {
  23646. if (mesh._source && mesh._source === _this) {
  23647. mesh._source = null;
  23648. }
  23649. });
  23650. this._source = null;
  23651. // Instances
  23652. if (this._instancesBuffer) {
  23653. this._instancesBuffer.dispose();
  23654. this._instancesBuffer = null;
  23655. }
  23656. while (this.instances.length) {
  23657. this.instances[0].dispose();
  23658. }
  23659. // Highlight layers.
  23660. var highlightLayers = this.getScene().highlightLayers;
  23661. for (var i = 0; i < highlightLayers.length; i++) {
  23662. var highlightLayer = highlightLayers[i];
  23663. if (highlightLayer) {
  23664. highlightLayer.removeMesh(this);
  23665. highlightLayer.removeExcludedMesh(this);
  23666. }
  23667. }
  23668. _super.prototype.dispose.call(this, doNotRecurse);
  23669. };
  23670. /**
  23671. * Modifies the mesh geometry according to a displacement map.
  23672. * 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.
  23673. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23674. * This method returns nothing.
  23675. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23676. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23677. * 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.
  23678. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23679. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23680. *
  23681. * Returns the Mesh.
  23682. */
  23683. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23684. var _this = this;
  23685. var scene = this.getScene();
  23686. var onload = function (img) {
  23687. // Getting height map data
  23688. var canvas = document.createElement("canvas");
  23689. var context = canvas.getContext("2d");
  23690. var heightMapWidth = img.width;
  23691. var heightMapHeight = img.height;
  23692. canvas.width = heightMapWidth;
  23693. canvas.height = heightMapHeight;
  23694. context.drawImage(img, 0, 0);
  23695. // Create VertexData from map data
  23696. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23697. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23698. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23699. //execute success callback, if set
  23700. if (onSuccess) {
  23701. onSuccess(_this);
  23702. }
  23703. };
  23704. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23705. return this;
  23706. };
  23707. /**
  23708. * Modifies the mesh geometry according to a displacementMap buffer.
  23709. * 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.
  23710. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23711. * This method returns nothing.
  23712. * 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.
  23713. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23714. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23715. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23716. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23717. *
  23718. * Returns the Mesh.
  23719. */
  23720. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23721. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23722. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23723. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23724. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23725. return this;
  23726. }
  23727. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23728. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23729. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23730. var position = BABYLON.Vector3.Zero();
  23731. var normal = BABYLON.Vector3.Zero();
  23732. var uv = BABYLON.Vector2.Zero();
  23733. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23734. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23735. for (var index = 0; index < positions.length; index += 3) {
  23736. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23737. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23738. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23739. // Compute height
  23740. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23741. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23742. var pos = (u + v * heightMapWidth) * 4;
  23743. var r = buffer[pos] / 255.0;
  23744. var g = buffer[pos + 1] / 255.0;
  23745. var b = buffer[pos + 2] / 255.0;
  23746. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23747. normal.normalize();
  23748. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23749. position = position.add(normal);
  23750. position.toArray(positions, index);
  23751. }
  23752. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23753. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23754. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23755. return this;
  23756. };
  23757. /**
  23758. * Modify the mesh to get a flat shading rendering.
  23759. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23760. * This method returns the Mesh.
  23761. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23762. */
  23763. Mesh.prototype.convertToFlatShadedMesh = function () {
  23764. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23765. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23766. var kinds = this.getVerticesDataKinds();
  23767. var vbs = {};
  23768. var data = {};
  23769. var newdata = {};
  23770. var updatableNormals = false;
  23771. var kindIndex;
  23772. var kind;
  23773. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23774. kind = kinds[kindIndex];
  23775. var vertexBuffer = this.getVertexBuffer(kind);
  23776. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23777. updatableNormals = vertexBuffer.isUpdatable();
  23778. kinds.splice(kindIndex, 1);
  23779. kindIndex--;
  23780. continue;
  23781. }
  23782. vbs[kind] = vertexBuffer;
  23783. data[kind] = vbs[kind].getData();
  23784. newdata[kind] = [];
  23785. }
  23786. // Save previous submeshes
  23787. var previousSubmeshes = this.subMeshes.slice(0);
  23788. var indices = this.getIndices();
  23789. var totalIndices = this.getTotalIndices();
  23790. // Generating unique vertices per face
  23791. var index;
  23792. for (index = 0; index < totalIndices; index++) {
  23793. var vertexIndex = indices[index];
  23794. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23795. kind = kinds[kindIndex];
  23796. var stride = vbs[kind].getStrideSize();
  23797. for (var offset = 0; offset < stride; offset++) {
  23798. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23799. }
  23800. }
  23801. }
  23802. // Updating faces & normal
  23803. var normals = [];
  23804. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23805. for (index = 0; index < totalIndices; index += 3) {
  23806. indices[index] = index;
  23807. indices[index + 1] = index + 1;
  23808. indices[index + 2] = index + 2;
  23809. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23810. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23811. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23812. var p1p2 = p1.subtract(p2);
  23813. var p3p2 = p3.subtract(p2);
  23814. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23815. // Store same normals for every vertex
  23816. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23817. normals.push(normal.x);
  23818. normals.push(normal.y);
  23819. normals.push(normal.z);
  23820. }
  23821. }
  23822. this.setIndices(indices);
  23823. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23824. // Updating vertex buffers
  23825. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23826. kind = kinds[kindIndex];
  23827. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23828. }
  23829. // Updating submeshes
  23830. this.releaseSubMeshes();
  23831. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23832. var previousOne = previousSubmeshes[submeshIndex];
  23833. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23834. }
  23835. this.synchronizeInstances();
  23836. return this;
  23837. };
  23838. /**
  23839. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23840. * In other words, more vertices, no more indices and a single bigger VBO.
  23841. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23842. * Returns the Mesh.
  23843. */
  23844. Mesh.prototype.convertToUnIndexedMesh = function () {
  23845. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23846. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23847. var kinds = this.getVerticesDataKinds();
  23848. var vbs = {};
  23849. var data = {};
  23850. var newdata = {};
  23851. var kindIndex;
  23852. var kind;
  23853. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23854. kind = kinds[kindIndex];
  23855. var vertexBuffer = this.getVertexBuffer(kind);
  23856. vbs[kind] = vertexBuffer;
  23857. data[kind] = vbs[kind].getData();
  23858. newdata[kind] = [];
  23859. }
  23860. // Save previous submeshes
  23861. var previousSubmeshes = this.subMeshes.slice(0);
  23862. var indices = this.getIndices();
  23863. var totalIndices = this.getTotalIndices();
  23864. // Generating unique vertices per face
  23865. var index;
  23866. for (index = 0; index < totalIndices; index++) {
  23867. var vertexIndex = indices[index];
  23868. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23869. kind = kinds[kindIndex];
  23870. var stride = vbs[kind].getStrideSize();
  23871. for (var offset = 0; offset < stride; offset++) {
  23872. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23873. }
  23874. }
  23875. }
  23876. // Updating indices
  23877. for (index = 0; index < totalIndices; index += 3) {
  23878. indices[index] = index;
  23879. indices[index + 1] = index + 1;
  23880. indices[index + 2] = index + 2;
  23881. }
  23882. this.setIndices(indices);
  23883. // Updating vertex buffers
  23884. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23885. kind = kinds[kindIndex];
  23886. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23887. }
  23888. // Updating submeshes
  23889. this.releaseSubMeshes();
  23890. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23891. var previousOne = previousSubmeshes[submeshIndex];
  23892. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23893. }
  23894. this._unIndexed = true;
  23895. this.synchronizeInstances();
  23896. return this;
  23897. };
  23898. /**
  23899. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23900. * This method returns the Mesh.
  23901. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23902. */
  23903. Mesh.prototype.flipFaces = function (flipNormals) {
  23904. if (flipNormals === void 0) { flipNormals = false; }
  23905. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23906. var i;
  23907. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  23908. for (i = 0; i < vertex_data.normals.length; i++) {
  23909. vertex_data.normals[i] *= -1;
  23910. }
  23911. }
  23912. if (vertex_data.indices) {
  23913. var temp;
  23914. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23915. // reassign indices
  23916. temp = vertex_data.indices[i + 1];
  23917. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23918. vertex_data.indices[i + 2] = temp;
  23919. }
  23920. }
  23921. vertex_data.applyToMesh(this);
  23922. return this;
  23923. };
  23924. // Instances
  23925. /**
  23926. * Creates a new InstancedMesh object from the mesh model.
  23927. * An instance shares the same properties and the same material than its model.
  23928. * Only these properties of each instance can then be set individually :
  23929. * - position
  23930. * - rotation
  23931. * - rotationQuaternion
  23932. * - setPivotMatrix
  23933. * - scaling
  23934. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23935. * Warning : this method is not supported for Line mesh and LineSystem
  23936. */
  23937. Mesh.prototype.createInstance = function (name) {
  23938. return new BABYLON.InstancedMesh(name, this);
  23939. };
  23940. /**
  23941. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  23942. * After this call, all the mesh instances have the same submeshes than the current mesh.
  23943. * This method returns the Mesh.
  23944. */
  23945. Mesh.prototype.synchronizeInstances = function () {
  23946. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  23947. var instance = this.instances[instanceIndex];
  23948. instance._syncSubMeshes();
  23949. }
  23950. return this;
  23951. };
  23952. /**
  23953. * Simplify the mesh according to the given array of settings.
  23954. * Function will return immediately and will simplify async. It returns the Mesh.
  23955. * @param settings a collection of simplification settings.
  23956. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23957. * @param type the type of simplification to run.
  23958. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23959. */
  23960. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23961. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23962. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23963. this.getScene().simplificationQueue.addTask({
  23964. settings: settings,
  23965. parallelProcessing: parallelProcessing,
  23966. mesh: this,
  23967. simplificationType: simplificationType,
  23968. successCallback: successCallback
  23969. });
  23970. return this;
  23971. };
  23972. /**
  23973. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23974. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23975. * This should be used together with the simplification to avoid disappearing triangles.
  23976. * Returns the Mesh.
  23977. * @param successCallback an optional success callback to be called after the optimization finished.
  23978. */
  23979. Mesh.prototype.optimizeIndices = function (successCallback) {
  23980. var _this = this;
  23981. var indices = this.getIndices();
  23982. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23983. if (!positions || !indices) {
  23984. return this;
  23985. }
  23986. var vectorPositions = new Array();
  23987. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23988. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23989. }
  23990. var dupes = new Array();
  23991. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23992. var realPos = vectorPositions.length - 1 - iteration;
  23993. var testedPosition = vectorPositions[realPos];
  23994. for (var j = 0; j < realPos; ++j) {
  23995. var againstPosition = vectorPositions[j];
  23996. if (testedPosition.equals(againstPosition)) {
  23997. dupes[realPos] = j;
  23998. break;
  23999. }
  24000. }
  24001. }, function () {
  24002. for (var i = 0; i < indices.length; ++i) {
  24003. indices[i] = dupes[indices[i]] || indices[i];
  24004. }
  24005. //indices are now reordered
  24006. var originalSubMeshes = _this.subMeshes.slice(0);
  24007. _this.setIndices(indices);
  24008. _this.subMeshes = originalSubMeshes;
  24009. if (successCallback) {
  24010. successCallback(_this);
  24011. }
  24012. });
  24013. return this;
  24014. };
  24015. Mesh.prototype.serialize = function (serializationObject) {
  24016. serializationObject.name = this.name;
  24017. serializationObject.id = this.id;
  24018. serializationObject.type = this.getClassName();
  24019. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24020. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24021. }
  24022. serializationObject.position = this.position.asArray();
  24023. if (this.rotationQuaternion) {
  24024. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24025. }
  24026. else if (this.rotation) {
  24027. serializationObject.rotation = this.rotation.asArray();
  24028. }
  24029. serializationObject.scaling = this.scaling.asArray();
  24030. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24031. serializationObject.isEnabled = this.isEnabled();
  24032. serializationObject.isVisible = this.isVisible;
  24033. serializationObject.infiniteDistance = this.infiniteDistance;
  24034. serializationObject.pickable = this.isPickable;
  24035. serializationObject.receiveShadows = this.receiveShadows;
  24036. serializationObject.billboardMode = this.billboardMode;
  24037. serializationObject.visibility = this.visibility;
  24038. serializationObject.checkCollisions = this.checkCollisions;
  24039. serializationObject.isBlocker = this.isBlocker;
  24040. // Parent
  24041. if (this.parent) {
  24042. serializationObject.parentId = this.parent.id;
  24043. }
  24044. // Geometry
  24045. var geometry = this._geometry;
  24046. if (geometry) {
  24047. var geometryId = geometry.id;
  24048. serializationObject.geometryId = geometryId;
  24049. // SubMeshes
  24050. serializationObject.subMeshes = [];
  24051. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24052. var subMesh = this.subMeshes[subIndex];
  24053. serializationObject.subMeshes.push({
  24054. materialIndex: subMesh.materialIndex,
  24055. verticesStart: subMesh.verticesStart,
  24056. verticesCount: subMesh.verticesCount,
  24057. indexStart: subMesh.indexStart,
  24058. indexCount: subMesh.indexCount
  24059. });
  24060. }
  24061. }
  24062. // Material
  24063. if (this.material) {
  24064. serializationObject.materialId = this.material.id;
  24065. }
  24066. else {
  24067. this.material = null;
  24068. }
  24069. // Morph targets
  24070. if (this.morphTargetManager) {
  24071. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24072. }
  24073. // Skeleton
  24074. if (this.skeleton) {
  24075. serializationObject.skeletonId = this.skeleton.id;
  24076. }
  24077. // Physics
  24078. //TODO implement correct serialization for physics impostors.
  24079. var impostor = this.getPhysicsImpostor();
  24080. if (impostor) {
  24081. serializationObject.physicsMass = impostor.getParam("mass");
  24082. serializationObject.physicsFriction = impostor.getParam("friction");
  24083. serializationObject.physicsRestitution = impostor.getParam("mass");
  24084. serializationObject.physicsImpostor = impostor.type;
  24085. }
  24086. // Metadata
  24087. if (this.metadata) {
  24088. serializationObject.metadata = this.metadata;
  24089. }
  24090. // Instances
  24091. serializationObject.instances = [];
  24092. for (var index = 0; index < this.instances.length; index++) {
  24093. var instance = this.instances[index];
  24094. var serializationInstance = {
  24095. name: instance.name,
  24096. position: instance.position.asArray(),
  24097. scaling: instance.scaling.asArray()
  24098. };
  24099. if (instance.rotationQuaternion) {
  24100. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24101. }
  24102. else if (instance.rotation) {
  24103. serializationInstance.rotation = instance.rotation.asArray();
  24104. }
  24105. serializationObject.instances.push(serializationInstance);
  24106. // Animations
  24107. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24108. serializationInstance.ranges = instance.serializeAnimationRanges();
  24109. }
  24110. //
  24111. // Animations
  24112. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24113. serializationObject.ranges = this.serializeAnimationRanges();
  24114. // Layer mask
  24115. serializationObject.layerMask = this.layerMask;
  24116. // Alpha
  24117. serializationObject.alphaIndex = this.alphaIndex;
  24118. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24119. // Overlay
  24120. serializationObject.overlayAlpha = this.overlayAlpha;
  24121. serializationObject.overlayColor = this.overlayColor.asArray();
  24122. serializationObject.renderOverlay = this.renderOverlay;
  24123. // Fog
  24124. serializationObject.applyFog = this.applyFog;
  24125. // Action Manager
  24126. if (this.actionManager) {
  24127. serializationObject.actions = this.actionManager.serialize(this.name);
  24128. }
  24129. };
  24130. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24131. if (!this.geometry) {
  24132. return;
  24133. }
  24134. this._markSubMeshesAsAttributesDirty();
  24135. var morphTargetManager = this._morphTargetManager;
  24136. if (morphTargetManager && morphTargetManager.vertexCount) {
  24137. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24138. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24139. this.morphTargetManager = null;
  24140. return;
  24141. }
  24142. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24143. var morphTarget = morphTargetManager.getActiveTarget(index);
  24144. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  24145. if (morphTarget.hasNormals) {
  24146. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  24147. }
  24148. if (morphTarget.hasTangents) {
  24149. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  24150. }
  24151. }
  24152. }
  24153. else {
  24154. var index = 0;
  24155. // Positions
  24156. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24157. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24158. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24159. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24160. }
  24161. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24162. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24163. }
  24164. index++;
  24165. }
  24166. }
  24167. };
  24168. // Statics
  24169. /**
  24170. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24171. * The parameter `parsedMesh` is the mesh to be copied.
  24172. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24173. */
  24174. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24175. var mesh;
  24176. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24177. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24178. }
  24179. else {
  24180. mesh = new Mesh(parsedMesh.name, scene);
  24181. }
  24182. mesh.id = parsedMesh.id;
  24183. if (BABYLON.Tags) {
  24184. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24185. }
  24186. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24187. if (parsedMesh.metadata !== undefined) {
  24188. mesh.metadata = parsedMesh.metadata;
  24189. }
  24190. if (parsedMesh.rotationQuaternion) {
  24191. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24192. }
  24193. else if (parsedMesh.rotation) {
  24194. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24195. }
  24196. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24197. if (parsedMesh.localMatrix) {
  24198. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24199. }
  24200. else if (parsedMesh.pivotMatrix) {
  24201. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24202. }
  24203. mesh.setEnabled(parsedMesh.isEnabled);
  24204. mesh.isVisible = parsedMesh.isVisible;
  24205. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24206. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24207. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24208. if (parsedMesh.applyFog !== undefined) {
  24209. mesh.applyFog = parsedMesh.applyFog;
  24210. }
  24211. if (parsedMesh.pickable !== undefined) {
  24212. mesh.isPickable = parsedMesh.pickable;
  24213. }
  24214. if (parsedMesh.alphaIndex !== undefined) {
  24215. mesh.alphaIndex = parsedMesh.alphaIndex;
  24216. }
  24217. mesh.receiveShadows = parsedMesh.receiveShadows;
  24218. mesh.billboardMode = parsedMesh.billboardMode;
  24219. if (parsedMesh.visibility !== undefined) {
  24220. mesh.visibility = parsedMesh.visibility;
  24221. }
  24222. mesh.checkCollisions = parsedMesh.checkCollisions;
  24223. if (parsedMesh.isBlocker !== undefined) {
  24224. mesh.isBlocker = parsedMesh.isBlocker;
  24225. }
  24226. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24227. // freezeWorldMatrix
  24228. if (parsedMesh.freezeWorldMatrix) {
  24229. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24230. }
  24231. // Parent
  24232. if (parsedMesh.parentId) {
  24233. mesh._waitingParentId = parsedMesh.parentId;
  24234. }
  24235. // Actions
  24236. if (parsedMesh.actions !== undefined) {
  24237. mesh._waitingActions = parsedMesh.actions;
  24238. }
  24239. // Overlay
  24240. if (parsedMesh.overlayAlpha !== undefined) {
  24241. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24242. }
  24243. if (parsedMesh.overlayColor !== undefined) {
  24244. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24245. }
  24246. if (parsedMesh.renderOverlay !== undefined) {
  24247. mesh.renderOverlay = parsedMesh.renderOverlay;
  24248. }
  24249. // Geometry
  24250. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24251. if (parsedMesh.delayLoadingFile) {
  24252. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24253. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24254. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24255. if (parsedMesh._binaryInfo) {
  24256. mesh._binaryInfo = parsedMesh._binaryInfo;
  24257. }
  24258. mesh._delayInfo = [];
  24259. if (parsedMesh.hasUVs) {
  24260. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24261. }
  24262. if (parsedMesh.hasUVs2) {
  24263. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24264. }
  24265. if (parsedMesh.hasUVs3) {
  24266. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24267. }
  24268. if (parsedMesh.hasUVs4) {
  24269. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24270. }
  24271. if (parsedMesh.hasUVs5) {
  24272. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24273. }
  24274. if (parsedMesh.hasUVs6) {
  24275. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24276. }
  24277. if (parsedMesh.hasColors) {
  24278. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24279. }
  24280. if (parsedMesh.hasMatricesIndices) {
  24281. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24282. }
  24283. if (parsedMesh.hasMatricesWeights) {
  24284. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24285. }
  24286. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24287. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24288. mesh._checkDelayState();
  24289. }
  24290. }
  24291. else {
  24292. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24293. }
  24294. // Material
  24295. if (parsedMesh.materialId) {
  24296. mesh.setMaterialByID(parsedMesh.materialId);
  24297. }
  24298. else {
  24299. mesh.material = null;
  24300. }
  24301. // Morph targets
  24302. if (parsedMesh.morphTargetManagerId > -1) {
  24303. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24304. }
  24305. // Skeleton
  24306. if (parsedMesh.skeletonId > -1) {
  24307. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24308. if (parsedMesh.numBoneInfluencers) {
  24309. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24310. }
  24311. }
  24312. // Animations
  24313. if (parsedMesh.animations) {
  24314. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24315. var parsedAnimation = parsedMesh.animations[animationIndex];
  24316. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24317. }
  24318. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24319. }
  24320. if (parsedMesh.autoAnimate) {
  24321. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24322. }
  24323. // Layer Mask
  24324. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24325. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24326. }
  24327. else {
  24328. mesh.layerMask = 0x0FFFFFFF;
  24329. }
  24330. // Physics
  24331. if (parsedMesh.physicsImpostor) {
  24332. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24333. mass: parsedMesh.physicsMass,
  24334. friction: parsedMesh.physicsFriction,
  24335. restitution: parsedMesh.physicsRestitution
  24336. }, scene);
  24337. }
  24338. // Instances
  24339. if (parsedMesh.instances) {
  24340. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24341. var parsedInstance = parsedMesh.instances[index];
  24342. var instance = mesh.createInstance(parsedInstance.name);
  24343. if (BABYLON.Tags) {
  24344. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24345. }
  24346. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24347. if (parsedInstance.parentId) {
  24348. instance._waitingParentId = parsedInstance.parentId;
  24349. }
  24350. if (parsedInstance.rotationQuaternion) {
  24351. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24352. }
  24353. else if (parsedInstance.rotation) {
  24354. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24355. }
  24356. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24357. instance.checkCollisions = mesh.checkCollisions;
  24358. if (parsedMesh.animations) {
  24359. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24360. parsedAnimation = parsedMesh.animations[animationIndex];
  24361. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24362. }
  24363. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24364. }
  24365. }
  24366. }
  24367. return mesh;
  24368. };
  24369. /**
  24370. * Creates a ribbon mesh.
  24371. * Please consider using the same method from the MeshBuilder class instead.
  24372. * 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.
  24373. *
  24374. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24375. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24376. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24377. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24378. * 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.
  24379. * 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.
  24380. * 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
  24381. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24382. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24384. */
  24385. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24386. if (closeArray === void 0) { closeArray = false; }
  24387. if (updatable === void 0) { updatable = false; }
  24388. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24389. pathArray: pathArray,
  24390. closeArray: closeArray,
  24391. closePath: closePath,
  24392. offset: offset,
  24393. updatable: updatable,
  24394. sideOrientation: sideOrientation,
  24395. instance: instance
  24396. }, scene);
  24397. };
  24398. /**
  24399. * Creates a plane polygonal mesh. By default, this is a disc.
  24400. * Please consider using the same method from the MeshBuilder class instead.
  24401. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24402. * 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.
  24403. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24404. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24405. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24406. */
  24407. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24408. if (scene === void 0) { scene = null; }
  24409. var options = {
  24410. radius: radius,
  24411. tessellation: tessellation,
  24412. sideOrientation: sideOrientation,
  24413. updatable: updatable
  24414. };
  24415. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24416. };
  24417. /**
  24418. * Creates a box mesh.
  24419. * Please consider using the same method from the MeshBuilder class instead.
  24420. * The parameter `size` sets the size (float) of each box side (default 1).
  24421. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24422. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24423. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24424. */
  24425. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24426. if (scene === void 0) { scene = null; }
  24427. var options = {
  24428. size: size,
  24429. sideOrientation: sideOrientation,
  24430. updatable: updatable
  24431. };
  24432. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24433. };
  24434. /**
  24435. * Creates a sphere mesh.
  24436. * Please consider using the same method from the MeshBuilder class instead.
  24437. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24438. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24442. */
  24443. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24444. var options = {
  24445. segments: segments,
  24446. diameterX: diameter,
  24447. diameterY: diameter,
  24448. diameterZ: diameter,
  24449. sideOrientation: sideOrientation,
  24450. updatable: updatable
  24451. };
  24452. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24453. };
  24454. /**
  24455. * Creates a cylinder or a cone mesh.
  24456. * Please consider using the same method from the MeshBuilder class instead.
  24457. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24458. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24459. * 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.
  24460. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24461. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24462. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24463. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24464. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24465. */
  24466. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24467. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24468. if (scene !== undefined) {
  24469. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24470. updatable = scene;
  24471. }
  24472. scene = subdivisions;
  24473. subdivisions = 1;
  24474. }
  24475. var options = {
  24476. height: height,
  24477. diameterTop: diameterTop,
  24478. diameterBottom: diameterBottom,
  24479. tessellation: tessellation,
  24480. subdivisions: subdivisions,
  24481. sideOrientation: sideOrientation,
  24482. updatable: updatable
  24483. };
  24484. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24485. };
  24486. // Torus (Code from SharpDX.org)
  24487. /**
  24488. * Creates a torus mesh.
  24489. * Please consider using the same method from the MeshBuilder class instead.
  24490. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24491. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24492. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24496. */
  24497. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24498. var options = {
  24499. diameter: diameter,
  24500. thickness: thickness,
  24501. tessellation: tessellation,
  24502. sideOrientation: sideOrientation,
  24503. updatable: updatable
  24504. };
  24505. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24506. };
  24507. /**
  24508. * Creates a torus knot mesh.
  24509. * Please consider using the same method from the MeshBuilder class instead.
  24510. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24511. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24512. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24513. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24514. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24515. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24516. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24517. */
  24518. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24519. var options = {
  24520. radius: radius,
  24521. tube: tube,
  24522. radialSegments: radialSegments,
  24523. tubularSegments: tubularSegments,
  24524. p: p,
  24525. q: q,
  24526. sideOrientation: sideOrientation,
  24527. updatable: updatable
  24528. };
  24529. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24530. };
  24531. /**
  24532. * Creates a line mesh.
  24533. * Please consider using the same method from the MeshBuilder class instead.
  24534. * 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.
  24535. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24536. * The parameter `points` is an array successive Vector3.
  24537. * 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
  24538. * When updating an instance, remember that only point positions can change, not the number of points.
  24539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24540. */
  24541. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24542. if (scene === void 0) { scene = null; }
  24543. if (updatable === void 0) { updatable = false; }
  24544. if (instance === void 0) { instance = null; }
  24545. var options = {
  24546. points: points,
  24547. updatable: updatable,
  24548. instance: instance
  24549. };
  24550. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24551. };
  24552. /**
  24553. * Creates a dashed line mesh.
  24554. * Please consider using the same method from the MeshBuilder class instead.
  24555. * 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.
  24556. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24557. * The parameter `points` is an array successive Vector3.
  24558. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24559. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24560. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24561. * 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
  24562. * When updating an instance, remember that only point positions can change, not the number of points.
  24563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24564. */
  24565. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24566. if (scene === void 0) { scene = null; }
  24567. var options = {
  24568. points: points,
  24569. dashSize: dashSize,
  24570. gapSize: gapSize,
  24571. dashNb: dashNb,
  24572. updatable: updatable,
  24573. instance: instance
  24574. };
  24575. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24576. };
  24577. /**
  24578. * Creates a polygon mesh.
  24579. * Please consider using the same method from the MeshBuilder class instead.
  24580. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24581. * 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.
  24582. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24583. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24584. * Remember you can only change the shape positions, not their number when updating a polygon.
  24585. */
  24586. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24587. var options = {
  24588. shape: shape,
  24589. holes: holes,
  24590. updatable: updatable,
  24591. sideOrientation: sideOrientation
  24592. };
  24593. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24594. };
  24595. /**
  24596. * Creates an extruded polygon mesh, with depth in the Y direction.
  24597. * Please consider using the same method from the MeshBuilder class instead.
  24598. */
  24599. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24600. var options = {
  24601. shape: shape,
  24602. holes: holes,
  24603. depth: depth,
  24604. updatable: updatable,
  24605. sideOrientation: sideOrientation
  24606. };
  24607. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24608. };
  24609. /**
  24610. * Creates an extruded shape mesh.
  24611. * 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.
  24612. * Please consider using the same method from the MeshBuilder class instead.
  24613. *
  24614. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24615. * 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
  24616. * extruded along the Z axis.
  24617. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24618. * 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.
  24619. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24620. * 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
  24621. * 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
  24622. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24624. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24625. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24626. */
  24627. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24628. if (scene === void 0) { scene = null; }
  24629. var options = {
  24630. shape: shape,
  24631. path: path,
  24632. scale: scale,
  24633. rotation: rotation,
  24634. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24635. sideOrientation: sideOrientation,
  24636. instance: instance,
  24637. updatable: updatable
  24638. };
  24639. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24640. };
  24641. /**
  24642. * Creates an custom extruded shape mesh.
  24643. * 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.
  24644. * Please consider using the same method from the MeshBuilder class instead.
  24645. *
  24646. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24647. * 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
  24648. * extruded along the Z axis.
  24649. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24650. * 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
  24651. * and the distance of this point from the begining of the path :
  24652. * ```javascript
  24653. * var rotationFunction = function(i, distance) {
  24654. * // do things
  24655. * return rotationValue; }
  24656. * ```
  24657. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24658. * 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
  24659. * and the distance of this point from the begining of the path :
  24660. * ```javascript
  24661. * var scaleFunction = function(i, distance) {
  24662. * // do things
  24663. * return scaleValue;}
  24664. * ```
  24665. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24666. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24667. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24668. * 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
  24669. * 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
  24670. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24671. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24672. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24674. */
  24675. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24676. var options = {
  24677. shape: shape,
  24678. path: path,
  24679. scaleFunction: scaleFunction,
  24680. rotationFunction: rotationFunction,
  24681. ribbonCloseArray: ribbonCloseArray,
  24682. ribbonClosePath: ribbonClosePath,
  24683. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24684. sideOrientation: sideOrientation,
  24685. instance: instance,
  24686. updatable: updatable
  24687. };
  24688. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24689. };
  24690. /**
  24691. * Creates lathe mesh.
  24692. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24693. * Please consider using the same method from the MeshBuilder class instead.
  24694. * 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
  24695. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24696. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24697. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24698. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24699. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24700. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24701. */
  24702. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24703. var options = {
  24704. shape: shape,
  24705. radius: radius,
  24706. tessellation: tessellation,
  24707. sideOrientation: sideOrientation,
  24708. updatable: updatable
  24709. };
  24710. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24711. };
  24712. /**
  24713. * Creates a plane mesh.
  24714. * Please consider using the same method from the MeshBuilder class instead.
  24715. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24716. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24717. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24718. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24719. */
  24720. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24721. var options = {
  24722. size: size,
  24723. width: size,
  24724. height: size,
  24725. sideOrientation: sideOrientation,
  24726. updatable: updatable
  24727. };
  24728. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24729. };
  24730. /**
  24731. * Creates a ground mesh.
  24732. * Please consider using the same method from the MeshBuilder class instead.
  24733. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24734. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24735. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24736. */
  24737. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24738. var options = {
  24739. width: width,
  24740. height: height,
  24741. subdivisions: subdivisions,
  24742. updatable: updatable
  24743. };
  24744. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24745. };
  24746. /**
  24747. * Creates a tiled ground mesh.
  24748. * Please consider using the same method from the MeshBuilder class instead.
  24749. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24750. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24751. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24752. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24753. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24754. * numbers of subdivisions on the ground width and height of each tile.
  24755. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24756. */
  24757. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24758. var options = {
  24759. xmin: xmin,
  24760. zmin: zmin,
  24761. xmax: xmax,
  24762. zmax: zmax,
  24763. subdivisions: subdivisions,
  24764. precision: precision,
  24765. updatable: updatable
  24766. };
  24767. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24768. };
  24769. /**
  24770. * Creates a ground mesh from a height map.
  24771. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24772. * Please consider using the same method from the MeshBuilder class instead.
  24773. * The parameter `url` sets the URL of the height map image resource.
  24774. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24775. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24776. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24777. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24778. * 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).
  24779. * This function is passed the newly built mesh :
  24780. * ```javascript
  24781. * function(mesh) { // do things
  24782. * return; }
  24783. * ```
  24784. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24785. */
  24786. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24787. var options = {
  24788. width: width,
  24789. height: height,
  24790. subdivisions: subdivisions,
  24791. minHeight: minHeight,
  24792. maxHeight: maxHeight,
  24793. updatable: updatable,
  24794. onReady: onReady
  24795. };
  24796. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24797. };
  24798. /**
  24799. * Creates a tube mesh.
  24800. * 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.
  24801. * Please consider using the same method from the MeshBuilder class instead.
  24802. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24803. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24804. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24805. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24806. * 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.
  24807. * It must return a radius value (positive float) :
  24808. * ```javascript
  24809. * var radiusFunction = function(i, distance) {
  24810. * // do things
  24811. * return radius; }
  24812. * ```
  24813. * 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
  24814. * 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
  24815. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24816. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24817. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24818. */
  24819. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24820. var options = {
  24821. path: path,
  24822. radius: radius,
  24823. tessellation: tessellation,
  24824. radiusFunction: radiusFunction,
  24825. arc: 1,
  24826. cap: cap,
  24827. updatable: updatable,
  24828. sideOrientation: sideOrientation,
  24829. instance: instance
  24830. };
  24831. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24832. };
  24833. /**
  24834. * Creates a polyhedron mesh.
  24835. * Please consider using the same method from the MeshBuilder class instead.
  24836. * 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
  24837. * to choose the wanted type.
  24838. * The parameter `size` (positive float, default 1) sets the polygon size.
  24839. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24840. * 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`.
  24841. * 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
  24842. * 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)`).
  24843. * 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
  24844. * 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.
  24845. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24846. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24848. */
  24849. Mesh.CreatePolyhedron = function (name, options, scene) {
  24850. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24851. };
  24852. /**
  24853. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24854. * Please consider using the same method from the MeshBuilder class instead.
  24855. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24856. * 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`).
  24857. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24858. * 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.
  24859. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24860. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24861. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24862. */
  24863. Mesh.CreateIcoSphere = function (name, options, scene) {
  24864. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24865. };
  24866. /**
  24867. * Creates a decal mesh.
  24868. * Please consider using the same method from the MeshBuilder class instead.
  24869. * 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.
  24870. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  24871. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  24872. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  24873. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  24874. */
  24875. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  24876. var options = {
  24877. position: position,
  24878. normal: normal,
  24879. size: size,
  24880. angle: angle
  24881. };
  24882. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24883. };
  24884. // Skeletons
  24885. /**
  24886. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24887. */
  24888. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24889. if (!this._sourcePositions) {
  24890. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24891. if (!source) {
  24892. return this._sourcePositions;
  24893. }
  24894. this._sourcePositions = new Float32Array(source);
  24895. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  24896. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24897. }
  24898. }
  24899. return this._sourcePositions;
  24900. };
  24901. /**
  24902. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24903. */
  24904. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24905. if (!this._sourceNormals) {
  24906. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24907. if (!source) {
  24908. return this._sourceNormals;
  24909. }
  24910. this._sourceNormals = new Float32Array(source);
  24911. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  24912. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24913. }
  24914. }
  24915. return this._sourceNormals;
  24916. };
  24917. /**
  24918. * Updates the vertex buffer by applying transformation from the bones.
  24919. * Returns the Mesh.
  24920. *
  24921. * @param {skeleton} skeleton to apply
  24922. */
  24923. Mesh.prototype.applySkeleton = function (skeleton) {
  24924. if (!this.geometry) {
  24925. return this;
  24926. }
  24927. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24928. return this;
  24929. }
  24930. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24931. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24932. return this;
  24933. }
  24934. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24935. return this;
  24936. }
  24937. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24938. return this;
  24939. }
  24940. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24941. return this;
  24942. }
  24943. if (!this._sourcePositions) {
  24944. var submeshes = this.subMeshes.slice();
  24945. this.setPositionsForCPUSkinning();
  24946. this.subMeshes = submeshes;
  24947. }
  24948. if (!this._sourceNormals) {
  24949. this.setNormalsForCPUSkinning();
  24950. }
  24951. // positionsData checks for not being Float32Array will only pass at most once
  24952. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24953. if (!positionsData) {
  24954. return this;
  24955. }
  24956. if (!(positionsData instanceof Float32Array)) {
  24957. positionsData = new Float32Array(positionsData);
  24958. }
  24959. // normalsData checks for not being Float32Array will only pass at most once
  24960. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24961. if (!normalsData) {
  24962. return this;
  24963. }
  24964. if (!(normalsData instanceof Float32Array)) {
  24965. normalsData = new Float32Array(normalsData);
  24966. }
  24967. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24968. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24969. if (!matricesWeightsData || !matricesIndicesData) {
  24970. return this;
  24971. }
  24972. var needExtras = this.numBoneInfluencers > 4;
  24973. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24974. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24975. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  24976. return this;
  24977. }
  24978. var skeletonMatrices = skeleton.getTransformMatrices(this);
  24979. var tempVector3 = BABYLON.Vector3.Zero();
  24980. var finalMatrix = new BABYLON.Matrix();
  24981. var tempMatrix = new BABYLON.Matrix();
  24982. var matWeightIdx = 0;
  24983. var inf;
  24984. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24985. var weight;
  24986. for (inf = 0; inf < 4; inf++) {
  24987. weight = matricesWeightsData[matWeightIdx + inf];
  24988. if (weight > 0) {
  24989. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24990. finalMatrix.addToSelf(tempMatrix);
  24991. }
  24992. else
  24993. break;
  24994. }
  24995. if (needExtras) {
  24996. for (inf = 0; inf < 4; inf++) {
  24997. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24998. if (weight > 0) {
  24999. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25000. finalMatrix.addToSelf(tempMatrix);
  25001. }
  25002. else
  25003. break;
  25004. }
  25005. }
  25006. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25007. tempVector3.toArray(positionsData, index);
  25008. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25009. tempVector3.toArray(normalsData, index);
  25010. finalMatrix.reset();
  25011. }
  25012. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25013. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25014. return this;
  25015. };
  25016. // Tools
  25017. /**
  25018. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25019. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25020. */
  25021. Mesh.MinMax = function (meshes) {
  25022. var minVector = null;
  25023. var maxVector = null;
  25024. meshes.forEach(function (mesh, index, array) {
  25025. var boundingInfo = mesh.getBoundingInfo();
  25026. if (!boundingInfo) {
  25027. return;
  25028. }
  25029. var boundingBox = boundingInfo.boundingBox;
  25030. if (!minVector || !maxVector) {
  25031. minVector = boundingBox.minimumWorld;
  25032. maxVector = boundingBox.maximumWorld;
  25033. }
  25034. else {
  25035. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25036. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25037. }
  25038. });
  25039. if (!minVector || !maxVector) {
  25040. return {
  25041. min: BABYLON.Vector3.Zero(),
  25042. max: BABYLON.Vector3.Zero()
  25043. };
  25044. }
  25045. return {
  25046. min: minVector,
  25047. max: maxVector
  25048. };
  25049. };
  25050. /**
  25051. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25052. */
  25053. Mesh.Center = function (meshesOrMinMaxVector) {
  25054. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25055. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25056. };
  25057. /**
  25058. * Merge the array of meshes into a single mesh for performance reasons.
  25059. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25060. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25061. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25062. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25063. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25064. */
  25065. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25066. if (disposeSource === void 0) { disposeSource = true; }
  25067. var index;
  25068. if (!allow32BitsIndices) {
  25069. var totalVertices = 0;
  25070. // Counting vertices
  25071. for (index = 0; index < meshes.length; index++) {
  25072. if (meshes[index]) {
  25073. totalVertices += meshes[index].getTotalVertices();
  25074. if (totalVertices > 65536) {
  25075. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25076. return null;
  25077. }
  25078. }
  25079. }
  25080. }
  25081. // Merge
  25082. var vertexData = null;
  25083. var otherVertexData;
  25084. var indiceArray = new Array();
  25085. var source = null;
  25086. for (index = 0; index < meshes.length; index++) {
  25087. if (meshes[index]) {
  25088. meshes[index].computeWorldMatrix(true);
  25089. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25090. otherVertexData.transform(meshes[index].getWorldMatrix());
  25091. if (vertexData) {
  25092. vertexData.merge(otherVertexData);
  25093. }
  25094. else {
  25095. vertexData = otherVertexData;
  25096. source = meshes[index];
  25097. }
  25098. if (subdivideWithSubMeshes) {
  25099. indiceArray.push(meshes[index].getTotalIndices());
  25100. }
  25101. }
  25102. }
  25103. source = source;
  25104. if (!meshSubclass) {
  25105. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25106. }
  25107. vertexData.applyToMesh(meshSubclass);
  25108. // Setting properties
  25109. meshSubclass.material = source.material;
  25110. meshSubclass.checkCollisions = source.checkCollisions;
  25111. // Cleaning
  25112. if (disposeSource) {
  25113. for (index = 0; index < meshes.length; index++) {
  25114. if (meshes[index]) {
  25115. meshes[index].dispose();
  25116. }
  25117. }
  25118. }
  25119. // Subdivide
  25120. if (subdivideWithSubMeshes) {
  25121. //-- Suppresions du submesh global
  25122. meshSubclass.releaseSubMeshes();
  25123. index = 0;
  25124. var offset = 0;
  25125. //-- aplique la subdivision en fonction du tableau d'indices
  25126. while (index < indiceArray.length) {
  25127. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25128. offset += indiceArray[index];
  25129. index++;
  25130. }
  25131. }
  25132. return meshSubclass;
  25133. };
  25134. // Consts
  25135. Mesh._FRONTSIDE = 0;
  25136. Mesh._BACKSIDE = 1;
  25137. Mesh._DOUBLESIDE = 2;
  25138. Mesh._DEFAULTSIDE = 0;
  25139. Mesh._NO_CAP = 0;
  25140. Mesh._CAP_START = 1;
  25141. Mesh._CAP_END = 2;
  25142. Mesh._CAP_ALL = 3;
  25143. return Mesh;
  25144. }(BABYLON.AbstractMesh));
  25145. BABYLON.Mesh = Mesh;
  25146. })(BABYLON || (BABYLON = {}));
  25147. //# sourceMappingURL=babylon.mesh.js.map
  25148. var BABYLON;
  25149. (function (BABYLON) {
  25150. var BaseSubMesh = /** @class */ (function () {
  25151. function BaseSubMesh() {
  25152. }
  25153. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25154. get: function () {
  25155. return this._materialEffect;
  25156. },
  25157. enumerable: true,
  25158. configurable: true
  25159. });
  25160. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25161. if (defines === void 0) { defines = null; }
  25162. if (this._materialEffect === effect) {
  25163. if (!effect) {
  25164. this._materialDefines = null;
  25165. }
  25166. return;
  25167. }
  25168. this._materialDefines = defines;
  25169. this._materialEffect = effect;
  25170. };
  25171. return BaseSubMesh;
  25172. }());
  25173. BABYLON.BaseSubMesh = BaseSubMesh;
  25174. var SubMesh = /** @class */ (function (_super) {
  25175. __extends(SubMesh, _super);
  25176. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25177. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25178. var _this = _super.call(this) || this;
  25179. _this.materialIndex = materialIndex;
  25180. _this.verticesStart = verticesStart;
  25181. _this.verticesCount = verticesCount;
  25182. _this.indexStart = indexStart;
  25183. _this.indexCount = indexCount;
  25184. _this._renderId = 0;
  25185. _this._mesh = mesh;
  25186. _this._renderingMesh = renderingMesh || mesh;
  25187. mesh.subMeshes.push(_this);
  25188. _this._trianglePlanes = [];
  25189. _this._id = mesh.subMeshes.length - 1;
  25190. if (createBoundingBox) {
  25191. _this.refreshBoundingInfo();
  25192. mesh.computeWorldMatrix(true);
  25193. }
  25194. return _this;
  25195. }
  25196. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25197. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25198. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25199. };
  25200. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25201. get: function () {
  25202. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25203. },
  25204. enumerable: true,
  25205. configurable: true
  25206. });
  25207. /**
  25208. * Returns the submesh BoudingInfo object.
  25209. */
  25210. SubMesh.prototype.getBoundingInfo = function () {
  25211. if (this.IsGlobal) {
  25212. return this._mesh.getBoundingInfo();
  25213. }
  25214. return this._boundingInfo;
  25215. };
  25216. /**
  25217. * Sets the submesh BoundingInfo.
  25218. * Return the SubMesh.
  25219. */
  25220. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25221. this._boundingInfo = boundingInfo;
  25222. return this;
  25223. };
  25224. /**
  25225. * Returns the mesh of the current submesh.
  25226. */
  25227. SubMesh.prototype.getMesh = function () {
  25228. return this._mesh;
  25229. };
  25230. /**
  25231. * Returns the rendering mesh of the submesh.
  25232. */
  25233. SubMesh.prototype.getRenderingMesh = function () {
  25234. return this._renderingMesh;
  25235. };
  25236. /**
  25237. * Returns the submesh material.
  25238. */
  25239. SubMesh.prototype.getMaterial = function () {
  25240. var rootMaterial = this._renderingMesh.material;
  25241. if (rootMaterial && rootMaterial.getSubMaterial) {
  25242. var multiMaterial = rootMaterial;
  25243. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25244. if (this._currentMaterial !== effectiveMaterial) {
  25245. this._currentMaterial = effectiveMaterial;
  25246. this._materialDefines = null;
  25247. }
  25248. return effectiveMaterial;
  25249. }
  25250. if (!rootMaterial) {
  25251. return this._mesh.getScene().defaultMaterial;
  25252. }
  25253. return rootMaterial;
  25254. };
  25255. // Methods
  25256. /**
  25257. * Sets a new updated BoundingInfo object to the submesh.
  25258. * Returns the SubMesh.
  25259. */
  25260. SubMesh.prototype.refreshBoundingInfo = function () {
  25261. this._lastColliderWorldVertices = null;
  25262. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25263. return this;
  25264. }
  25265. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25266. if (!data) {
  25267. this._boundingInfo = this._mesh._boundingInfo;
  25268. return this;
  25269. }
  25270. var indices = this._renderingMesh.getIndices();
  25271. var extend;
  25272. //is this the only submesh?
  25273. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25274. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25275. if (!boundingInfo) {
  25276. return this;
  25277. }
  25278. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25279. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25280. }
  25281. else {
  25282. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25283. }
  25284. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25285. return this;
  25286. };
  25287. SubMesh.prototype._checkCollision = function (collider) {
  25288. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25289. if (!boundingInfo) {
  25290. return false;
  25291. }
  25292. return boundingInfo._checkCollision(collider);
  25293. };
  25294. /**
  25295. * Updates the submesh BoundingInfo.
  25296. * Returns the Submesh.
  25297. */
  25298. SubMesh.prototype.updateBoundingInfo = function (world) {
  25299. var boundingInfo = this.getBoundingInfo();
  25300. if (!boundingInfo) {
  25301. this.refreshBoundingInfo();
  25302. }
  25303. boundingInfo.update(world);
  25304. return this;
  25305. };
  25306. /**
  25307. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25308. * Boolean returned.
  25309. */
  25310. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25311. var boundingInfo = this.getBoundingInfo();
  25312. if (!boundingInfo) {
  25313. return false;
  25314. }
  25315. return boundingInfo.isInFrustum(frustumPlanes);
  25316. };
  25317. /**
  25318. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25319. * Boolean returned.
  25320. */
  25321. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25322. var boundingInfo = this.getBoundingInfo();
  25323. if (!boundingInfo) {
  25324. return false;
  25325. }
  25326. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25327. };
  25328. /**
  25329. * Renders the submesh.
  25330. * Returns it.
  25331. */
  25332. SubMesh.prototype.render = function (enableAlphaMode) {
  25333. this._renderingMesh.render(this, enableAlphaMode);
  25334. return this;
  25335. };
  25336. /**
  25337. * Returns a new Index Buffer.
  25338. * Type returned : WebGLBuffer.
  25339. */
  25340. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25341. if (!this._linesIndexBuffer) {
  25342. var linesIndices = [];
  25343. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25344. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25345. }
  25346. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25347. this.linesIndexCount = linesIndices.length;
  25348. }
  25349. return this._linesIndexBuffer;
  25350. };
  25351. /**
  25352. * True is the passed Ray intersects the submesh bounding box.
  25353. * Boolean returned.
  25354. */
  25355. SubMesh.prototype.canIntersects = function (ray) {
  25356. var boundingInfo = this.getBoundingInfo();
  25357. if (!boundingInfo) {
  25358. return false;
  25359. }
  25360. return ray.intersectsBox(boundingInfo.boundingBox);
  25361. };
  25362. /**
  25363. * Returns an object IntersectionInfo.
  25364. */
  25365. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25366. var intersectInfo = null;
  25367. // LineMesh first as it's also a Mesh...
  25368. if (this._mesh instanceof BABYLON.LinesMesh) {
  25369. var lineMesh = this._mesh;
  25370. // Line test
  25371. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25372. var p0 = positions[indices[index]];
  25373. var p1 = positions[indices[index + 1]];
  25374. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25375. if (length < 0) {
  25376. continue;
  25377. }
  25378. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25379. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25380. if (fastCheck) {
  25381. break;
  25382. }
  25383. }
  25384. }
  25385. }
  25386. else {
  25387. // Triangles test
  25388. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25389. var p0 = positions[indices[index]];
  25390. var p1 = positions[indices[index + 1]];
  25391. var p2 = positions[indices[index + 2]];
  25392. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25393. if (currentIntersectInfo) {
  25394. if (currentIntersectInfo.distance < 0) {
  25395. continue;
  25396. }
  25397. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25398. intersectInfo = currentIntersectInfo;
  25399. intersectInfo.faceId = index / 3;
  25400. if (fastCheck) {
  25401. break;
  25402. }
  25403. }
  25404. }
  25405. }
  25406. }
  25407. return intersectInfo;
  25408. };
  25409. SubMesh.prototype._rebuild = function () {
  25410. if (this._linesIndexBuffer) {
  25411. this._linesIndexBuffer = null;
  25412. }
  25413. };
  25414. // Clone
  25415. /**
  25416. * Creates a new Submesh from the passed Mesh.
  25417. */
  25418. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25419. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25420. if (!this.IsGlobal) {
  25421. var boundingInfo = this.getBoundingInfo();
  25422. if (!boundingInfo) {
  25423. return result;
  25424. }
  25425. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  25426. }
  25427. return result;
  25428. };
  25429. // Dispose
  25430. /**
  25431. * Disposes the Submesh.
  25432. * Returns nothing.
  25433. */
  25434. SubMesh.prototype.dispose = function () {
  25435. if (this._linesIndexBuffer) {
  25436. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25437. this._linesIndexBuffer = null;
  25438. }
  25439. // Remove from mesh
  25440. var index = this._mesh.subMeshes.indexOf(this);
  25441. this._mesh.subMeshes.splice(index, 1);
  25442. };
  25443. // Statics
  25444. /**
  25445. * Creates a new Submesh from the passed parameters :
  25446. * - materialIndex (integer) : the index of the main mesh material.
  25447. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25448. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25449. * - mesh (Mesh) : the main mesh to create the submesh from.
  25450. * - renderingMesh (optional Mesh) : rendering mesh.
  25451. */
  25452. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25453. var minVertexIndex = Number.MAX_VALUE;
  25454. var maxVertexIndex = -Number.MAX_VALUE;
  25455. renderingMesh = (renderingMesh || mesh);
  25456. var indices = renderingMesh.getIndices();
  25457. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25458. var vertexIndex = indices[index];
  25459. if (vertexIndex < minVertexIndex)
  25460. minVertexIndex = vertexIndex;
  25461. if (vertexIndex > maxVertexIndex)
  25462. maxVertexIndex = vertexIndex;
  25463. }
  25464. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25465. };
  25466. return SubMesh;
  25467. }(BaseSubMesh));
  25468. BABYLON.SubMesh = SubMesh;
  25469. })(BABYLON || (BABYLON = {}));
  25470. //# sourceMappingURL=babylon.subMesh.js.map
  25471. var BABYLON;
  25472. (function (BABYLON) {
  25473. var EffectFallbacks = /** @class */ (function () {
  25474. function EffectFallbacks() {
  25475. this._defines = {};
  25476. this._currentRank = 32;
  25477. this._maxRank = -1;
  25478. }
  25479. EffectFallbacks.prototype.unBindMesh = function () {
  25480. this._mesh = null;
  25481. };
  25482. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25483. if (!this._defines[rank]) {
  25484. if (rank < this._currentRank) {
  25485. this._currentRank = rank;
  25486. }
  25487. if (rank > this._maxRank) {
  25488. this._maxRank = rank;
  25489. }
  25490. this._defines[rank] = new Array();
  25491. }
  25492. this._defines[rank].push(define);
  25493. };
  25494. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25495. this._meshRank = rank;
  25496. this._mesh = mesh;
  25497. if (rank < this._currentRank) {
  25498. this._currentRank = rank;
  25499. }
  25500. if (rank > this._maxRank) {
  25501. this._maxRank = rank;
  25502. }
  25503. };
  25504. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25505. get: function () {
  25506. return this._currentRank <= this._maxRank;
  25507. },
  25508. enumerable: true,
  25509. configurable: true
  25510. });
  25511. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25512. // First we try to switch to CPU skinning
  25513. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25514. this._mesh.computeBonesUsingShaders = false;
  25515. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25516. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25517. var scene = this._mesh.getScene();
  25518. for (var index = 0; index < scene.meshes.length; index++) {
  25519. var otherMesh = scene.meshes[index];
  25520. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25521. otherMesh.computeBonesUsingShaders = false;
  25522. }
  25523. }
  25524. }
  25525. else {
  25526. var currentFallbacks = this._defines[this._currentRank];
  25527. if (currentFallbacks) {
  25528. for (var index = 0; index < currentFallbacks.length; index++) {
  25529. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25530. }
  25531. }
  25532. this._currentRank++;
  25533. }
  25534. return currentDefines;
  25535. };
  25536. return EffectFallbacks;
  25537. }());
  25538. BABYLON.EffectFallbacks = EffectFallbacks;
  25539. var EffectCreationOptions = /** @class */ (function () {
  25540. function EffectCreationOptions() {
  25541. }
  25542. return EffectCreationOptions;
  25543. }());
  25544. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25545. var Effect = /** @class */ (function () {
  25546. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25547. if (samplers === void 0) { samplers = null; }
  25548. if (defines === void 0) { defines = null; }
  25549. if (fallbacks === void 0) { fallbacks = null; }
  25550. if (onCompiled === void 0) { onCompiled = null; }
  25551. if (onError === void 0) { onError = null; }
  25552. var _this = this;
  25553. this.uniqueId = 0;
  25554. this.onCompileObservable = new BABYLON.Observable();
  25555. this.onErrorObservable = new BABYLON.Observable();
  25556. this.onBindObservable = new BABYLON.Observable();
  25557. this._uniformBuffersNames = {};
  25558. this._isReady = false;
  25559. this._compilationError = "";
  25560. this.name = baseName;
  25561. if (attributesNamesOrOptions.attributes) {
  25562. var options = attributesNamesOrOptions;
  25563. this._engine = uniformsNamesOrEngine;
  25564. this._attributesNames = options.attributes;
  25565. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25566. this._samplers = options.samplers;
  25567. this.defines = options.defines;
  25568. this.onError = options.onError;
  25569. this.onCompiled = options.onCompiled;
  25570. this._fallbacks = options.fallbacks;
  25571. this._indexParameters = options.indexParameters;
  25572. if (options.uniformBuffersNames) {
  25573. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25574. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25575. }
  25576. }
  25577. }
  25578. else {
  25579. this._engine = engine;
  25580. this.defines = defines;
  25581. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25582. this._samplers = samplers;
  25583. this._attributesNames = attributesNamesOrOptions;
  25584. this.onError = onError;
  25585. this.onCompiled = onCompiled;
  25586. this._indexParameters = indexParameters;
  25587. this._fallbacks = fallbacks;
  25588. }
  25589. this.uniqueId = Effect._uniqueIdSeed++;
  25590. var vertexSource;
  25591. var fragmentSource;
  25592. if (baseName.vertexElement) {
  25593. vertexSource = document.getElementById(baseName.vertexElement);
  25594. if (!vertexSource) {
  25595. vertexSource = baseName.vertexElement;
  25596. }
  25597. }
  25598. else {
  25599. vertexSource = baseName.vertex || baseName;
  25600. }
  25601. if (baseName.fragmentElement) {
  25602. fragmentSource = document.getElementById(baseName.fragmentElement);
  25603. if (!fragmentSource) {
  25604. fragmentSource = baseName.fragmentElement;
  25605. }
  25606. }
  25607. else {
  25608. fragmentSource = baseName.fragment || baseName;
  25609. }
  25610. this._loadVertexShader(vertexSource, function (vertexCode) {
  25611. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25612. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25613. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25614. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25615. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25616. if (baseName) {
  25617. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25618. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25619. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25620. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25621. }
  25622. else {
  25623. _this._vertexSourceCode = migratedVertexCode;
  25624. _this._fragmentSourceCode = migratedFragmentCode;
  25625. }
  25626. _this._prepareEffect();
  25627. });
  25628. });
  25629. });
  25630. });
  25631. });
  25632. });
  25633. }
  25634. Object.defineProperty(Effect.prototype, "key", {
  25635. get: function () {
  25636. return this._key;
  25637. },
  25638. enumerable: true,
  25639. configurable: true
  25640. });
  25641. // Properties
  25642. Effect.prototype.isReady = function () {
  25643. return this._isReady;
  25644. };
  25645. Effect.prototype.getEngine = function () {
  25646. return this._engine;
  25647. };
  25648. Effect.prototype.getProgram = function () {
  25649. return this._program;
  25650. };
  25651. Effect.prototype.getAttributesNames = function () {
  25652. return this._attributesNames;
  25653. };
  25654. Effect.prototype.getAttributeLocation = function (index) {
  25655. return this._attributes[index];
  25656. };
  25657. Effect.prototype.getAttributeLocationByName = function (name) {
  25658. var index = this._attributesNames.indexOf(name);
  25659. return this._attributes[index];
  25660. };
  25661. Effect.prototype.getAttributesCount = function () {
  25662. return this._attributes.length;
  25663. };
  25664. Effect.prototype.getUniformIndex = function (uniformName) {
  25665. return this._uniformsNames.indexOf(uniformName);
  25666. };
  25667. Effect.prototype.getUniform = function (uniformName) {
  25668. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25669. };
  25670. Effect.prototype.getSamplers = function () {
  25671. return this._samplers;
  25672. };
  25673. Effect.prototype.getCompilationError = function () {
  25674. return this._compilationError;
  25675. };
  25676. // Methods
  25677. Effect.prototype.executeWhenCompiled = function (func) {
  25678. if (this.isReady()) {
  25679. func(this);
  25680. return;
  25681. }
  25682. this.onCompileObservable.add(function (effect) {
  25683. func(effect);
  25684. });
  25685. };
  25686. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25687. if (BABYLON.Tools.IsWindowObjectExist()) {
  25688. // DOM element ?
  25689. if (vertex instanceof HTMLElement) {
  25690. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25691. callback(vertexCode);
  25692. return;
  25693. }
  25694. }
  25695. // Base64 encoded ?
  25696. if (vertex.substr(0, 7) === "base64:") {
  25697. var vertexBinary = window.atob(vertex.substr(7));
  25698. callback(vertexBinary);
  25699. return;
  25700. }
  25701. // Is in local store ?
  25702. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25703. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25704. return;
  25705. }
  25706. var vertexShaderUrl;
  25707. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25708. vertexShaderUrl = vertex;
  25709. }
  25710. else {
  25711. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25712. }
  25713. // Vertex shader
  25714. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25715. };
  25716. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25717. if (BABYLON.Tools.IsWindowObjectExist()) {
  25718. // DOM element ?
  25719. if (fragment instanceof HTMLElement) {
  25720. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25721. callback(fragmentCode);
  25722. return;
  25723. }
  25724. }
  25725. // Base64 encoded ?
  25726. if (fragment.substr(0, 7) === "base64:") {
  25727. var fragmentBinary = window.atob(fragment.substr(7));
  25728. callback(fragmentBinary);
  25729. return;
  25730. }
  25731. // Is in local store ?
  25732. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25733. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25734. return;
  25735. }
  25736. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25737. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25738. return;
  25739. }
  25740. var fragmentShaderUrl;
  25741. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25742. fragmentShaderUrl = fragment;
  25743. }
  25744. else {
  25745. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25746. }
  25747. // Fragment shader
  25748. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25749. };
  25750. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  25751. // Rebuild shaders source code
  25752. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  25753. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  25754. vertexCode = prefix + vertexCode;
  25755. fragmentCode = prefix + fragmentCode;
  25756. // Number lines of shaders source code
  25757. var i = 2;
  25758. var regex = /\n/gm;
  25759. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25760. i = 2;
  25761. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25762. // Dump shaders name and formatted source code
  25763. if (this.name.vertexElement) {
  25764. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  25765. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  25766. }
  25767. else if (this.name.vertex) {
  25768. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  25769. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  25770. }
  25771. else {
  25772. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  25773. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  25774. }
  25775. };
  25776. ;
  25777. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25778. var preparedSourceCode = this._processPrecision(sourceCode);
  25779. if (this._engine.webGLVersion == 1) {
  25780. callback(preparedSourceCode);
  25781. return;
  25782. }
  25783. // Already converted
  25784. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25785. callback(preparedSourceCode.replace("#version 300 es", ""));
  25786. return;
  25787. }
  25788. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  25789. // Remove extensions
  25790. // #extension GL_OES_standard_derivatives : enable
  25791. // #extension GL_EXT_shader_texture_lod : enable
  25792. // #extension GL_EXT_frag_depth : enable
  25793. // #extension GL_EXT_draw_buffers : require
  25794. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  25795. var result = preparedSourceCode.replace(regex, "");
  25796. // Migrate to GLSL v300
  25797. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  25798. result = result.replace(/attribute[ \t]/g, "in ");
  25799. result = result.replace(/[ \t]attribute/g, " in");
  25800. if (isFragment) {
  25801. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  25802. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  25803. result = result.replace(/texture2D\s*\(/g, "texture(");
  25804. result = result.replace(/textureCube\s*\(/g, "texture(");
  25805. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25806. result = result.replace(/gl_FragColor/g, "glFragColor");
  25807. result = result.replace(/gl_FragData/g, "glFragData");
  25808. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  25809. }
  25810. callback(result);
  25811. };
  25812. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25813. var _this = this;
  25814. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25815. var match = regex.exec(sourceCode);
  25816. var returnValue = new String(sourceCode);
  25817. while (match != null) {
  25818. var includeFile = match[1];
  25819. // Uniform declaration
  25820. if (includeFile.indexOf("__decl__") !== -1) {
  25821. includeFile = includeFile.replace(/__decl__/, "");
  25822. if (this._engine.supportsUniformBuffers) {
  25823. includeFile = includeFile.replace(/Vertex/, "Ubo");
  25824. includeFile = includeFile.replace(/Fragment/, "Ubo");
  25825. }
  25826. includeFile = includeFile + "Declaration";
  25827. }
  25828. if (Effect.IncludesShadersStore[includeFile]) {
  25829. // Substitution
  25830. var includeContent = Effect.IncludesShadersStore[includeFile];
  25831. if (match[2]) {
  25832. var splits = match[3].split(",");
  25833. for (var index = 0; index < splits.length; index += 2) {
  25834. var source = new RegExp(splits[index], "g");
  25835. var dest = splits[index + 1];
  25836. includeContent = includeContent.replace(source, dest);
  25837. }
  25838. }
  25839. if (match[4]) {
  25840. var indexString = match[5];
  25841. if (indexString.indexOf("..") !== -1) {
  25842. var indexSplits = indexString.split("..");
  25843. var minIndex = parseInt(indexSplits[0]);
  25844. var maxIndex = parseInt(indexSplits[1]);
  25845. var sourceIncludeContent = includeContent.slice(0);
  25846. includeContent = "";
  25847. if (isNaN(maxIndex)) {
  25848. maxIndex = this._indexParameters[indexSplits[1]];
  25849. }
  25850. for (var i = minIndex; i < maxIndex; i++) {
  25851. if (!this._engine.supportsUniformBuffers) {
  25852. // Ubo replacement
  25853. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25854. return p1 + "{X}";
  25855. });
  25856. }
  25857. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  25858. }
  25859. }
  25860. else {
  25861. if (!this._engine.supportsUniformBuffers) {
  25862. // Ubo replacement
  25863. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25864. return p1 + "{X}";
  25865. });
  25866. }
  25867. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25868. }
  25869. }
  25870. // Replace
  25871. returnValue = returnValue.replace(match[0], includeContent);
  25872. }
  25873. else {
  25874. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25875. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25876. Effect.IncludesShadersStore[includeFile] = fileContent;
  25877. _this._processIncludes(returnValue, callback);
  25878. });
  25879. return;
  25880. }
  25881. match = regex.exec(sourceCode);
  25882. }
  25883. callback(returnValue);
  25884. };
  25885. Effect.prototype._processPrecision = function (source) {
  25886. if (source.indexOf("precision highp float") === -1) {
  25887. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25888. source = "precision mediump float;\n" + source;
  25889. }
  25890. else {
  25891. source = "precision highp float;\n" + source;
  25892. }
  25893. }
  25894. else {
  25895. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25896. source = source.replace("precision highp float", "precision mediump float");
  25897. }
  25898. }
  25899. return source;
  25900. };
  25901. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  25902. var _this = this;
  25903. this._isReady = false;
  25904. this._vertexSourceCodeOverride = vertexSourceCode;
  25905. this._fragmentSourceCodeOverride = fragmentSourceCode;
  25906. this.onError = function (effect, error) {
  25907. if (onError) {
  25908. onError(error);
  25909. }
  25910. };
  25911. this.onCompiled = function () {
  25912. var scenes = _this.getEngine().scenes;
  25913. for (var i = 0; i < scenes.length; i++) {
  25914. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25915. }
  25916. if (onCompiled) {
  25917. onCompiled(_this._program);
  25918. }
  25919. };
  25920. this._fallbacks = null;
  25921. this._prepareEffect();
  25922. };
  25923. Effect.prototype._prepareEffect = function () {
  25924. var attributesNames = this._attributesNames;
  25925. var defines = this.defines;
  25926. var fallbacks = this._fallbacks;
  25927. this._valueCache = {};
  25928. var previousProgram = this._program;
  25929. try {
  25930. var engine = this._engine;
  25931. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  25932. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride);
  25933. }
  25934. else {
  25935. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25936. }
  25937. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  25938. if (engine.webGLVersion > 1) {
  25939. for (var name in this._uniformBuffersNames) {
  25940. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  25941. }
  25942. }
  25943. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25944. this._attributes = engine.getAttributes(this._program, attributesNames);
  25945. var index;
  25946. for (index = 0; index < this._samplers.length; index++) {
  25947. var sampler = this.getUniform(this._samplers[index]);
  25948. if (sampler == null) {
  25949. this._samplers.splice(index, 1);
  25950. index--;
  25951. }
  25952. }
  25953. engine.bindSamplers(this);
  25954. this._compilationError = "";
  25955. this._isReady = true;
  25956. if (this.onCompiled) {
  25957. this.onCompiled(this);
  25958. }
  25959. this.onCompileObservable.notifyObservers(this);
  25960. this.onCompileObservable.clear();
  25961. // Unbind mesh reference in fallbacks
  25962. if (this._fallbacks) {
  25963. this._fallbacks.unBindMesh();
  25964. }
  25965. if (previousProgram) {
  25966. this.getEngine()._deleteProgram(previousProgram);
  25967. }
  25968. }
  25969. catch (e) {
  25970. this._compilationError = e.message;
  25971. // Let's go through fallbacks then
  25972. BABYLON.Tools.Error("Unable to compile effect:");
  25973. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  25974. return " " + uniform;
  25975. }));
  25976. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  25977. return " " + attribute;
  25978. }));
  25979. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25980. BABYLON.Tools.Error("Error: " + this._compilationError);
  25981. if (previousProgram) {
  25982. this._program = previousProgram;
  25983. this._isReady = true;
  25984. if (this.onError) {
  25985. this.onError(this, this._compilationError);
  25986. }
  25987. this.onErrorObservable.notifyObservers(this);
  25988. }
  25989. if (fallbacks && fallbacks.isMoreFallbacks) {
  25990. BABYLON.Tools.Error("Trying next fallback.");
  25991. this.defines = fallbacks.reduce(this.defines);
  25992. this._prepareEffect();
  25993. }
  25994. else {
  25995. if (this.onError) {
  25996. this.onError(this, this._compilationError);
  25997. }
  25998. this.onErrorObservable.notifyObservers(this);
  25999. this.onErrorObservable.clear();
  26000. // Unbind mesh reference in fallbacks
  26001. if (this._fallbacks) {
  26002. this._fallbacks.unBindMesh();
  26003. }
  26004. }
  26005. }
  26006. };
  26007. Object.defineProperty(Effect.prototype, "isSupported", {
  26008. get: function () {
  26009. return this._compilationError === "";
  26010. },
  26011. enumerable: true,
  26012. configurable: true
  26013. });
  26014. Effect.prototype._bindTexture = function (channel, texture) {
  26015. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26016. };
  26017. Effect.prototype.setTexture = function (channel, texture) {
  26018. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26019. };
  26020. Effect.prototype.setTextureArray = function (channel, textures) {
  26021. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26022. var initialPos = this._samplers.indexOf(channel);
  26023. for (var index = 1; index < textures.length; index++) {
  26024. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26025. }
  26026. }
  26027. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26028. };
  26029. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26030. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26031. };
  26032. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26033. var cache = this._valueCache[uniformName];
  26034. var flag = matrix.updateFlag;
  26035. if (cache !== undefined && cache === flag) {
  26036. return false;
  26037. }
  26038. this._valueCache[uniformName] = flag;
  26039. return true;
  26040. };
  26041. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26042. var cache = this._valueCache[uniformName];
  26043. if (!cache) {
  26044. cache = [x, y];
  26045. this._valueCache[uniformName] = cache;
  26046. return true;
  26047. }
  26048. var changed = false;
  26049. if (cache[0] !== x) {
  26050. cache[0] = x;
  26051. changed = true;
  26052. }
  26053. if (cache[1] !== y) {
  26054. cache[1] = y;
  26055. changed = true;
  26056. }
  26057. return changed;
  26058. };
  26059. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26060. var cache = this._valueCache[uniformName];
  26061. if (!cache) {
  26062. cache = [x, y, z];
  26063. this._valueCache[uniformName] = cache;
  26064. return true;
  26065. }
  26066. var changed = false;
  26067. if (cache[0] !== x) {
  26068. cache[0] = x;
  26069. changed = true;
  26070. }
  26071. if (cache[1] !== y) {
  26072. cache[1] = y;
  26073. changed = true;
  26074. }
  26075. if (cache[2] !== z) {
  26076. cache[2] = z;
  26077. changed = true;
  26078. }
  26079. return changed;
  26080. };
  26081. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26082. var cache = this._valueCache[uniformName];
  26083. if (!cache) {
  26084. cache = [x, y, z, w];
  26085. this._valueCache[uniformName] = cache;
  26086. return true;
  26087. }
  26088. var changed = false;
  26089. if (cache[0] !== x) {
  26090. cache[0] = x;
  26091. changed = true;
  26092. }
  26093. if (cache[1] !== y) {
  26094. cache[1] = y;
  26095. changed = true;
  26096. }
  26097. if (cache[2] !== z) {
  26098. cache[2] = z;
  26099. changed = true;
  26100. }
  26101. if (cache[3] !== w) {
  26102. cache[3] = w;
  26103. changed = true;
  26104. }
  26105. return changed;
  26106. };
  26107. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26108. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  26109. return;
  26110. }
  26111. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  26112. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  26113. };
  26114. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26115. this._engine.bindUniformBlock(this._program, blockName, index);
  26116. };
  26117. Effect.prototype.setIntArray = function (uniformName, array) {
  26118. this._valueCache[uniformName] = null;
  26119. this._engine.setIntArray(this.getUniform(uniformName), array);
  26120. return this;
  26121. };
  26122. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26123. this._valueCache[uniformName] = null;
  26124. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26125. return this;
  26126. };
  26127. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26128. this._valueCache[uniformName] = null;
  26129. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26130. return this;
  26131. };
  26132. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26133. this._valueCache[uniformName] = null;
  26134. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26135. return this;
  26136. };
  26137. Effect.prototype.setFloatArray = function (uniformName, array) {
  26138. this._valueCache[uniformName] = null;
  26139. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26140. return this;
  26141. };
  26142. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26143. this._valueCache[uniformName] = null;
  26144. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26145. return this;
  26146. };
  26147. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26148. this._valueCache[uniformName] = null;
  26149. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26150. return this;
  26151. };
  26152. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26153. this._valueCache[uniformName] = null;
  26154. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26155. return this;
  26156. };
  26157. Effect.prototype.setArray = function (uniformName, array) {
  26158. this._valueCache[uniformName] = null;
  26159. this._engine.setArray(this.getUniform(uniformName), array);
  26160. return this;
  26161. };
  26162. Effect.prototype.setArray2 = function (uniformName, array) {
  26163. this._valueCache[uniformName] = null;
  26164. this._engine.setArray2(this.getUniform(uniformName), array);
  26165. return this;
  26166. };
  26167. Effect.prototype.setArray3 = function (uniformName, array) {
  26168. this._valueCache[uniformName] = null;
  26169. this._engine.setArray3(this.getUniform(uniformName), array);
  26170. return this;
  26171. };
  26172. Effect.prototype.setArray4 = function (uniformName, array) {
  26173. this._valueCache[uniformName] = null;
  26174. this._engine.setArray4(this.getUniform(uniformName), array);
  26175. return this;
  26176. };
  26177. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26178. if (!matrices) {
  26179. return this;
  26180. }
  26181. this._valueCache[uniformName] = null;
  26182. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26183. return this;
  26184. };
  26185. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26186. if (this._cacheMatrix(uniformName, matrix)) {
  26187. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26188. }
  26189. return this;
  26190. };
  26191. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26192. this._valueCache[uniformName] = null;
  26193. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26194. return this;
  26195. };
  26196. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26197. this._valueCache[uniformName] = null;
  26198. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26199. return this;
  26200. };
  26201. Effect.prototype.setFloat = function (uniformName, value) {
  26202. var cache = this._valueCache[uniformName];
  26203. if (cache !== undefined && cache === value)
  26204. return this;
  26205. this._valueCache[uniformName] = value;
  26206. this._engine.setFloat(this.getUniform(uniformName), value);
  26207. return this;
  26208. };
  26209. Effect.prototype.setBool = function (uniformName, bool) {
  26210. var cache = this._valueCache[uniformName];
  26211. if (cache !== undefined && cache === bool)
  26212. return this;
  26213. this._valueCache[uniformName] = bool;
  26214. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26215. return this;
  26216. };
  26217. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26218. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26219. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26220. }
  26221. return this;
  26222. };
  26223. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26224. if (this._cacheFloat2(uniformName, x, y)) {
  26225. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26226. }
  26227. return this;
  26228. };
  26229. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26230. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26231. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26232. }
  26233. return this;
  26234. };
  26235. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26236. if (this._cacheFloat3(uniformName, x, y, z)) {
  26237. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26238. }
  26239. return this;
  26240. };
  26241. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26242. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26243. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26244. }
  26245. return this;
  26246. };
  26247. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26248. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26249. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26250. }
  26251. return this;
  26252. };
  26253. Effect.prototype.setColor3 = function (uniformName, color3) {
  26254. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26255. this._engine.setColor3(this.getUniform(uniformName), color3);
  26256. }
  26257. return this;
  26258. };
  26259. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26260. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26261. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26262. }
  26263. return this;
  26264. };
  26265. Effect.ResetCache = function () {
  26266. Effect._baseCache = {};
  26267. };
  26268. Effect._uniqueIdSeed = 0;
  26269. Effect._baseCache = {};
  26270. // Statics
  26271. Effect.ShadersStore = {};
  26272. Effect.IncludesShadersStore = {};
  26273. return Effect;
  26274. }());
  26275. BABYLON.Effect = Effect;
  26276. })(BABYLON || (BABYLON = {}));
  26277. //# sourceMappingURL=babylon.effect.js.map
  26278. var BABYLON;
  26279. (function (BABYLON) {
  26280. var MaterialHelper = /** @class */ (function () {
  26281. function MaterialHelper() {
  26282. }
  26283. MaterialHelper.BindEyePosition = function (effect, scene) {
  26284. if (scene._forcedViewPosition) {
  26285. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26286. return;
  26287. }
  26288. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26289. };
  26290. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26291. defines._needUVs = true;
  26292. defines[key] = true;
  26293. if (texture.getTextureMatrix().isIdentity(true)) {
  26294. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26295. if (texture.coordinatesIndex === 0) {
  26296. defines["MAINUV1"] = true;
  26297. }
  26298. else {
  26299. defines["MAINUV2"] = true;
  26300. }
  26301. }
  26302. else {
  26303. defines[key + "DIRECTUV"] = 0;
  26304. }
  26305. };
  26306. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26307. var matrix = texture.getTextureMatrix();
  26308. if (!matrix.isIdentity(true)) {
  26309. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26310. }
  26311. };
  26312. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26313. if (defines._areMiscDirty) {
  26314. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26315. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26316. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26317. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26318. }
  26319. };
  26320. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26321. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26322. var changed = false;
  26323. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26324. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26325. changed = true;
  26326. }
  26327. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26328. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26329. changed = true;
  26330. }
  26331. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26332. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26333. changed = true;
  26334. }
  26335. if (defines["INSTANCES"] !== useInstances) {
  26336. defines["INSTANCES"] = useInstances;
  26337. changed = true;
  26338. }
  26339. if (changed) {
  26340. defines.markAsUnprocessed();
  26341. }
  26342. };
  26343. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  26344. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26345. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26346. return false;
  26347. }
  26348. defines._normals = defines._needNormals;
  26349. defines._uvs = defines._needUVs;
  26350. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26351. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26352. defines["TANGENT"] = true;
  26353. }
  26354. if (defines._needUVs) {
  26355. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26356. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26357. }
  26358. else {
  26359. defines["UV1"] = false;
  26360. defines["UV2"] = false;
  26361. }
  26362. if (useVertexColor) {
  26363. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26364. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  26365. }
  26366. if (useBones) {
  26367. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26368. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26369. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26370. }
  26371. else {
  26372. defines["NUM_BONE_INFLUENCERS"] = 0;
  26373. defines["BonesPerMesh"] = 0;
  26374. }
  26375. }
  26376. if (useMorphTargets) {
  26377. var manager = mesh.morphTargetManager;
  26378. if (manager) {
  26379. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  26380. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  26381. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  26382. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  26383. }
  26384. else {
  26385. defines["MORPHTARGETS_TANGENT"] = false;
  26386. defines["MORPHTARGETS_NORMAL"] = false;
  26387. defines["MORPHTARGETS"] = false;
  26388. defines["NUM_MORPH_INFLUENCERS"] = 0;
  26389. }
  26390. }
  26391. return true;
  26392. };
  26393. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  26394. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26395. if (disableLighting === void 0) { disableLighting = false; }
  26396. if (!defines._areLightsDirty) {
  26397. return defines._needNormals;
  26398. }
  26399. var lightIndex = 0;
  26400. var needNormals = false;
  26401. var needRebuild = false;
  26402. var lightmapMode = false;
  26403. var shadowEnabled = false;
  26404. var specularEnabled = false;
  26405. if (scene.lightsEnabled && !disableLighting) {
  26406. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26407. var light = _a[_i];
  26408. needNormals = true;
  26409. if (defines["LIGHT" + lightIndex] === undefined) {
  26410. needRebuild = true;
  26411. }
  26412. defines["LIGHT" + lightIndex] = true;
  26413. defines["SPOTLIGHT" + lightIndex] = false;
  26414. defines["HEMILIGHT" + lightIndex] = false;
  26415. defines["POINTLIGHT" + lightIndex] = false;
  26416. defines["DIRLIGHT" + lightIndex] = false;
  26417. var type;
  26418. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  26419. type = "SPOTLIGHT" + lightIndex;
  26420. }
  26421. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  26422. type = "HEMILIGHT" + lightIndex;
  26423. }
  26424. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  26425. type = "POINTLIGHT" + lightIndex;
  26426. }
  26427. else {
  26428. type = "DIRLIGHT" + lightIndex;
  26429. }
  26430. defines[type] = true;
  26431. // Specular
  26432. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  26433. specularEnabled = true;
  26434. }
  26435. // Shadows
  26436. defines["SHADOW" + lightIndex] = false;
  26437. defines["SHADOWPCF" + lightIndex] = false;
  26438. defines["SHADOWESM" + lightIndex] = false;
  26439. defines["SHADOWCUBE" + lightIndex] = false;
  26440. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  26441. var shadowGenerator = light.getShadowGenerator();
  26442. if (shadowGenerator) {
  26443. shadowEnabled = true;
  26444. shadowGenerator.prepareDefines(defines, lightIndex);
  26445. }
  26446. }
  26447. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26448. lightmapMode = true;
  26449. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26450. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  26451. }
  26452. else {
  26453. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  26454. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  26455. }
  26456. lightIndex++;
  26457. if (lightIndex === maxSimultaneousLights)
  26458. break;
  26459. }
  26460. }
  26461. defines["SPECULARTERM"] = specularEnabled;
  26462. defines["SHADOWS"] = shadowEnabled;
  26463. // Resetting all other lights if any
  26464. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26465. if (defines["LIGHT" + index] !== undefined) {
  26466. defines["LIGHT" + index] = false;
  26467. defines["HEMILIGHT" + lightIndex] = false;
  26468. defines["POINTLIGHT" + lightIndex] = false;
  26469. defines["DIRLIGHT" + lightIndex] = false;
  26470. defines["SPOTLIGHT" + lightIndex] = false;
  26471. defines["SHADOW" + lightIndex] = false;
  26472. }
  26473. }
  26474. var caps = scene.getEngine().getCaps();
  26475. if (defines["SHADOWFLOAT"] === undefined) {
  26476. needRebuild = true;
  26477. }
  26478. defines["SHADOWFLOAT"] = shadowEnabled &&
  26479. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26480. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26481. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26482. if (needRebuild) {
  26483. defines.rebuild();
  26484. }
  26485. return needNormals;
  26486. };
  26487. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26488. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26489. var uniformsList;
  26490. var uniformBuffersList = null;
  26491. if (uniformsListOrOptions.uniformsNames) {
  26492. var options = uniformsListOrOptions;
  26493. uniformsList = options.uniformsNames;
  26494. uniformBuffersList = options.uniformBuffersNames;
  26495. samplersList = options.samplers;
  26496. defines = options.defines;
  26497. maxSimultaneousLights = options.maxSimultaneousLights;
  26498. }
  26499. else {
  26500. uniformsList = uniformsListOrOptions;
  26501. if (!samplersList) {
  26502. samplersList = [];
  26503. }
  26504. }
  26505. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26506. if (!defines["LIGHT" + lightIndex]) {
  26507. break;
  26508. }
  26509. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26510. if (uniformBuffersList) {
  26511. uniformBuffersList.push("Light" + lightIndex);
  26512. }
  26513. samplersList.push("shadowSampler" + lightIndex);
  26514. }
  26515. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26516. uniformsList.push("morphTargetInfluences");
  26517. }
  26518. };
  26519. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  26520. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26521. if (!defines["SHADOWS"]) {
  26522. return;
  26523. }
  26524. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26525. if (!defines["LIGHT" + lightIndex]) {
  26526. break;
  26527. }
  26528. if (lightIndex > 0) {
  26529. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  26530. }
  26531. if (defines["SHADOW" + lightIndex]) {
  26532. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  26533. }
  26534. if (defines["SHADOWPCF" + lightIndex]) {
  26535. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  26536. }
  26537. if (defines["SHADOWESM" + lightIndex]) {
  26538. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  26539. }
  26540. }
  26541. };
  26542. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26543. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26544. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  26545. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26546. var manager = mesh.morphTargetManager;
  26547. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  26548. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  26549. for (var index = 0; index < influencers; index++) {
  26550. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26551. if (normal) {
  26552. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26553. }
  26554. if (tangent) {
  26555. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26556. }
  26557. if (attribs.length > maxAttributesCount) {
  26558. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26559. }
  26560. }
  26561. }
  26562. };
  26563. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26564. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26565. fallbacks.addCPUSkinningFallback(0, mesh);
  26566. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26567. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26568. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26569. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26570. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26571. }
  26572. }
  26573. };
  26574. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26575. if (defines["INSTANCES"]) {
  26576. attribs.push("world0");
  26577. attribs.push("world1");
  26578. attribs.push("world2");
  26579. attribs.push("world3");
  26580. }
  26581. };
  26582. // Bindings
  26583. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26584. if (light.shadowEnabled && mesh.receiveShadows) {
  26585. var shadowGenerator = light.getShadowGenerator();
  26586. if (shadowGenerator) {
  26587. shadowGenerator.bindShadowLight(lightIndex, effect);
  26588. }
  26589. }
  26590. };
  26591. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26592. light.transferToEffect(effect, lightIndex + "");
  26593. };
  26594. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26595. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26596. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26597. var lightIndex = 0;
  26598. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26599. var light = _a[_i];
  26600. var scaledIntensity = light.getScaledIntensity();
  26601. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26602. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26603. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26604. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26605. if (defines["SPECULARTERM"]) {
  26606. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26607. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26608. }
  26609. // Shadows
  26610. if (scene.shadowsEnabled) {
  26611. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26612. }
  26613. light._uniformBuffer.update();
  26614. lightIndex++;
  26615. if (lightIndex === maxSimultaneousLights)
  26616. break;
  26617. }
  26618. };
  26619. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26620. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26621. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26622. effect.setColor3("vFogColor", scene.fogColor);
  26623. }
  26624. };
  26625. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26626. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26627. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26628. if (matrices && effect) {
  26629. effect.setMatrices("mBones", matrices);
  26630. }
  26631. }
  26632. };
  26633. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26634. var manager = abstractMesh.morphTargetManager;
  26635. if (!abstractMesh || !manager) {
  26636. return;
  26637. }
  26638. effect.setFloatArray("morphTargetInfluences", manager.influences);
  26639. };
  26640. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26641. if (defines["LOGARITHMICDEPTH"]) {
  26642. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26643. }
  26644. };
  26645. MaterialHelper.BindClipPlane = function (effect, scene) {
  26646. if (scene.clipPlane) {
  26647. var clipPlane = scene.clipPlane;
  26648. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26649. }
  26650. };
  26651. return MaterialHelper;
  26652. }());
  26653. BABYLON.MaterialHelper = MaterialHelper;
  26654. })(BABYLON || (BABYLON = {}));
  26655. //# sourceMappingURL=babylon.materialHelper.js.map
  26656. var BABYLON;
  26657. (function (BABYLON) {
  26658. var MaterialDefines = /** @class */ (function () {
  26659. function MaterialDefines() {
  26660. this._isDirty = true;
  26661. this._areLightsDirty = true;
  26662. this._areAttributesDirty = true;
  26663. this._areTexturesDirty = true;
  26664. this._areFresnelDirty = true;
  26665. this._areMiscDirty = true;
  26666. this._areImageProcessingDirty = true;
  26667. this._normals = false;
  26668. this._uvs = false;
  26669. this._needNormals = false;
  26670. this._needUVs = false;
  26671. }
  26672. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26673. get: function () {
  26674. return this._isDirty;
  26675. },
  26676. enumerable: true,
  26677. configurable: true
  26678. });
  26679. MaterialDefines.prototype.markAsProcessed = function () {
  26680. this._isDirty = false;
  26681. this._areAttributesDirty = false;
  26682. this._areTexturesDirty = false;
  26683. this._areFresnelDirty = false;
  26684. this._areLightsDirty = false;
  26685. this._areMiscDirty = false;
  26686. this._areImageProcessingDirty = false;
  26687. };
  26688. MaterialDefines.prototype.markAsUnprocessed = function () {
  26689. this._isDirty = true;
  26690. };
  26691. MaterialDefines.prototype.markAllAsDirty = function () {
  26692. this._areTexturesDirty = true;
  26693. this._areAttributesDirty = true;
  26694. this._areLightsDirty = true;
  26695. this._areFresnelDirty = true;
  26696. this._areMiscDirty = true;
  26697. this._areImageProcessingDirty = true;
  26698. this._isDirty = true;
  26699. };
  26700. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  26701. this._areImageProcessingDirty = true;
  26702. this._isDirty = true;
  26703. };
  26704. MaterialDefines.prototype.markAsLightDirty = function () {
  26705. this._areLightsDirty = true;
  26706. this._isDirty = true;
  26707. };
  26708. MaterialDefines.prototype.markAsAttributesDirty = function () {
  26709. this._areAttributesDirty = true;
  26710. this._isDirty = true;
  26711. };
  26712. MaterialDefines.prototype.markAsTexturesDirty = function () {
  26713. this._areTexturesDirty = true;
  26714. this._isDirty = true;
  26715. };
  26716. MaterialDefines.prototype.markAsFresnelDirty = function () {
  26717. this._areFresnelDirty = true;
  26718. this._isDirty = true;
  26719. };
  26720. MaterialDefines.prototype.markAsMiscDirty = function () {
  26721. this._areMiscDirty = true;
  26722. this._isDirty = true;
  26723. };
  26724. MaterialDefines.prototype.rebuild = function () {
  26725. if (this._keys) {
  26726. delete this._keys;
  26727. }
  26728. this._keys = [];
  26729. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  26730. var key = _a[_i];
  26731. if (key[0] === "_") {
  26732. continue;
  26733. }
  26734. this._keys.push(key);
  26735. }
  26736. };
  26737. MaterialDefines.prototype.isEqual = function (other) {
  26738. if (this._keys.length !== other._keys.length) {
  26739. return false;
  26740. }
  26741. for (var index = 0; index < this._keys.length; index++) {
  26742. var prop = this._keys[index];
  26743. if (this[prop] !== other[prop]) {
  26744. return false;
  26745. }
  26746. }
  26747. return true;
  26748. };
  26749. MaterialDefines.prototype.cloneTo = function (other) {
  26750. if (this._keys.length !== other._keys.length) {
  26751. other._keys = this._keys.slice(0);
  26752. }
  26753. for (var index = 0; index < this._keys.length; index++) {
  26754. var prop = this._keys[index];
  26755. other[prop] = this[prop];
  26756. }
  26757. };
  26758. MaterialDefines.prototype.reset = function () {
  26759. for (var index = 0; index < this._keys.length; index++) {
  26760. var prop = this._keys[index];
  26761. if (typeof (this[prop]) === "number") {
  26762. this[prop] = 0;
  26763. }
  26764. else {
  26765. this[prop] = false;
  26766. }
  26767. }
  26768. };
  26769. MaterialDefines.prototype.toString = function () {
  26770. var result = "";
  26771. for (var index = 0; index < this._keys.length; index++) {
  26772. var prop = this._keys[index];
  26773. var value = this[prop];
  26774. if (typeof (value) === "number") {
  26775. result += "#define " + prop + " " + this[prop] + "\n";
  26776. }
  26777. else if (value) {
  26778. result += "#define " + prop + "\n";
  26779. }
  26780. }
  26781. return result;
  26782. };
  26783. return MaterialDefines;
  26784. }());
  26785. BABYLON.MaterialDefines = MaterialDefines;
  26786. var Material = /** @class */ (function () {
  26787. function Material(name, scene, doNotAdd) {
  26788. this.checkReadyOnEveryCall = false;
  26789. this.checkReadyOnlyOnce = false;
  26790. this.state = "";
  26791. this.alpha = 1.0;
  26792. this._backFaceCulling = true;
  26793. this.doNotSerialize = false;
  26794. this.storeEffectOnSubMeshes = false;
  26795. /**
  26796. * An event triggered when the material is disposed.
  26797. * @type {BABYLON.Observable}
  26798. */
  26799. this.onDisposeObservable = new BABYLON.Observable();
  26800. /**
  26801. * An event triggered when the material is bound.
  26802. * @type {BABYLON.Observable}
  26803. */
  26804. this.onBindObservable = new BABYLON.Observable();
  26805. /**
  26806. * An event triggered when the material is unbound.
  26807. * @type {BABYLON.Observable}
  26808. */
  26809. this.onUnBindObservable = new BABYLON.Observable();
  26810. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26811. this._needDepthPrePass = false;
  26812. this.disableDepthWrite = false;
  26813. this.forceDepthWrite = false;
  26814. this.separateCullingPass = false;
  26815. this._fogEnabled = true;
  26816. this.pointSize = 1.0;
  26817. this.zOffset = 0;
  26818. this._wasPreviouslyReady = false;
  26819. this._fillMode = Material.TriangleFillMode;
  26820. this.name = name;
  26821. this.id = name || BABYLON.Tools.RandomId();
  26822. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26823. if (this._scene.useRightHandedSystem) {
  26824. this.sideOrientation = Material.ClockWiseSideOrientation;
  26825. }
  26826. else {
  26827. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26828. }
  26829. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  26830. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  26831. if (!doNotAdd) {
  26832. this._scene.materials.push(this);
  26833. }
  26834. }
  26835. Object.defineProperty(Material, "TriangleFillMode", {
  26836. get: function () {
  26837. return Material._TriangleFillMode;
  26838. },
  26839. enumerable: true,
  26840. configurable: true
  26841. });
  26842. Object.defineProperty(Material, "WireFrameFillMode", {
  26843. get: function () {
  26844. return Material._WireFrameFillMode;
  26845. },
  26846. enumerable: true,
  26847. configurable: true
  26848. });
  26849. Object.defineProperty(Material, "PointFillMode", {
  26850. get: function () {
  26851. return Material._PointFillMode;
  26852. },
  26853. enumerable: true,
  26854. configurable: true
  26855. });
  26856. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26857. get: function () {
  26858. return Material._ClockWiseSideOrientation;
  26859. },
  26860. enumerable: true,
  26861. configurable: true
  26862. });
  26863. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26864. get: function () {
  26865. return Material._CounterClockWiseSideOrientation;
  26866. },
  26867. enumerable: true,
  26868. configurable: true
  26869. });
  26870. Object.defineProperty(Material, "TextureDirtyFlag", {
  26871. get: function () {
  26872. return Material._TextureDirtyFlag;
  26873. },
  26874. enumerable: true,
  26875. configurable: true
  26876. });
  26877. Object.defineProperty(Material, "LightDirtyFlag", {
  26878. get: function () {
  26879. return Material._LightDirtyFlag;
  26880. },
  26881. enumerable: true,
  26882. configurable: true
  26883. });
  26884. Object.defineProperty(Material, "FresnelDirtyFlag", {
  26885. get: function () {
  26886. return Material._FresnelDirtyFlag;
  26887. },
  26888. enumerable: true,
  26889. configurable: true
  26890. });
  26891. Object.defineProperty(Material, "AttributesDirtyFlag", {
  26892. get: function () {
  26893. return Material._AttributesDirtyFlag;
  26894. },
  26895. enumerable: true,
  26896. configurable: true
  26897. });
  26898. Object.defineProperty(Material, "MiscDirtyFlag", {
  26899. get: function () {
  26900. return Material._MiscDirtyFlag;
  26901. },
  26902. enumerable: true,
  26903. configurable: true
  26904. });
  26905. Object.defineProperty(Material.prototype, "backFaceCulling", {
  26906. get: function () {
  26907. return this._backFaceCulling;
  26908. },
  26909. set: function (value) {
  26910. if (this._backFaceCulling === value) {
  26911. return;
  26912. }
  26913. this._backFaceCulling = value;
  26914. this.markAsDirty(Material.TextureDirtyFlag);
  26915. },
  26916. enumerable: true,
  26917. configurable: true
  26918. });
  26919. Object.defineProperty(Material.prototype, "onDispose", {
  26920. set: function (callback) {
  26921. if (this._onDisposeObserver) {
  26922. this.onDisposeObservable.remove(this._onDisposeObserver);
  26923. }
  26924. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26925. },
  26926. enumerable: true,
  26927. configurable: true
  26928. });
  26929. Object.defineProperty(Material.prototype, "onBind", {
  26930. set: function (callback) {
  26931. if (this._onBindObserver) {
  26932. this.onBindObservable.remove(this._onBindObserver);
  26933. }
  26934. this._onBindObserver = this.onBindObservable.add(callback);
  26935. },
  26936. enumerable: true,
  26937. configurable: true
  26938. });
  26939. Object.defineProperty(Material.prototype, "alphaMode", {
  26940. get: function () {
  26941. return this._alphaMode;
  26942. },
  26943. set: function (value) {
  26944. if (this._alphaMode === value) {
  26945. return;
  26946. }
  26947. this._alphaMode = value;
  26948. this.markAsDirty(Material.TextureDirtyFlag);
  26949. },
  26950. enumerable: true,
  26951. configurable: true
  26952. });
  26953. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  26954. get: function () {
  26955. return this._needDepthPrePass;
  26956. },
  26957. set: function (value) {
  26958. if (this._needDepthPrePass === value) {
  26959. return;
  26960. }
  26961. this._needDepthPrePass = value;
  26962. if (this._needDepthPrePass) {
  26963. this.checkReadyOnEveryCall = true;
  26964. }
  26965. },
  26966. enumerable: true,
  26967. configurable: true
  26968. });
  26969. Object.defineProperty(Material.prototype, "fogEnabled", {
  26970. get: function () {
  26971. return this._fogEnabled;
  26972. },
  26973. set: function (value) {
  26974. if (this._fogEnabled === value) {
  26975. return;
  26976. }
  26977. this._fogEnabled = value;
  26978. this.markAsDirty(Material.MiscDirtyFlag);
  26979. },
  26980. enumerable: true,
  26981. configurable: true
  26982. });
  26983. Object.defineProperty(Material.prototype, "wireframe", {
  26984. get: function () {
  26985. return this._fillMode === Material.WireFrameFillMode;
  26986. },
  26987. set: function (value) {
  26988. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26989. },
  26990. enumerable: true,
  26991. configurable: true
  26992. });
  26993. Object.defineProperty(Material.prototype, "pointsCloud", {
  26994. get: function () {
  26995. return this._fillMode === Material.PointFillMode;
  26996. },
  26997. set: function (value) {
  26998. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26999. },
  27000. enumerable: true,
  27001. configurable: true
  27002. });
  27003. Object.defineProperty(Material.prototype, "fillMode", {
  27004. get: function () {
  27005. return this._fillMode;
  27006. },
  27007. set: function (value) {
  27008. if (this._fillMode === value) {
  27009. return;
  27010. }
  27011. this._fillMode = value;
  27012. this.markAsDirty(Material.MiscDirtyFlag);
  27013. },
  27014. enumerable: true,
  27015. configurable: true
  27016. });
  27017. /**
  27018. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27019. * subclasses should override adding information pertainent to themselves
  27020. */
  27021. Material.prototype.toString = function (fullDetails) {
  27022. var ret = "Name: " + this.name;
  27023. if (fullDetails) {
  27024. }
  27025. return ret;
  27026. };
  27027. /**
  27028. * Child classes can use it to update shaders
  27029. */
  27030. Material.prototype.getClassName = function () {
  27031. return "Material";
  27032. };
  27033. Object.defineProperty(Material.prototype, "isFrozen", {
  27034. get: function () {
  27035. return this.checkReadyOnlyOnce;
  27036. },
  27037. enumerable: true,
  27038. configurable: true
  27039. });
  27040. Material.prototype.freeze = function () {
  27041. this.checkReadyOnlyOnce = true;
  27042. };
  27043. Material.prototype.unfreeze = function () {
  27044. this.checkReadyOnlyOnce = false;
  27045. };
  27046. Material.prototype.isReady = function (mesh, useInstances) {
  27047. return true;
  27048. };
  27049. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27050. return false;
  27051. };
  27052. Material.prototype.getEffect = function () {
  27053. return this._effect;
  27054. };
  27055. Material.prototype.getScene = function () {
  27056. return this._scene;
  27057. };
  27058. Material.prototype.needAlphaBlending = function () {
  27059. return (this.alpha < 1.0);
  27060. };
  27061. Material.prototype.needAlphaTesting = function () {
  27062. return false;
  27063. };
  27064. Material.prototype.getAlphaTestTexture = function () {
  27065. return null;
  27066. };
  27067. Material.prototype.markDirty = function () {
  27068. this._wasPreviouslyReady = false;
  27069. };
  27070. Material.prototype._preBind = function (effect, overrideOrientation) {
  27071. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27072. var engine = this._scene.getEngine();
  27073. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27074. var reverse = orientation === Material.ClockWiseSideOrientation;
  27075. engine.enableEffect(effect ? effect : this._effect);
  27076. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27077. return reverse;
  27078. };
  27079. Material.prototype.bind = function (world, mesh) {
  27080. };
  27081. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27082. };
  27083. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27084. };
  27085. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27086. sceneUbo.bindToEffect(effect, "Scene");
  27087. };
  27088. Material.prototype.bindView = function (effect) {
  27089. if (!this._useUBO) {
  27090. effect.setMatrix("view", this.getScene().getViewMatrix());
  27091. }
  27092. else {
  27093. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27094. }
  27095. };
  27096. Material.prototype.bindViewProjection = function (effect) {
  27097. if (!this._useUBO) {
  27098. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27099. }
  27100. else {
  27101. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27102. }
  27103. };
  27104. Material.prototype._afterBind = function (mesh) {
  27105. this._scene._cachedMaterial = this;
  27106. if (mesh) {
  27107. this._scene._cachedVisibility = mesh.visibility;
  27108. }
  27109. else {
  27110. this._scene._cachedVisibility = 1;
  27111. }
  27112. if (mesh) {
  27113. this.onBindObservable.notifyObservers(mesh);
  27114. }
  27115. if (this.disableDepthWrite) {
  27116. var engine = this._scene.getEngine();
  27117. this._cachedDepthWriteState = engine.getDepthWrite();
  27118. engine.setDepthWrite(false);
  27119. }
  27120. };
  27121. Material.prototype.unbind = function () {
  27122. this.onUnBindObservable.notifyObservers(this);
  27123. if (this.disableDepthWrite) {
  27124. var engine = this._scene.getEngine();
  27125. engine.setDepthWrite(this._cachedDepthWriteState);
  27126. }
  27127. };
  27128. Material.prototype.getActiveTextures = function () {
  27129. return [];
  27130. };
  27131. Material.prototype.hasTexture = function (texture) {
  27132. return false;
  27133. };
  27134. Material.prototype.clone = function (name) {
  27135. return null;
  27136. };
  27137. Material.prototype.getBindedMeshes = function () {
  27138. var result = new Array();
  27139. for (var index = 0; index < this._scene.meshes.length; index++) {
  27140. var mesh = this._scene.meshes[index];
  27141. if (mesh.material === this) {
  27142. result.push(mesh);
  27143. }
  27144. }
  27145. return result;
  27146. };
  27147. /**
  27148. * Force shader compilation including textures ready check
  27149. */
  27150. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27151. var _this = this;
  27152. var subMesh = new BABYLON.BaseSubMesh();
  27153. var scene = this.getScene();
  27154. var engine = scene.getEngine();
  27155. var checkReady = function () {
  27156. if (!_this._scene || !_this._scene.getEngine()) {
  27157. return;
  27158. }
  27159. if (subMesh._materialDefines) {
  27160. subMesh._materialDefines._renderId = -1;
  27161. }
  27162. var alphaTestState = engine.getAlphaTesting();
  27163. var clipPlaneState = scene.clipPlane;
  27164. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  27165. if (options && options.clipPlane) {
  27166. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27167. }
  27168. if (_this.storeEffectOnSubMeshes) {
  27169. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27170. if (onCompiled) {
  27171. onCompiled(_this);
  27172. }
  27173. }
  27174. else {
  27175. setTimeout(checkReady, 16);
  27176. }
  27177. }
  27178. else {
  27179. if (_this.isReady(mesh)) {
  27180. if (onCompiled) {
  27181. onCompiled(_this);
  27182. }
  27183. }
  27184. else {
  27185. setTimeout(checkReady, 16);
  27186. }
  27187. }
  27188. engine.setAlphaTesting(alphaTestState);
  27189. if (options && options.clipPlane) {
  27190. scene.clipPlane = clipPlaneState;
  27191. }
  27192. };
  27193. checkReady();
  27194. };
  27195. Material.prototype.markAsDirty = function (flag) {
  27196. if (flag & Material.TextureDirtyFlag) {
  27197. this._markAllSubMeshesAsTexturesDirty();
  27198. }
  27199. if (flag & Material.LightDirtyFlag) {
  27200. this._markAllSubMeshesAsLightsDirty();
  27201. }
  27202. if (flag & Material.FresnelDirtyFlag) {
  27203. this._markAllSubMeshesAsFresnelDirty();
  27204. }
  27205. if (flag & Material.AttributesDirtyFlag) {
  27206. this._markAllSubMeshesAsAttributesDirty();
  27207. }
  27208. if (flag & Material.MiscDirtyFlag) {
  27209. this._markAllSubMeshesAsMiscDirty();
  27210. }
  27211. this.getScene().resetCachedMaterial();
  27212. };
  27213. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27214. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27215. var mesh = _a[_i];
  27216. if (!mesh.subMeshes) {
  27217. continue;
  27218. }
  27219. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27220. var subMesh = _c[_b];
  27221. if (subMesh.getMaterial() !== this) {
  27222. continue;
  27223. }
  27224. if (!subMesh._materialDefines) {
  27225. continue;
  27226. }
  27227. func(subMesh._materialDefines);
  27228. }
  27229. }
  27230. };
  27231. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27232. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27233. };
  27234. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27235. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27236. };
  27237. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27238. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27239. };
  27240. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27241. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27242. };
  27243. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27244. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27245. };
  27246. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27247. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27248. };
  27249. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27250. // Animations
  27251. this.getScene().stopAnimation(this);
  27252. // Remove from scene
  27253. var index = this._scene.materials.indexOf(this);
  27254. if (index >= 0) {
  27255. this._scene.materials.splice(index, 1);
  27256. }
  27257. // Remove from meshes
  27258. for (index = 0; index < this._scene.meshes.length; index++) {
  27259. var mesh = this._scene.meshes[index];
  27260. if (mesh.material === this) {
  27261. mesh.material = null;
  27262. if (mesh.geometry) {
  27263. var geometry = (mesh.geometry);
  27264. if (this.storeEffectOnSubMeshes) {
  27265. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27266. var subMesh = _a[_i];
  27267. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27268. if (forceDisposeEffect && subMesh._materialEffect) {
  27269. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27270. }
  27271. }
  27272. }
  27273. else {
  27274. geometry._releaseVertexArrayObject(this._effect);
  27275. }
  27276. }
  27277. }
  27278. }
  27279. this._uniformBuffer.dispose();
  27280. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27281. if (forceDisposeEffect && this._effect) {
  27282. if (!this.storeEffectOnSubMeshes) {
  27283. this._scene.getEngine()._releaseEffect(this._effect);
  27284. }
  27285. this._effect = null;
  27286. }
  27287. // Callback
  27288. this.onDisposeObservable.notifyObservers(this);
  27289. this.onDisposeObservable.clear();
  27290. this.onBindObservable.clear();
  27291. this.onUnBindObservable.clear();
  27292. };
  27293. Material.prototype.serialize = function () {
  27294. return BABYLON.SerializationHelper.Serialize(this);
  27295. };
  27296. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27297. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27298. multiMaterial.id = parsedMultiMaterial.id;
  27299. if (BABYLON.Tags) {
  27300. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27301. }
  27302. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27303. var subMatId = parsedMultiMaterial.materials[matIndex];
  27304. if (subMatId) {
  27305. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27306. }
  27307. else {
  27308. multiMaterial.subMaterials.push(null);
  27309. }
  27310. }
  27311. return multiMaterial;
  27312. };
  27313. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27314. if (!parsedMaterial.customType) {
  27315. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27316. }
  27317. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27318. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27319. if (!BABYLON.LegacyPBRMaterial) {
  27320. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27321. return;
  27322. }
  27323. }
  27324. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27325. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27326. ;
  27327. };
  27328. Material._TriangleFillMode = 0;
  27329. Material._WireFrameFillMode = 1;
  27330. Material._PointFillMode = 2;
  27331. Material._ClockWiseSideOrientation = 0;
  27332. Material._CounterClockWiseSideOrientation = 1;
  27333. Material._TextureDirtyFlag = 1;
  27334. Material._LightDirtyFlag = 2;
  27335. Material._FresnelDirtyFlag = 4;
  27336. Material._AttributesDirtyFlag = 8;
  27337. Material._MiscDirtyFlag = 16;
  27338. __decorate([
  27339. BABYLON.serialize()
  27340. ], Material.prototype, "id", void 0);
  27341. __decorate([
  27342. BABYLON.serialize()
  27343. ], Material.prototype, "name", void 0);
  27344. __decorate([
  27345. BABYLON.serialize()
  27346. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27347. __decorate([
  27348. BABYLON.serialize()
  27349. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27350. __decorate([
  27351. BABYLON.serialize()
  27352. ], Material.prototype, "state", void 0);
  27353. __decorate([
  27354. BABYLON.serialize()
  27355. ], Material.prototype, "alpha", void 0);
  27356. __decorate([
  27357. BABYLON.serialize("backFaceCulling")
  27358. ], Material.prototype, "_backFaceCulling", void 0);
  27359. __decorate([
  27360. BABYLON.serialize()
  27361. ], Material.prototype, "sideOrientation", void 0);
  27362. __decorate([
  27363. BABYLON.serialize("alphaMode")
  27364. ], Material.prototype, "_alphaMode", void 0);
  27365. __decorate([
  27366. BABYLON.serialize()
  27367. ], Material.prototype, "_needDepthPrePass", void 0);
  27368. __decorate([
  27369. BABYLON.serialize()
  27370. ], Material.prototype, "disableDepthWrite", void 0);
  27371. __decorate([
  27372. BABYLON.serialize()
  27373. ], Material.prototype, "forceDepthWrite", void 0);
  27374. __decorate([
  27375. BABYLON.serialize()
  27376. ], Material.prototype, "separateCullingPass", void 0);
  27377. __decorate([
  27378. BABYLON.serialize("fogEnabled")
  27379. ], Material.prototype, "_fogEnabled", void 0);
  27380. __decorate([
  27381. BABYLON.serialize()
  27382. ], Material.prototype, "pointSize", void 0);
  27383. __decorate([
  27384. BABYLON.serialize()
  27385. ], Material.prototype, "zOffset", void 0);
  27386. __decorate([
  27387. BABYLON.serialize()
  27388. ], Material.prototype, "wireframe", null);
  27389. __decorate([
  27390. BABYLON.serialize()
  27391. ], Material.prototype, "pointsCloud", null);
  27392. __decorate([
  27393. BABYLON.serialize()
  27394. ], Material.prototype, "fillMode", null);
  27395. return Material;
  27396. }());
  27397. BABYLON.Material = Material;
  27398. })(BABYLON || (BABYLON = {}));
  27399. //# sourceMappingURL=babylon.material.js.map
  27400. var BABYLON;
  27401. (function (BABYLON) {
  27402. var UniformBuffer = /** @class */ (function () {
  27403. /**
  27404. * Uniform buffer objects.
  27405. *
  27406. * Handles blocks of uniform on the GPU.
  27407. *
  27408. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  27409. *
  27410. * For more information, please refer to :
  27411. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  27412. */
  27413. function UniformBuffer(engine, data, dynamic) {
  27414. this._engine = engine;
  27415. this._noUBO = !engine.supportsUniformBuffers;
  27416. this._dynamic = dynamic;
  27417. this._data = data || [];
  27418. this._uniformLocations = {};
  27419. this._uniformSizes = {};
  27420. this._uniformLocationPointer = 0;
  27421. this._needSync = false;
  27422. if (this._noUBO) {
  27423. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  27424. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  27425. this.updateFloat = this._updateFloatForEffect;
  27426. this.updateFloat2 = this._updateFloat2ForEffect;
  27427. this.updateFloat3 = this._updateFloat3ForEffect;
  27428. this.updateFloat4 = this._updateFloat4ForEffect;
  27429. this.updateMatrix = this._updateMatrixForEffect;
  27430. this.updateVector3 = this._updateVector3ForEffect;
  27431. this.updateVector4 = this._updateVector4ForEffect;
  27432. this.updateColor3 = this._updateColor3ForEffect;
  27433. this.updateColor4 = this._updateColor4ForEffect;
  27434. }
  27435. else {
  27436. this._engine._uniformBuffers.push(this);
  27437. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  27438. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  27439. this.updateFloat = this._updateFloatForUniform;
  27440. this.updateFloat2 = this._updateFloat2ForUniform;
  27441. this.updateFloat3 = this._updateFloat3ForUniform;
  27442. this.updateFloat4 = this._updateFloat4ForUniform;
  27443. this.updateMatrix = this._updateMatrixForUniform;
  27444. this.updateVector3 = this._updateVector3ForUniform;
  27445. this.updateVector4 = this._updateVector4ForUniform;
  27446. this.updateColor3 = this._updateColor3ForUniform;
  27447. this.updateColor4 = this._updateColor4ForUniform;
  27448. }
  27449. }
  27450. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  27451. // Properties
  27452. /**
  27453. * Indicates if the buffer is using the WebGL2 UBO implementation,
  27454. * or just falling back on setUniformXXX calls.
  27455. */
  27456. get: function () {
  27457. return !this._noUBO;
  27458. },
  27459. enumerable: true,
  27460. configurable: true
  27461. });
  27462. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  27463. /**
  27464. * Indicates if the WebGL underlying uniform buffer is in sync
  27465. * with the javascript cache data.
  27466. */
  27467. get: function () {
  27468. return !this._needSync;
  27469. },
  27470. enumerable: true,
  27471. configurable: true
  27472. });
  27473. /**
  27474. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27475. * Also, a dynamic UniformBuffer will disable cache verification and always
  27476. * update the underlying WebGL uniform buffer to the GPU.
  27477. */
  27478. UniformBuffer.prototype.isDynamic = function () {
  27479. return this._dynamic !== undefined;
  27480. };
  27481. /**
  27482. * The data cache on JS side.
  27483. */
  27484. UniformBuffer.prototype.getData = function () {
  27485. return this._bufferData;
  27486. };
  27487. /**
  27488. * The underlying WebGL Uniform buffer.
  27489. */
  27490. UniformBuffer.prototype.getBuffer = function () {
  27491. return this._buffer;
  27492. };
  27493. /**
  27494. * std140 layout specifies how to align data within an UBO structure.
  27495. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27496. * for specs.
  27497. */
  27498. UniformBuffer.prototype._fillAlignment = function (size) {
  27499. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27500. // and 4x4 matrices
  27501. // TODO : change if other types are used
  27502. var alignment;
  27503. if (size <= 2) {
  27504. alignment = size;
  27505. }
  27506. else {
  27507. alignment = 4;
  27508. }
  27509. if ((this._uniformLocationPointer % alignment) !== 0) {
  27510. var oldPointer = this._uniformLocationPointer;
  27511. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27512. var diff = this._uniformLocationPointer - oldPointer;
  27513. for (var i = 0; i < diff; i++) {
  27514. this._data.push(0);
  27515. }
  27516. }
  27517. };
  27518. /**
  27519. * Adds an uniform in the buffer.
  27520. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27521. * for the layout to be correct !
  27522. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27523. * @param {number|number[]} size Data size, or data directly.
  27524. */
  27525. UniformBuffer.prototype.addUniform = function (name, size) {
  27526. if (this._noUBO) {
  27527. return;
  27528. }
  27529. if (this._uniformLocations[name] !== undefined) {
  27530. // Already existing uniform
  27531. return;
  27532. }
  27533. // This function must be called in the order of the shader layout !
  27534. // size can be the size of the uniform, or data directly
  27535. var data;
  27536. if (size instanceof Array) {
  27537. data = size;
  27538. size = data.length;
  27539. }
  27540. else {
  27541. size = size;
  27542. data = [];
  27543. // Fill with zeros
  27544. for (var i = 0; i < size; i++) {
  27545. data.push(0);
  27546. }
  27547. }
  27548. this._fillAlignment(size);
  27549. this._uniformSizes[name] = size;
  27550. this._uniformLocations[name] = this._uniformLocationPointer;
  27551. this._uniformLocationPointer += size;
  27552. for (var i = 0; i < size; i++) {
  27553. this._data.push(data[i]);
  27554. }
  27555. this._needSync = true;
  27556. };
  27557. /**
  27558. * Wrapper for addUniform.
  27559. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27560. * @param {Matrix} mat A 4x4 matrix.
  27561. */
  27562. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27563. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27564. };
  27565. /**
  27566. * Wrapper for addUniform.
  27567. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27568. * @param {number} x
  27569. * @param {number} y
  27570. */
  27571. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27572. var temp = [x, y];
  27573. this.addUniform(name, temp);
  27574. };
  27575. /**
  27576. * Wrapper for addUniform.
  27577. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27578. * @param {number} x
  27579. * @param {number} y
  27580. * @param {number} z
  27581. */
  27582. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27583. var temp = [x, y, z];
  27584. this.addUniform(name, temp);
  27585. };
  27586. /**
  27587. * Wrapper for addUniform.
  27588. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27589. * @param {Color3} color
  27590. */
  27591. UniformBuffer.prototype.addColor3 = function (name, color) {
  27592. var temp = new Array();
  27593. color.toArray(temp);
  27594. this.addUniform(name, temp);
  27595. };
  27596. /**
  27597. * Wrapper for addUniform.
  27598. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27599. * @param {Color3} color
  27600. * @param {number} alpha
  27601. */
  27602. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27603. var temp = new Array();
  27604. color.toArray(temp);
  27605. temp.push(alpha);
  27606. this.addUniform(name, temp);
  27607. };
  27608. /**
  27609. * Wrapper for addUniform.
  27610. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27611. * @param {Vector3} vector
  27612. */
  27613. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27614. var temp = new Array();
  27615. vector.toArray(temp);
  27616. this.addUniform(name, temp);
  27617. };
  27618. /**
  27619. * Wrapper for addUniform.
  27620. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27621. */
  27622. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27623. this.addUniform(name, 12);
  27624. };
  27625. /**
  27626. * Wrapper for addUniform.
  27627. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27628. */
  27629. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27630. this.addUniform(name, 8);
  27631. };
  27632. /**
  27633. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27634. */
  27635. UniformBuffer.prototype.create = function () {
  27636. if (this._noUBO) {
  27637. return;
  27638. }
  27639. if (this._buffer) {
  27640. return; // nothing to do
  27641. }
  27642. // See spec, alignment must be filled as a vec4
  27643. this._fillAlignment(4);
  27644. this._bufferData = new Float32Array(this._data);
  27645. this._rebuild();
  27646. this._needSync = true;
  27647. };
  27648. UniformBuffer.prototype._rebuild = function () {
  27649. if (this._noUBO) {
  27650. return;
  27651. }
  27652. if (this._dynamic) {
  27653. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27654. }
  27655. else {
  27656. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27657. }
  27658. };
  27659. /**
  27660. * Updates the WebGL Uniform Buffer on the GPU.
  27661. * If the `dynamic` flag is set to true, no cache comparison is done.
  27662. * Otherwise, the buffer will be updated only if the cache differs.
  27663. */
  27664. UniformBuffer.prototype.update = function () {
  27665. if (!this._buffer) {
  27666. this.create();
  27667. return;
  27668. }
  27669. if (!this._dynamic && !this._needSync) {
  27670. return;
  27671. }
  27672. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27673. this._needSync = false;
  27674. };
  27675. /**
  27676. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  27677. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27678. * @param {number[]|Float32Array} data Flattened data
  27679. * @param {number} size Size of the data.
  27680. */
  27681. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  27682. var location = this._uniformLocations[uniformName];
  27683. if (location === undefined) {
  27684. if (this._buffer) {
  27685. // Cannot add an uniform if the buffer is already created
  27686. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  27687. return;
  27688. }
  27689. this.addUniform(uniformName, size);
  27690. location = this._uniformLocations[uniformName];
  27691. }
  27692. if (!this._buffer) {
  27693. this.create();
  27694. }
  27695. if (!this._dynamic) {
  27696. // Cache for static uniform buffers
  27697. var changed = false;
  27698. for (var i = 0; i < size; i++) {
  27699. if (this._bufferData[location + i] !== data[i]) {
  27700. changed = true;
  27701. this._bufferData[location + i] = data[i];
  27702. }
  27703. }
  27704. this._needSync = this._needSync || changed;
  27705. }
  27706. else {
  27707. // No cache for dynamic
  27708. for (var i = 0; i < size; i++) {
  27709. this._bufferData[location + i] = data[i];
  27710. }
  27711. }
  27712. };
  27713. // Update methods
  27714. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  27715. // To match std140, matrix must be realigned
  27716. for (var i = 0; i < 3; i++) {
  27717. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  27718. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  27719. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  27720. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27721. }
  27722. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  27723. };
  27724. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  27725. this._currentEffect.setMatrix3x3(name, matrix);
  27726. };
  27727. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  27728. this._currentEffect.setMatrix2x2(name, matrix);
  27729. };
  27730. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  27731. // To match std140, matrix must be realigned
  27732. for (var i = 0; i < 2; i++) {
  27733. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  27734. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  27735. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  27736. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27737. }
  27738. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  27739. };
  27740. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  27741. this._currentEffect.setFloat(name, x);
  27742. };
  27743. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  27744. UniformBuffer._tempBuffer[0] = x;
  27745. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  27746. };
  27747. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  27748. if (suffix === void 0) { suffix = ""; }
  27749. this._currentEffect.setFloat2(name + suffix, x, y);
  27750. };
  27751. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  27752. if (suffix === void 0) { suffix = ""; }
  27753. UniformBuffer._tempBuffer[0] = x;
  27754. UniformBuffer._tempBuffer[1] = y;
  27755. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  27756. };
  27757. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  27758. if (suffix === void 0) { suffix = ""; }
  27759. this._currentEffect.setFloat3(name + suffix, x, y, z);
  27760. };
  27761. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  27762. if (suffix === void 0) { suffix = ""; }
  27763. UniformBuffer._tempBuffer[0] = x;
  27764. UniformBuffer._tempBuffer[1] = y;
  27765. UniformBuffer._tempBuffer[2] = z;
  27766. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27767. };
  27768. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  27769. if (suffix === void 0) { suffix = ""; }
  27770. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  27771. };
  27772. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  27773. if (suffix === void 0) { suffix = ""; }
  27774. UniformBuffer._tempBuffer[0] = x;
  27775. UniformBuffer._tempBuffer[1] = y;
  27776. UniformBuffer._tempBuffer[2] = z;
  27777. UniformBuffer._tempBuffer[3] = w;
  27778. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27779. };
  27780. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  27781. this._currentEffect.setMatrix(name, mat);
  27782. };
  27783. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  27784. this.updateUniform(name, mat.toArray(), 16);
  27785. };
  27786. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  27787. this._currentEffect.setVector3(name, vector);
  27788. };
  27789. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  27790. vector.toArray(UniformBuffer._tempBuffer);
  27791. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27792. };
  27793. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  27794. this._currentEffect.setVector4(name, vector);
  27795. };
  27796. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  27797. vector.toArray(UniformBuffer._tempBuffer);
  27798. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27799. };
  27800. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  27801. if (suffix === void 0) { suffix = ""; }
  27802. this._currentEffect.setColor3(name + suffix, color);
  27803. };
  27804. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  27805. if (suffix === void 0) { suffix = ""; }
  27806. color.toArray(UniformBuffer._tempBuffer);
  27807. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27808. };
  27809. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  27810. if (suffix === void 0) { suffix = ""; }
  27811. this._currentEffect.setColor4(name + suffix, color, alpha);
  27812. };
  27813. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  27814. if (suffix === void 0) { suffix = ""; }
  27815. color.toArray(UniformBuffer._tempBuffer);
  27816. UniformBuffer._tempBuffer[3] = alpha;
  27817. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27818. };
  27819. /**
  27820. * Sets a sampler uniform on the effect.
  27821. * @param {string} name Name of the sampler.
  27822. * @param {Texture} texture
  27823. */
  27824. UniformBuffer.prototype.setTexture = function (name, texture) {
  27825. this._currentEffect.setTexture(name, texture);
  27826. };
  27827. /**
  27828. * Directly updates the value of the uniform in the cache AND on the GPU.
  27829. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27830. * @param {number[]|Float32Array} data Flattened data
  27831. */
  27832. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  27833. this.updateUniform(uniformName, data, data.length);
  27834. this.update();
  27835. };
  27836. /**
  27837. * Binds this uniform buffer to an effect.
  27838. * @param {Effect} effect
  27839. * @param {string} name Name of the uniform block in the shader.
  27840. */
  27841. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  27842. this._currentEffect = effect;
  27843. if (this._noUBO || !this._buffer) {
  27844. return;
  27845. }
  27846. effect.bindUniformBuffer(this._buffer, name);
  27847. };
  27848. /**
  27849. * Disposes the uniform buffer.
  27850. */
  27851. UniformBuffer.prototype.dispose = function () {
  27852. if (this._noUBO) {
  27853. return;
  27854. }
  27855. var index = this._engine._uniformBuffers.indexOf(this);
  27856. if (index !== -1) {
  27857. this._engine._uniformBuffers.splice(index, 1);
  27858. }
  27859. if (!this._buffer) {
  27860. return;
  27861. }
  27862. if (this._engine._releaseBuffer(this._buffer)) {
  27863. this._buffer = null;
  27864. }
  27865. };
  27866. // Pool for avoiding memory leaks
  27867. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  27868. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  27869. return UniformBuffer;
  27870. }());
  27871. BABYLON.UniformBuffer = UniformBuffer;
  27872. })(BABYLON || (BABYLON = {}));
  27873. //# sourceMappingURL=babylon.uniformBuffer.js.map
  27874. var BABYLON;
  27875. (function (BABYLON) {
  27876. var PushMaterial = /** @class */ (function (_super) {
  27877. __extends(PushMaterial, _super);
  27878. function PushMaterial(name, scene) {
  27879. var _this = _super.call(this, name, scene) || this;
  27880. _this.storeEffectOnSubMeshes = true;
  27881. return _this;
  27882. }
  27883. PushMaterial.prototype.getEffect = function () {
  27884. return this._activeEffect;
  27885. };
  27886. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  27887. if (!mesh) {
  27888. return false;
  27889. }
  27890. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27891. return true;
  27892. }
  27893. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  27894. };
  27895. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27896. this._activeEffect.setMatrix("world", world);
  27897. };
  27898. PushMaterial.prototype.bind = function (world, mesh) {
  27899. if (!mesh) {
  27900. return;
  27901. }
  27902. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  27903. };
  27904. PushMaterial.prototype._afterBind = function (mesh, effect) {
  27905. if (effect === void 0) { effect = null; }
  27906. _super.prototype._afterBind.call(this, mesh);
  27907. this.getScene()._cachedEffect = effect;
  27908. };
  27909. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  27910. if (visibility === void 0) { visibility = 1; }
  27911. return scene.isCachedMaterialInvalid(this, effect, visibility);
  27912. };
  27913. return PushMaterial;
  27914. }(BABYLON.Material));
  27915. BABYLON.PushMaterial = PushMaterial;
  27916. })(BABYLON || (BABYLON = {}));
  27917. //# sourceMappingURL=babylon.pushMaterial.js.map
  27918. var BABYLON;
  27919. (function (BABYLON) {
  27920. var VertexData = /** @class */ (function () {
  27921. function VertexData() {
  27922. }
  27923. VertexData.prototype.set = function (data, kind) {
  27924. switch (kind) {
  27925. case BABYLON.VertexBuffer.PositionKind:
  27926. this.positions = data;
  27927. break;
  27928. case BABYLON.VertexBuffer.NormalKind:
  27929. this.normals = data;
  27930. break;
  27931. case BABYLON.VertexBuffer.TangentKind:
  27932. this.tangents = data;
  27933. break;
  27934. case BABYLON.VertexBuffer.UVKind:
  27935. this.uvs = data;
  27936. break;
  27937. case BABYLON.VertexBuffer.UV2Kind:
  27938. this.uvs2 = data;
  27939. break;
  27940. case BABYLON.VertexBuffer.UV3Kind:
  27941. this.uvs3 = data;
  27942. break;
  27943. case BABYLON.VertexBuffer.UV4Kind:
  27944. this.uvs4 = data;
  27945. break;
  27946. case BABYLON.VertexBuffer.UV5Kind:
  27947. this.uvs5 = data;
  27948. break;
  27949. case BABYLON.VertexBuffer.UV6Kind:
  27950. this.uvs6 = data;
  27951. break;
  27952. case BABYLON.VertexBuffer.ColorKind:
  27953. this.colors = data;
  27954. break;
  27955. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27956. this.matricesIndices = data;
  27957. break;
  27958. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27959. this.matricesWeights = data;
  27960. break;
  27961. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27962. this.matricesIndicesExtra = data;
  27963. break;
  27964. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27965. this.matricesWeightsExtra = data;
  27966. break;
  27967. }
  27968. };
  27969. /**
  27970. * Associates the vertexData to the passed Mesh.
  27971. * Sets it as updatable or not (default `false`).
  27972. * Returns the VertexData.
  27973. */
  27974. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27975. this._applyTo(mesh, updatable);
  27976. return this;
  27977. };
  27978. /**
  27979. * Associates the vertexData to the passed Geometry.
  27980. * Sets it as updatable or not (default `false`).
  27981. * Returns the VertexData.
  27982. */
  27983. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27984. this._applyTo(geometry, updatable);
  27985. return this;
  27986. };
  27987. /**
  27988. * Updates the associated mesh.
  27989. * Returns the VertexData.
  27990. */
  27991. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27992. this._update(mesh);
  27993. return this;
  27994. };
  27995. /**
  27996. * Updates the associated geometry.
  27997. * Returns the VertexData.
  27998. */
  27999. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28000. this._update(geometry);
  28001. return this;
  28002. };
  28003. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28004. if (updatable === void 0) { updatable = false; }
  28005. if (this.positions) {
  28006. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28007. }
  28008. if (this.normals) {
  28009. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28010. }
  28011. if (this.tangents) {
  28012. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28013. }
  28014. if (this.uvs) {
  28015. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28016. }
  28017. if (this.uvs2) {
  28018. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28019. }
  28020. if (this.uvs3) {
  28021. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28022. }
  28023. if (this.uvs4) {
  28024. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28025. }
  28026. if (this.uvs5) {
  28027. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28028. }
  28029. if (this.uvs6) {
  28030. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28031. }
  28032. if (this.colors) {
  28033. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28034. }
  28035. if (this.matricesIndices) {
  28036. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28037. }
  28038. if (this.matricesWeights) {
  28039. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28040. }
  28041. if (this.matricesIndicesExtra) {
  28042. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28043. }
  28044. if (this.matricesWeightsExtra) {
  28045. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28046. }
  28047. if (this.indices) {
  28048. meshOrGeometry.setIndices(this.indices, null, updatable);
  28049. }
  28050. return this;
  28051. };
  28052. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28053. if (this.positions) {
  28054. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28055. }
  28056. if (this.normals) {
  28057. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28058. }
  28059. if (this.tangents) {
  28060. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28061. }
  28062. if (this.uvs) {
  28063. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28064. }
  28065. if (this.uvs2) {
  28066. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28067. }
  28068. if (this.uvs3) {
  28069. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28070. }
  28071. if (this.uvs4) {
  28072. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28073. }
  28074. if (this.uvs5) {
  28075. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28076. }
  28077. if (this.uvs6) {
  28078. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28079. }
  28080. if (this.colors) {
  28081. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28082. }
  28083. if (this.matricesIndices) {
  28084. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28085. }
  28086. if (this.matricesWeights) {
  28087. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28088. }
  28089. if (this.matricesIndicesExtra) {
  28090. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28091. }
  28092. if (this.matricesWeightsExtra) {
  28093. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28094. }
  28095. if (this.indices) {
  28096. meshOrGeometry.setIndices(this.indices, null);
  28097. }
  28098. return this;
  28099. };
  28100. /**
  28101. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28102. * Returns the VertexData.
  28103. */
  28104. VertexData.prototype.transform = function (matrix) {
  28105. var transformed = BABYLON.Vector3.Zero();
  28106. var index;
  28107. if (this.positions) {
  28108. var position = BABYLON.Vector3.Zero();
  28109. for (index = 0; index < this.positions.length; index += 3) {
  28110. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28111. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28112. this.positions[index] = transformed.x;
  28113. this.positions[index + 1] = transformed.y;
  28114. this.positions[index + 2] = transformed.z;
  28115. }
  28116. }
  28117. if (this.normals) {
  28118. var normal = BABYLON.Vector3.Zero();
  28119. for (index = 0; index < this.normals.length; index += 3) {
  28120. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28121. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28122. this.normals[index] = transformed.x;
  28123. this.normals[index + 1] = transformed.y;
  28124. this.normals[index + 2] = transformed.z;
  28125. }
  28126. }
  28127. if (this.tangents) {
  28128. var tangent = BABYLON.Vector4.Zero();
  28129. var tangentTransformed = BABYLON.Vector4.Zero();
  28130. for (index = 0; index < this.tangents.length; index += 4) {
  28131. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28132. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28133. this.tangents[index] = tangentTransformed.x;
  28134. this.tangents[index + 1] = tangentTransformed.y;
  28135. this.tangents[index + 2] = tangentTransformed.z;
  28136. this.tangents[index + 3] = tangentTransformed.w;
  28137. }
  28138. }
  28139. return this;
  28140. };
  28141. /**
  28142. * Merges the passed VertexData into the current one.
  28143. * Returns the modified VertexData.
  28144. */
  28145. VertexData.prototype.merge = function (other, options) {
  28146. options = options || {};
  28147. if (other.indices) {
  28148. if (!this.indices) {
  28149. this.indices = [];
  28150. }
  28151. var offset = this.positions ? this.positions.length / 3 : 0;
  28152. for (var index = 0; index < other.indices.length; index++) {
  28153. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28154. this.indices.push(other.indices[index] + offset);
  28155. }
  28156. }
  28157. this.positions = this._mergeElement(this.positions, other.positions);
  28158. if (!this.positions) {
  28159. return this;
  28160. }
  28161. var count = this.positions.length / 3;
  28162. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28163. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28164. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28165. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28166. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28167. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28168. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28169. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28170. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28171. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28172. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28173. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28174. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28175. return this;
  28176. };
  28177. VertexData.prototype._mergeElement = function (source, other, length) {
  28178. if (length === void 0) { length = 0; }
  28179. if (!other && !source) {
  28180. return null;
  28181. }
  28182. if (!other) {
  28183. return this._mergeElement(source, new Float32Array(source.length), length);
  28184. }
  28185. if (!source) {
  28186. if (length === 0 || length === other.length) {
  28187. return other;
  28188. }
  28189. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28190. }
  28191. var len = other.length + source.length;
  28192. var isSrcTypedArray = source instanceof Float32Array;
  28193. var isOthTypedArray = other instanceof Float32Array;
  28194. // use non-loop method when the source is Float32Array
  28195. if (isSrcTypedArray) {
  28196. var ret32 = new Float32Array(len);
  28197. ret32.set(source);
  28198. ret32.set(other, source.length);
  28199. return ret32;
  28200. // source is number[], when other is also use concat
  28201. }
  28202. else if (!isOthTypedArray) {
  28203. return source.concat(other);
  28204. // source is a number[], but other is a Float32Array, loop required
  28205. }
  28206. else {
  28207. var ret = source.slice(0); // copy source to a separate array
  28208. for (var i = 0, len = other.length; i < len; i++) {
  28209. ret.push(other[i]);
  28210. }
  28211. return ret;
  28212. }
  28213. };
  28214. /**
  28215. * Serializes the VertexData.
  28216. * Returns a serialized object.
  28217. */
  28218. VertexData.prototype.serialize = function () {
  28219. var serializationObject = this.serialize();
  28220. if (this.positions) {
  28221. serializationObject.positions = this.positions;
  28222. }
  28223. if (this.normals) {
  28224. serializationObject.normals = this.normals;
  28225. }
  28226. if (this.tangents) {
  28227. serializationObject.tangents = this.tangents;
  28228. }
  28229. if (this.uvs) {
  28230. serializationObject.uvs = this.uvs;
  28231. }
  28232. if (this.uvs2) {
  28233. serializationObject.uvs2 = this.uvs2;
  28234. }
  28235. if (this.uvs3) {
  28236. serializationObject.uvs3 = this.uvs3;
  28237. }
  28238. if (this.uvs4) {
  28239. serializationObject.uvs4 = this.uvs4;
  28240. }
  28241. if (this.uvs5) {
  28242. serializationObject.uvs5 = this.uvs5;
  28243. }
  28244. if (this.uvs6) {
  28245. serializationObject.uvs6 = this.uvs6;
  28246. }
  28247. if (this.colors) {
  28248. serializationObject.colors = this.colors;
  28249. }
  28250. if (this.matricesIndices) {
  28251. serializationObject.matricesIndices = this.matricesIndices;
  28252. serializationObject.matricesIndices._isExpanded = true;
  28253. }
  28254. if (this.matricesWeights) {
  28255. serializationObject.matricesWeights = this.matricesWeights;
  28256. }
  28257. if (this.matricesIndicesExtra) {
  28258. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28259. serializationObject.matricesIndicesExtra._isExpanded = true;
  28260. }
  28261. if (this.matricesWeightsExtra) {
  28262. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28263. }
  28264. serializationObject.indices = this.indices;
  28265. return serializationObject;
  28266. };
  28267. // Statics
  28268. /**
  28269. * Returns the object VertexData associated to the passed mesh.
  28270. */
  28271. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28272. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28273. };
  28274. /**
  28275. * Returns the object VertexData associated to the passed geometry.
  28276. */
  28277. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28278. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28279. };
  28280. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28281. var result = new VertexData();
  28282. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28283. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28284. }
  28285. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28286. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28287. }
  28288. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28289. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28290. }
  28291. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28292. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28293. }
  28294. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28295. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28296. }
  28297. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28298. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28299. }
  28300. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28301. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28302. }
  28303. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28304. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28305. }
  28306. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28307. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28308. }
  28309. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28310. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28311. }
  28312. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28313. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28314. }
  28315. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28316. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28317. }
  28318. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28319. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28320. }
  28321. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28322. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28323. }
  28324. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28325. return result;
  28326. };
  28327. /**
  28328. * Creates the vertexData of the Ribbon.
  28329. */
  28330. VertexData.CreateRibbon = function (options) {
  28331. var pathArray = options.pathArray;
  28332. var closeArray = options.closeArray || false;
  28333. var closePath = options.closePath || false;
  28334. var invertUV = options.invertUV || false;
  28335. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28336. var offset = options.offset || defaultOffset;
  28337. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28338. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28339. var customUV = options.uvs;
  28340. var customColors = options.colors;
  28341. var positions = [];
  28342. var indices = [];
  28343. var normals = [];
  28344. var uvs = [];
  28345. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28346. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28347. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28348. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28349. var minlg; // minimal length among all paths from pathArray
  28350. var lg = []; // array of path lengths : nb of vertex per path
  28351. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28352. var p; // path iterator
  28353. var i; // point iterator
  28354. var j; // point iterator
  28355. // if single path in pathArray
  28356. if (pathArray.length < 2) {
  28357. var ar1 = [];
  28358. var ar2 = [];
  28359. for (i = 0; i < pathArray[0].length - offset; i++) {
  28360. ar1.push(pathArray[0][i]);
  28361. ar2.push(pathArray[0][i + offset]);
  28362. }
  28363. pathArray = [ar1, ar2];
  28364. }
  28365. // positions and horizontal distances (u)
  28366. var idc = 0;
  28367. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  28368. var path;
  28369. var l;
  28370. minlg = pathArray[0].length;
  28371. var vectlg;
  28372. var dist;
  28373. for (p = 0; p < pathArray.length; p++) {
  28374. uTotalDistance[p] = 0;
  28375. us[p] = [0];
  28376. path = pathArray[p];
  28377. l = path.length;
  28378. minlg = (minlg < l) ? minlg : l;
  28379. j = 0;
  28380. while (j < l) {
  28381. positions.push(path[j].x, path[j].y, path[j].z);
  28382. if (j > 0) {
  28383. vectlg = path[j].subtract(path[j - 1]).length();
  28384. dist = vectlg + uTotalDistance[p];
  28385. us[p].push(dist);
  28386. uTotalDistance[p] = dist;
  28387. }
  28388. j++;
  28389. }
  28390. if (closePath) {
  28391. j--;
  28392. positions.push(path[0].x, path[0].y, path[0].z);
  28393. vectlg = path[j].subtract(path[0]).length();
  28394. dist = vectlg + uTotalDistance[p];
  28395. us[p].push(dist);
  28396. uTotalDistance[p] = dist;
  28397. }
  28398. lg[p] = l + closePathCorr;
  28399. idx[p] = idc;
  28400. idc += (l + closePathCorr);
  28401. }
  28402. // vertical distances (v)
  28403. var path1;
  28404. var path2;
  28405. var vertex1 = null;
  28406. var vertex2 = null;
  28407. for (i = 0; i < minlg + closePathCorr; i++) {
  28408. vTotalDistance[i] = 0;
  28409. vs[i] = [0];
  28410. for (p = 0; p < pathArray.length - 1; p++) {
  28411. path1 = pathArray[p];
  28412. path2 = pathArray[p + 1];
  28413. if (i === minlg) {
  28414. vertex1 = path1[0];
  28415. vertex2 = path2[0];
  28416. }
  28417. else {
  28418. vertex1 = path1[i];
  28419. vertex2 = path2[i];
  28420. }
  28421. vectlg = vertex2.subtract(vertex1).length();
  28422. dist = vectlg + vTotalDistance[i];
  28423. vs[i].push(dist);
  28424. vTotalDistance[i] = dist;
  28425. }
  28426. if (closeArray && vertex2 && vertex1) {
  28427. path1 = pathArray[p];
  28428. path2 = pathArray[0];
  28429. if (i === minlg) {
  28430. vertex2 = path2[0];
  28431. }
  28432. vectlg = vertex2.subtract(vertex1).length();
  28433. dist = vectlg + vTotalDistance[i];
  28434. vTotalDistance[i] = dist;
  28435. }
  28436. }
  28437. // uvs
  28438. var u;
  28439. var v;
  28440. if (customUV) {
  28441. for (p = 0; p < customUV.length; p++) {
  28442. uvs.push(customUV[p].x, customUV[p].y);
  28443. }
  28444. }
  28445. else {
  28446. for (p = 0; p < pathArray.length; p++) {
  28447. for (i = 0; i < minlg + closePathCorr; i++) {
  28448. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  28449. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  28450. if (invertUV) {
  28451. uvs.push(v, u);
  28452. }
  28453. else {
  28454. uvs.push(u, v);
  28455. }
  28456. }
  28457. }
  28458. }
  28459. // indices
  28460. p = 0; // path index
  28461. var pi = 0; // positions array index
  28462. var l1 = lg[p] - 1; // path1 length
  28463. var l2 = lg[p + 1] - 1; // path2 length
  28464. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28465. var shft = idx[1] - idx[0]; // shift
  28466. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28467. while (pi <= min && p < path1nb) {
  28468. // 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
  28469. indices.push(pi, pi + shft, pi + 1);
  28470. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28471. pi += 1;
  28472. if (pi === min) {
  28473. p++;
  28474. if (p === lg.length - 1) {
  28475. shft = idx[0] - idx[p];
  28476. l1 = lg[p] - 1;
  28477. l2 = lg[0] - 1;
  28478. }
  28479. else {
  28480. shft = idx[p + 1] - idx[p];
  28481. l1 = lg[p] - 1;
  28482. l2 = lg[p + 1] - 1;
  28483. }
  28484. pi = idx[p];
  28485. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28486. }
  28487. }
  28488. // normals
  28489. VertexData.ComputeNormals(positions, indices, normals);
  28490. if (closePath) {
  28491. var indexFirst = 0;
  28492. var indexLast = 0;
  28493. for (p = 0; p < pathArray.length; p++) {
  28494. indexFirst = idx[p] * 3;
  28495. if (p + 1 < pathArray.length) {
  28496. indexLast = (idx[p + 1] - 1) * 3;
  28497. }
  28498. else {
  28499. indexLast = normals.length - 3;
  28500. }
  28501. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28502. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28503. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28504. normals[indexLast] = normals[indexFirst];
  28505. normals[indexLast + 1] = normals[indexFirst + 1];
  28506. normals[indexLast + 2] = normals[indexFirst + 2];
  28507. }
  28508. }
  28509. // sides
  28510. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28511. // Colors
  28512. var colors = null;
  28513. if (customColors) {
  28514. colors = new Float32Array(customColors.length * 4);
  28515. for (var c = 0; c < customColors.length; c++) {
  28516. colors[c * 4] = customColors[c].r;
  28517. colors[c * 4 + 1] = customColors[c].g;
  28518. colors[c * 4 + 2] = customColors[c].b;
  28519. colors[c * 4 + 3] = customColors[c].a;
  28520. }
  28521. }
  28522. // Result
  28523. var vertexData = new VertexData();
  28524. var positions32 = new Float32Array(positions);
  28525. var normals32 = new Float32Array(normals);
  28526. var uvs32 = new Float32Array(uvs);
  28527. vertexData.indices = indices;
  28528. vertexData.positions = positions32;
  28529. vertexData.normals = normals32;
  28530. vertexData.uvs = uvs32;
  28531. if (colors) {
  28532. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28533. }
  28534. if (closePath) {
  28535. vertexData._idx = idx;
  28536. }
  28537. return vertexData;
  28538. };
  28539. /**
  28540. * Creates the VertexData of the Box.
  28541. */
  28542. VertexData.CreateBox = function (options) {
  28543. var normalsSource = [
  28544. new BABYLON.Vector3(0, 0, 1),
  28545. new BABYLON.Vector3(0, 0, -1),
  28546. new BABYLON.Vector3(1, 0, 0),
  28547. new BABYLON.Vector3(-1, 0, 0),
  28548. new BABYLON.Vector3(0, 1, 0),
  28549. new BABYLON.Vector3(0, -1, 0)
  28550. ];
  28551. var indices = [];
  28552. var positions = [];
  28553. var normals = [];
  28554. var uvs = [];
  28555. var width = options.width || options.size || 1;
  28556. var height = options.height || options.size || 1;
  28557. var depth = options.depth || options.size || 1;
  28558. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28559. var faceUV = options.faceUV || new Array(6);
  28560. var faceColors = options.faceColors;
  28561. var colors = [];
  28562. // default face colors and UV if undefined
  28563. for (var f = 0; f < 6; f++) {
  28564. if (faceUV[f] === undefined) {
  28565. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28566. }
  28567. if (faceColors && faceColors[f] === undefined) {
  28568. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28569. }
  28570. }
  28571. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28572. // Create each face in turn.
  28573. for (var index = 0; index < normalsSource.length; index++) {
  28574. var normal = normalsSource[index];
  28575. // Get two vectors perpendicular to the face normal and to each other.
  28576. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28577. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28578. // Six indices (two triangles) per face.
  28579. var verticesLength = positions.length / 3;
  28580. indices.push(verticesLength);
  28581. indices.push(verticesLength + 1);
  28582. indices.push(verticesLength + 2);
  28583. indices.push(verticesLength);
  28584. indices.push(verticesLength + 2);
  28585. indices.push(verticesLength + 3);
  28586. // Four vertices per face.
  28587. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28588. positions.push(vertex.x, vertex.y, vertex.z);
  28589. normals.push(normal.x, normal.y, normal.z);
  28590. uvs.push(faceUV[index].z, faceUV[index].w);
  28591. if (faceColors) {
  28592. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28593. }
  28594. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28595. positions.push(vertex.x, vertex.y, vertex.z);
  28596. normals.push(normal.x, normal.y, normal.z);
  28597. uvs.push(faceUV[index].x, faceUV[index].w);
  28598. if (faceColors) {
  28599. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28600. }
  28601. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28602. positions.push(vertex.x, vertex.y, vertex.z);
  28603. normals.push(normal.x, normal.y, normal.z);
  28604. uvs.push(faceUV[index].x, faceUV[index].y);
  28605. if (faceColors) {
  28606. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28607. }
  28608. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28609. positions.push(vertex.x, vertex.y, vertex.z);
  28610. normals.push(normal.x, normal.y, normal.z);
  28611. uvs.push(faceUV[index].z, faceUV[index].y);
  28612. if (faceColors) {
  28613. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28614. }
  28615. }
  28616. // sides
  28617. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28618. // Result
  28619. var vertexData = new VertexData();
  28620. vertexData.indices = indices;
  28621. vertexData.positions = positions;
  28622. vertexData.normals = normals;
  28623. vertexData.uvs = uvs;
  28624. if (faceColors) {
  28625. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28626. vertexData.colors = totalColors;
  28627. }
  28628. return vertexData;
  28629. };
  28630. /**
  28631. * Creates the VertexData of the Sphere.
  28632. */
  28633. VertexData.CreateSphere = function (options) {
  28634. var segments = options.segments || 32;
  28635. var diameterX = options.diameterX || options.diameter || 1;
  28636. var diameterY = options.diameterY || options.diameter || 1;
  28637. var diameterZ = options.diameterZ || options.diameter || 1;
  28638. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28639. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28640. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28641. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28642. var totalZRotationSteps = 2 + segments;
  28643. var totalYRotationSteps = 2 * totalZRotationSteps;
  28644. var indices = [];
  28645. var positions = [];
  28646. var normals = [];
  28647. var uvs = [];
  28648. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28649. var normalizedZ = zRotationStep / totalZRotationSteps;
  28650. var angleZ = normalizedZ * Math.PI * slice;
  28651. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28652. var normalizedY = yRotationStep / totalYRotationSteps;
  28653. var angleY = normalizedY * Math.PI * 2 * arc;
  28654. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28655. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28656. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28657. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28658. var vertex = complete.multiply(radius);
  28659. var normal = complete.divide(radius).normalize();
  28660. positions.push(vertex.x, vertex.y, vertex.z);
  28661. normals.push(normal.x, normal.y, normal.z);
  28662. uvs.push(normalizedY, normalizedZ);
  28663. }
  28664. if (zRotationStep > 0) {
  28665. var verticesCount = positions.length / 3;
  28666. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28667. indices.push((firstIndex));
  28668. indices.push((firstIndex + 1));
  28669. indices.push(firstIndex + totalYRotationSteps + 1);
  28670. indices.push((firstIndex + totalYRotationSteps + 1));
  28671. indices.push((firstIndex + 1));
  28672. indices.push((firstIndex + totalYRotationSteps + 2));
  28673. }
  28674. }
  28675. }
  28676. // Sides
  28677. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28678. // Result
  28679. var vertexData = new VertexData();
  28680. vertexData.indices = indices;
  28681. vertexData.positions = positions;
  28682. vertexData.normals = normals;
  28683. vertexData.uvs = uvs;
  28684. return vertexData;
  28685. };
  28686. /**
  28687. * Creates the VertexData of the Cylinder or Cone.
  28688. */
  28689. VertexData.CreateCylinder = function (options) {
  28690. var height = options.height || 2;
  28691. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28692. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  28693. var tessellation = options.tessellation || 24;
  28694. var subdivisions = options.subdivisions || 1;
  28695. var hasRings = options.hasRings ? true : false;
  28696. var enclose = options.enclose ? true : false;
  28697. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28698. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28699. var faceUV = options.faceUV || new Array(3);
  28700. var faceColors = options.faceColors;
  28701. // default face colors and UV if undefined
  28702. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28703. var ringNb = (hasRings) ? subdivisions : 1;
  28704. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28705. var f;
  28706. for (f = 0; f < surfaceNb; f++) {
  28707. if (faceColors && faceColors[f] === undefined) {
  28708. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28709. }
  28710. }
  28711. for (f = 0; f < surfaceNb; f++) {
  28712. if (faceUV && faceUV[f] === undefined) {
  28713. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28714. }
  28715. }
  28716. var indices = new Array();
  28717. var positions = new Array();
  28718. var normals = new Array();
  28719. var uvs = new Array();
  28720. var colors = new Array();
  28721. var angle_step = Math.PI * 2 * arc / tessellation;
  28722. var angle;
  28723. var h;
  28724. var radius;
  28725. var tan = (diameterBottom - diameterTop) / 2 / height;
  28726. var ringVertex = BABYLON.Vector3.Zero();
  28727. var ringNormal = BABYLON.Vector3.Zero();
  28728. var ringFirstVertex = BABYLON.Vector3.Zero();
  28729. var ringFirstNormal = BABYLON.Vector3.Zero();
  28730. var quadNormal = BABYLON.Vector3.Zero();
  28731. var Y = BABYLON.Axis.Y;
  28732. // positions, normals, uvs
  28733. var i;
  28734. var j;
  28735. var r;
  28736. var ringIdx = 1;
  28737. var s = 1; // surface index
  28738. var cs = 0;
  28739. var v = 0;
  28740. for (i = 0; i <= subdivisions; i++) {
  28741. h = i / subdivisions;
  28742. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28743. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28744. for (r = 0; r < ringIdx; r++) {
  28745. if (hasRings) {
  28746. s += r;
  28747. }
  28748. if (enclose) {
  28749. s += 2 * r;
  28750. }
  28751. for (j = 0; j <= tessellation; j++) {
  28752. angle = j * angle_step;
  28753. // position
  28754. ringVertex.x = Math.cos(-angle) * radius;
  28755. ringVertex.y = -height / 2 + h * height;
  28756. ringVertex.z = Math.sin(-angle) * radius;
  28757. // normal
  28758. if (diameterTop === 0 && i === subdivisions) {
  28759. // if no top cap, reuse former normals
  28760. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28761. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28762. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28763. }
  28764. else {
  28765. ringNormal.x = ringVertex.x;
  28766. ringNormal.z = ringVertex.z;
  28767. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28768. ringNormal.normalize();
  28769. }
  28770. // keep first ring vertex values for enclose
  28771. if (j === 0) {
  28772. ringFirstVertex.copyFrom(ringVertex);
  28773. ringFirstNormal.copyFrom(ringNormal);
  28774. }
  28775. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28776. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28777. if (hasRings) {
  28778. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28779. }
  28780. else {
  28781. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28782. }
  28783. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28784. if (faceColors) {
  28785. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28786. }
  28787. }
  28788. // if enclose, add four vertices and their dedicated normals
  28789. if (arc !== 1 && enclose) {
  28790. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28791. positions.push(0, ringVertex.y, 0);
  28792. positions.push(0, ringVertex.y, 0);
  28793. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28794. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28795. quadNormal.normalize();
  28796. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28797. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28798. quadNormal.normalize();
  28799. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28800. if (hasRings) {
  28801. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28802. }
  28803. else {
  28804. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28805. }
  28806. uvs.push(faceUV[s + 1].x, v);
  28807. uvs.push(faceUV[s + 1].z, v);
  28808. if (hasRings) {
  28809. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28810. }
  28811. else {
  28812. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28813. }
  28814. uvs.push(faceUV[s + 2].x, v);
  28815. uvs.push(faceUV[s + 2].z, v);
  28816. if (faceColors) {
  28817. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28818. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28819. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28820. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28821. }
  28822. }
  28823. if (cs !== s) {
  28824. cs = s;
  28825. }
  28826. }
  28827. }
  28828. // indices
  28829. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28830. var s;
  28831. i = 0;
  28832. for (s = 0; s < subdivisions; s++) {
  28833. var i0 = 0;
  28834. var i1 = 0;
  28835. var i2 = 0;
  28836. var i3 = 0;
  28837. for (j = 0; j < tessellation; j++) {
  28838. i0 = i * (e + 1) + j;
  28839. i1 = (i + 1) * (e + 1) + j;
  28840. i2 = i * (e + 1) + (j + 1);
  28841. i3 = (i + 1) * (e + 1) + (j + 1);
  28842. indices.push(i0, i1, i2);
  28843. indices.push(i3, i2, i1);
  28844. }
  28845. if (arc !== 1 && enclose) {
  28846. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28847. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28848. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28849. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28850. }
  28851. i = (hasRings) ? (i + 2) : (i + 1);
  28852. }
  28853. // Caps
  28854. var createCylinderCap = function (isTop) {
  28855. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28856. if (radius === 0) {
  28857. return;
  28858. }
  28859. // Cap positions, normals & uvs
  28860. var angle;
  28861. var circleVector;
  28862. var i;
  28863. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28864. var c = null;
  28865. if (faceColors) {
  28866. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28867. }
  28868. // cap center
  28869. var vbase = positions.length / 3;
  28870. var offset = isTop ? height / 2 : -height / 2;
  28871. var center = new BABYLON.Vector3(0, offset, 0);
  28872. positions.push(center.x, center.y, center.z);
  28873. normals.push(0, isTop ? 1 : -1, 0);
  28874. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28875. if (c) {
  28876. colors.push(c.r, c.g, c.b, c.a);
  28877. }
  28878. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28879. for (i = 0; i <= tessellation; i++) {
  28880. angle = Math.PI * 2 * i * arc / tessellation;
  28881. var cos = Math.cos(-angle);
  28882. var sin = Math.sin(-angle);
  28883. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28884. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28885. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28886. normals.push(0, isTop ? 1 : -1, 0);
  28887. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28888. if (c) {
  28889. colors.push(c.r, c.g, c.b, c.a);
  28890. }
  28891. }
  28892. // Cap indices
  28893. for (i = 0; i < tessellation; i++) {
  28894. if (!isTop) {
  28895. indices.push(vbase);
  28896. indices.push(vbase + (i + 1));
  28897. indices.push(vbase + (i + 2));
  28898. }
  28899. else {
  28900. indices.push(vbase);
  28901. indices.push(vbase + (i + 2));
  28902. indices.push(vbase + (i + 1));
  28903. }
  28904. }
  28905. };
  28906. // add caps to geometry
  28907. createCylinderCap(false);
  28908. createCylinderCap(true);
  28909. // Sides
  28910. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28911. var vertexData = new VertexData();
  28912. vertexData.indices = indices;
  28913. vertexData.positions = positions;
  28914. vertexData.normals = normals;
  28915. vertexData.uvs = uvs;
  28916. if (faceColors) {
  28917. vertexData.colors = colors;
  28918. }
  28919. return vertexData;
  28920. };
  28921. /**
  28922. * Creates the VertexData of the Torus.
  28923. */
  28924. VertexData.CreateTorus = function (options) {
  28925. var indices = [];
  28926. var positions = [];
  28927. var normals = [];
  28928. var uvs = [];
  28929. var diameter = options.diameter || 1;
  28930. var thickness = options.thickness || 0.5;
  28931. var tessellation = options.tessellation || 16;
  28932. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28933. var stride = tessellation + 1;
  28934. for (var i = 0; i <= tessellation; i++) {
  28935. var u = i / tessellation;
  28936. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28937. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28938. for (var j = 0; j <= tessellation; j++) {
  28939. var v = 1 - j / tessellation;
  28940. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28941. var dx = Math.cos(innerAngle);
  28942. var dy = Math.sin(innerAngle);
  28943. // Create a vertex.
  28944. var normal = new BABYLON.Vector3(dx, dy, 0);
  28945. var position = normal.scale(thickness / 2);
  28946. var textureCoordinate = new BABYLON.Vector2(u, v);
  28947. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28948. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28949. positions.push(position.x, position.y, position.z);
  28950. normals.push(normal.x, normal.y, normal.z);
  28951. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28952. // And create indices for two triangles.
  28953. var nextI = (i + 1) % stride;
  28954. var nextJ = (j + 1) % stride;
  28955. indices.push(i * stride + j);
  28956. indices.push(i * stride + nextJ);
  28957. indices.push(nextI * stride + j);
  28958. indices.push(i * stride + nextJ);
  28959. indices.push(nextI * stride + nextJ);
  28960. indices.push(nextI * stride + j);
  28961. }
  28962. }
  28963. // Sides
  28964. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28965. // Result
  28966. var vertexData = new VertexData();
  28967. vertexData.indices = indices;
  28968. vertexData.positions = positions;
  28969. vertexData.normals = normals;
  28970. vertexData.uvs = uvs;
  28971. return vertexData;
  28972. };
  28973. /**
  28974. * Creates the VertexData of the LineSystem.
  28975. */
  28976. VertexData.CreateLineSystem = function (options) {
  28977. var indices = [];
  28978. var positions = [];
  28979. var lines = options.lines;
  28980. var idx = 0;
  28981. for (var l = 0; l < lines.length; l++) {
  28982. var points = lines[l];
  28983. for (var index = 0; index < points.length; index++) {
  28984. positions.push(points[index].x, points[index].y, points[index].z);
  28985. if (index > 0) {
  28986. indices.push(idx - 1);
  28987. indices.push(idx);
  28988. }
  28989. idx++;
  28990. }
  28991. }
  28992. var vertexData = new VertexData();
  28993. vertexData.indices = indices;
  28994. vertexData.positions = positions;
  28995. return vertexData;
  28996. };
  28997. /**
  28998. * Create the VertexData of the DashedLines.
  28999. */
  29000. VertexData.CreateDashedLines = function (options) {
  29001. var dashSize = options.dashSize || 3;
  29002. var gapSize = options.gapSize || 1;
  29003. var dashNb = options.dashNb || 200;
  29004. var points = options.points;
  29005. var positions = new Array();
  29006. var indices = new Array();
  29007. var curvect = BABYLON.Vector3.Zero();
  29008. var lg = 0;
  29009. var nb = 0;
  29010. var shft = 0;
  29011. var dashshft = 0;
  29012. var curshft = 0;
  29013. var idx = 0;
  29014. var i = 0;
  29015. for (i = 0; i < points.length - 1; i++) {
  29016. points[i + 1].subtractToRef(points[i], curvect);
  29017. lg += curvect.length();
  29018. }
  29019. shft = lg / dashNb;
  29020. dashshft = dashSize * shft / (dashSize + gapSize);
  29021. for (i = 0; i < points.length - 1; i++) {
  29022. points[i + 1].subtractToRef(points[i], curvect);
  29023. nb = Math.floor(curvect.length() / shft);
  29024. curvect.normalize();
  29025. for (var j = 0; j < nb; j++) {
  29026. curshft = shft * j;
  29027. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29028. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29029. indices.push(idx, idx + 1);
  29030. idx += 2;
  29031. }
  29032. }
  29033. // Result
  29034. var vertexData = new VertexData();
  29035. vertexData.positions = positions;
  29036. vertexData.indices = indices;
  29037. return vertexData;
  29038. };
  29039. /**
  29040. * Creates the VertexData of the Ground.
  29041. */
  29042. VertexData.CreateGround = function (options) {
  29043. var indices = [];
  29044. var positions = [];
  29045. var normals = [];
  29046. var uvs = [];
  29047. var row, col;
  29048. var width = options.width || 1;
  29049. var height = options.height || 1;
  29050. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29051. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29052. for (row = 0; row <= subdivisionsY; row++) {
  29053. for (col = 0; col <= subdivisionsX; col++) {
  29054. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29055. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29056. positions.push(position.x, position.y, position.z);
  29057. normals.push(normal.x, normal.y, normal.z);
  29058. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29059. }
  29060. }
  29061. for (row = 0; row < subdivisionsY; row++) {
  29062. for (col = 0; col < subdivisionsX; col++) {
  29063. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29064. indices.push(col + 1 + row * (subdivisionsX + 1));
  29065. indices.push(col + row * (subdivisionsX + 1));
  29066. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29067. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29068. indices.push(col + row * (subdivisionsX + 1));
  29069. }
  29070. }
  29071. // Result
  29072. var vertexData = new VertexData();
  29073. vertexData.indices = indices;
  29074. vertexData.positions = positions;
  29075. vertexData.normals = normals;
  29076. vertexData.uvs = uvs;
  29077. return vertexData;
  29078. };
  29079. /**
  29080. * Creates the VertexData of the TiledGround.
  29081. */
  29082. VertexData.CreateTiledGround = function (options) {
  29083. var xmin = options.xmin || -1.0;
  29084. var zmin = options.zmin || -1.0;
  29085. var xmax = options.xmax || 1.0;
  29086. var zmax = options.zmax || 1.0;
  29087. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29088. var precision = options.precision || { w: 1, h: 1 };
  29089. var indices = new Array();
  29090. var positions = new Array();
  29091. var normals = new Array();
  29092. var uvs = new Array();
  29093. var row, col, tileRow, tileCol;
  29094. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29095. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29096. precision.w = (precision.w < 1) ? 1 : precision.w;
  29097. precision.h = (precision.h < 1) ? 1 : precision.h;
  29098. var tileSize = {
  29099. 'w': (xmax - xmin) / subdivisions.w,
  29100. 'h': (zmax - zmin) / subdivisions.h
  29101. };
  29102. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29103. // Indices
  29104. var base = positions.length / 3;
  29105. var rowLength = precision.w + 1;
  29106. for (row = 0; row < precision.h; row++) {
  29107. for (col = 0; col < precision.w; col++) {
  29108. var square = [
  29109. base + col + row * rowLength,
  29110. base + (col + 1) + row * rowLength,
  29111. base + (col + 1) + (row + 1) * rowLength,
  29112. base + col + (row + 1) * rowLength
  29113. ];
  29114. indices.push(square[1]);
  29115. indices.push(square[2]);
  29116. indices.push(square[3]);
  29117. indices.push(square[0]);
  29118. indices.push(square[1]);
  29119. indices.push(square[3]);
  29120. }
  29121. }
  29122. // Position, normals and uvs
  29123. var position = BABYLON.Vector3.Zero();
  29124. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29125. for (row = 0; row <= precision.h; row++) {
  29126. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29127. for (col = 0; col <= precision.w; col++) {
  29128. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29129. position.y = 0;
  29130. positions.push(position.x, position.y, position.z);
  29131. normals.push(normal.x, normal.y, normal.z);
  29132. uvs.push(col / precision.w, row / precision.h);
  29133. }
  29134. }
  29135. }
  29136. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29137. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29138. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29139. }
  29140. }
  29141. // Result
  29142. var vertexData = new VertexData();
  29143. vertexData.indices = indices;
  29144. vertexData.positions = positions;
  29145. vertexData.normals = normals;
  29146. vertexData.uvs = uvs;
  29147. return vertexData;
  29148. };
  29149. /**
  29150. * Creates the VertexData of the Ground designed from a heightmap.
  29151. */
  29152. VertexData.CreateGroundFromHeightMap = function (options) {
  29153. var indices = [];
  29154. var positions = [];
  29155. var normals = [];
  29156. var uvs = [];
  29157. var row, col;
  29158. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29159. // Vertices
  29160. for (row = 0; row <= options.subdivisions; row++) {
  29161. for (col = 0; col <= options.subdivisions; col++) {
  29162. 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));
  29163. // Compute height
  29164. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29165. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29166. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29167. var r = options.buffer[pos] / 255.0;
  29168. var g = options.buffer[pos + 1] / 255.0;
  29169. var b = options.buffer[pos + 2] / 255.0;
  29170. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29171. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29172. // Add vertex
  29173. positions.push(position.x, position.y, position.z);
  29174. normals.push(0, 0, 0);
  29175. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29176. }
  29177. }
  29178. // Indices
  29179. for (row = 0; row < options.subdivisions; row++) {
  29180. for (col = 0; col < options.subdivisions; col++) {
  29181. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29182. indices.push(col + 1 + row * (options.subdivisions + 1));
  29183. indices.push(col + row * (options.subdivisions + 1));
  29184. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29185. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29186. indices.push(col + row * (options.subdivisions + 1));
  29187. }
  29188. }
  29189. // Normals
  29190. VertexData.ComputeNormals(positions, indices, normals);
  29191. // Result
  29192. var vertexData = new VertexData();
  29193. vertexData.indices = indices;
  29194. vertexData.positions = positions;
  29195. vertexData.normals = normals;
  29196. vertexData.uvs = uvs;
  29197. return vertexData;
  29198. };
  29199. /**
  29200. * Creates the VertexData of the Plane.
  29201. */
  29202. VertexData.CreatePlane = function (options) {
  29203. var indices = [];
  29204. var positions = [];
  29205. var normals = [];
  29206. var uvs = [];
  29207. var width = options.width || options.size || 1;
  29208. var height = options.height || options.size || 1;
  29209. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29210. // Vertices
  29211. var halfWidth = width / 2.0;
  29212. var halfHeight = height / 2.0;
  29213. positions.push(-halfWidth, -halfHeight, 0);
  29214. normals.push(0, 0, -1.0);
  29215. uvs.push(0.0, 0.0);
  29216. positions.push(halfWidth, -halfHeight, 0);
  29217. normals.push(0, 0, -1.0);
  29218. uvs.push(1.0, 0.0);
  29219. positions.push(halfWidth, halfHeight, 0);
  29220. normals.push(0, 0, -1.0);
  29221. uvs.push(1.0, 1.0);
  29222. positions.push(-halfWidth, halfHeight, 0);
  29223. normals.push(0, 0, -1.0);
  29224. uvs.push(0.0, 1.0);
  29225. // Indices
  29226. indices.push(0);
  29227. indices.push(1);
  29228. indices.push(2);
  29229. indices.push(0);
  29230. indices.push(2);
  29231. indices.push(3);
  29232. // Sides
  29233. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29234. // Result
  29235. var vertexData = new VertexData();
  29236. vertexData.indices = indices;
  29237. vertexData.positions = positions;
  29238. vertexData.normals = normals;
  29239. vertexData.uvs = uvs;
  29240. return vertexData;
  29241. };
  29242. /**
  29243. * Creates the VertexData of the Disc or regular Polygon.
  29244. */
  29245. VertexData.CreateDisc = function (options) {
  29246. var positions = new Array();
  29247. var indices = new Array();
  29248. var normals = new Array();
  29249. var uvs = new Array();
  29250. var radius = options.radius || 0.5;
  29251. var tessellation = options.tessellation || 64;
  29252. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29253. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29254. // positions and uvs
  29255. positions.push(0, 0, 0); // disc center first
  29256. uvs.push(0.5, 0.5);
  29257. var theta = Math.PI * 2 * arc;
  29258. var step = theta / tessellation;
  29259. for (var a = 0; a < theta; a += step) {
  29260. var x = Math.cos(a);
  29261. var y = Math.sin(a);
  29262. var u = (x + 1) / 2;
  29263. var v = (1 - y) / 2;
  29264. positions.push(radius * x, radius * y, 0);
  29265. uvs.push(u, v);
  29266. }
  29267. if (arc === 1) {
  29268. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29269. uvs.push(uvs[2], uvs[3]);
  29270. }
  29271. //indices
  29272. var vertexNb = positions.length / 3;
  29273. for (var i = 1; i < vertexNb - 1; i++) {
  29274. indices.push(i + 1, 0, i);
  29275. }
  29276. // result
  29277. VertexData.ComputeNormals(positions, indices, normals);
  29278. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29279. var vertexData = new VertexData();
  29280. vertexData.indices = indices;
  29281. vertexData.positions = positions;
  29282. vertexData.normals = normals;
  29283. vertexData.uvs = uvs;
  29284. return vertexData;
  29285. };
  29286. /**
  29287. * Re-creates the VertexData of the Polygon for sideOrientation.
  29288. */
  29289. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29290. var faceUV = fUV || new Array(3);
  29291. var faceColors = fColors;
  29292. var colors = [];
  29293. // default face colors and UV if undefined
  29294. for (var f = 0; f < 3; f++) {
  29295. if (faceUV[f] === undefined) {
  29296. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29297. }
  29298. if (faceColors && faceColors[f] === undefined) {
  29299. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29300. }
  29301. }
  29302. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29303. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29304. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29305. var indices = polygon.getIndices();
  29306. // set face colours and textures
  29307. var idx = 0;
  29308. var face = 0;
  29309. for (var index = 0; index < normals.length; index += 3) {
  29310. //Edge Face no. 1
  29311. if (Math.abs(normals[index + 1]) < 0.001) {
  29312. face = 1;
  29313. }
  29314. //Top Face no. 0
  29315. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29316. face = 0;
  29317. }
  29318. //Bottom Face no. 2
  29319. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29320. face = 2;
  29321. }
  29322. idx = index / 3;
  29323. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29324. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29325. if (faceColors) {
  29326. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29327. }
  29328. }
  29329. // sides
  29330. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29331. // Result
  29332. var vertexData = new VertexData();
  29333. vertexData.indices = indices;
  29334. vertexData.positions = positions;
  29335. vertexData.normals = normals;
  29336. vertexData.uvs = uvs;
  29337. if (faceColors) {
  29338. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29339. vertexData.colors = totalColors;
  29340. }
  29341. return vertexData;
  29342. };
  29343. /**
  29344. * Creates the VertexData of the IcoSphere.
  29345. */
  29346. VertexData.CreateIcoSphere = function (options) {
  29347. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29348. var radius = options.radius || 1;
  29349. var flat = (options.flat === undefined) ? true : options.flat;
  29350. var subdivisions = options.subdivisions || 4;
  29351. var radiusX = options.radiusX || radius;
  29352. var radiusY = options.radiusY || radius;
  29353. var radiusZ = options.radiusZ || radius;
  29354. var t = (1 + Math.sqrt(5)) / 2;
  29355. // 12 vertex x,y,z
  29356. var ico_vertices = [
  29357. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29358. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29359. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29360. ];
  29361. // index of 3 vertex makes a face of icopshere
  29362. var ico_indices = [
  29363. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29364. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29365. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29366. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29367. ];
  29368. // vertex for uv have aliased position, not for UV
  29369. var vertices_unalias_id = [
  29370. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29371. // vertex alias
  29372. 0,
  29373. 2,
  29374. 3,
  29375. 3,
  29376. 3,
  29377. 4,
  29378. 7,
  29379. 8,
  29380. 9,
  29381. 9,
  29382. 10,
  29383. 11 // 23: B + 12
  29384. ];
  29385. // uv as integer step (not pixels !)
  29386. var ico_vertexuv = [
  29387. 5, 1, 3, 1, 6, 4, 0, 0,
  29388. 5, 3, 4, 2, 2, 2, 4, 0,
  29389. 2, 0, 1, 1, 6, 0, 6, 2,
  29390. // vertex alias (for same vertex on different faces)
  29391. 0, 4,
  29392. 3, 3,
  29393. 4, 4,
  29394. 3, 1,
  29395. 4, 2,
  29396. 4, 4,
  29397. 0, 2,
  29398. 1, 1,
  29399. 2, 2,
  29400. 3, 3,
  29401. 1, 3,
  29402. 2, 4 // 23: B + 12
  29403. ];
  29404. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29405. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29406. // First island of uv mapping
  29407. // v = 4h 3+ 2
  29408. // v = 3h 9+ 4
  29409. // v = 2h 9+ 5 B
  29410. // v = 1h 9 1 0
  29411. // v = 0h 3 8 7 A
  29412. // u = 0 1 2 3 4 5 6 *a
  29413. // Second island of uv mapping
  29414. // v = 4h 0+ B+ 4+
  29415. // v = 3h A+ 2+
  29416. // v = 2h 7+ 6 3+
  29417. // v = 1h 8+ 3+
  29418. // v = 0h
  29419. // u = 0 1 2 3 4 5 6 *a
  29420. // Face layout on texture UV mapping
  29421. // ============
  29422. // \ 4 /\ 16 / ======
  29423. // \ / \ / /\ 11 /
  29424. // \/ 7 \/ / \ /
  29425. // ======= / 10 \/
  29426. // /\ 17 /\ =======
  29427. // / \ / \ \ 15 /\
  29428. // / 8 \/ 12 \ \ / \
  29429. // ============ \/ 6 \
  29430. // \ 18 /\ ============
  29431. // \ / \ \ 5 /\ 0 /
  29432. // \/ 13 \ \ / \ /
  29433. // ======= \/ 1 \/
  29434. // =============
  29435. // /\ 19 /\ 2 /\
  29436. // / \ / \ / \
  29437. // / 14 \/ 9 \/ 3 \
  29438. // ===================
  29439. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29440. var ustep = 138 / 1024;
  29441. var vstep = 239 / 1024;
  29442. var uoffset = 60 / 1024;
  29443. var voffset = 26 / 1024;
  29444. // Second island should have margin, not to touch the first island
  29445. // avoid any borderline artefact in pixel rounding
  29446. var island_u_offset = -40 / 1024;
  29447. var island_v_offset = +20 / 1024;
  29448. // face is either island 0 or 1 :
  29449. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29450. var island = [
  29451. 0, 0, 0, 0, 1,
  29452. 0, 0, 1, 1, 0,
  29453. 0, 0, 1, 1, 0,
  29454. 0, 1, 1, 1, 0 // 15 - 19
  29455. ];
  29456. var indices = new Array();
  29457. var positions = new Array();
  29458. var normals = new Array();
  29459. var uvs = new Array();
  29460. var current_indice = 0;
  29461. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29462. var face_vertex_pos = new Array(3);
  29463. var face_vertex_uv = new Array(3);
  29464. var v012;
  29465. for (v012 = 0; v012 < 3; v012++) {
  29466. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29467. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29468. }
  29469. // create all with normals
  29470. for (var face = 0; face < 20; face++) {
  29471. // 3 vertex per face
  29472. for (v012 = 0; v012 < 3; v012++) {
  29473. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29474. var v_id = ico_indices[3 * face + v012];
  29475. // vertex have 3D position (x,y,z)
  29476. 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]);
  29477. // Normalize to get normal, then scale to radius
  29478. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29479. // uv Coordinates from vertex ID
  29480. 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);
  29481. }
  29482. // Subdivide the face (interpolate pos, norm, uv)
  29483. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29484. // - norm is linear interpolation of vertex corner normal
  29485. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29486. // - uv is linear interpolation
  29487. //
  29488. // Topology is as below for sub-divide by 2
  29489. // vertex shown as v0,v1,v2
  29490. // interp index is i1 to progress in range [v0,v1[
  29491. // interp index is i2 to progress in range [v0,v2[
  29492. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29493. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29494. //
  29495. //
  29496. // i2 v2
  29497. // ^ ^
  29498. // / / \
  29499. // / / \
  29500. // / / \
  29501. // / / (0,1) \
  29502. // / #---------\
  29503. // / / \ (0,0)'/ \
  29504. // / / \ / \
  29505. // / / \ / \
  29506. // / / (0,0) \ / (1,0) \
  29507. // / #---------#---------\
  29508. // v0 v1
  29509. //
  29510. // --------------------> i1
  29511. //
  29512. // interp of (i1,i2):
  29513. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29514. // along i1 : lerp(x0,x1, i1/(S-i2))
  29515. //
  29516. // centroid of triangle is needed to get help normal computation
  29517. // (c1,c2) are used for centroid location
  29518. var interp_vertex = function (i1, i2, c1, c2) {
  29519. // vertex is interpolated from
  29520. // - face_vertex_pos[0..2]
  29521. // - face_vertex_uv[0..2]
  29522. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29523. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29524. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29525. pos_interp.normalize();
  29526. var vertex_normal;
  29527. if (flat) {
  29528. // in flat mode, recalculate normal as face centroid normal
  29529. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29530. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29531. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29532. }
  29533. else {
  29534. // in smooth mode, recalculate normal from each single vertex position
  29535. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29536. }
  29537. // Vertex normal need correction due to X,Y,Z radius scaling
  29538. vertex_normal.x /= radiusX;
  29539. vertex_normal.y /= radiusY;
  29540. vertex_normal.z /= radiusZ;
  29541. vertex_normal.normalize();
  29542. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29543. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29544. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29545. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29546. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29547. uvs.push(uv_interp.x, uv_interp.y);
  29548. // push each vertex has member of a face
  29549. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29550. indices.push(current_indice);
  29551. current_indice++;
  29552. };
  29553. for (var i2 = 0; i2 < subdivisions; i2++) {
  29554. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29555. // face : (i1,i2) for /\ :
  29556. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29557. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29558. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29559. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29560. if (i1 + i2 + 1 < subdivisions) {
  29561. // face : (i1,i2)' for \/ :
  29562. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29563. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29564. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29565. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29566. }
  29567. }
  29568. }
  29569. }
  29570. // Sides
  29571. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29572. // Result
  29573. var vertexData = new VertexData();
  29574. vertexData.indices = indices;
  29575. vertexData.positions = positions;
  29576. vertexData.normals = normals;
  29577. vertexData.uvs = uvs;
  29578. return vertexData;
  29579. };
  29580. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29581. /**
  29582. * Creates the VertexData of the Polyhedron.
  29583. */
  29584. VertexData.CreatePolyhedron = function (options) {
  29585. // provided polyhedron types :
  29586. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29587. // 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)
  29588. var polyhedra = [];
  29589. 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]] };
  29590. 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]] };
  29591. polyhedra[2] = {
  29592. 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]],
  29593. 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]]
  29594. };
  29595. polyhedra[3] = {
  29596. 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]],
  29597. 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]]
  29598. };
  29599. polyhedra[4] = {
  29600. 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]],
  29601. 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]]
  29602. };
  29603. 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]] };
  29604. 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]] };
  29605. 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]] };
  29606. 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]] };
  29607. 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]] };
  29608. 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]] };
  29609. 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]] };
  29610. 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]] };
  29611. 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]] };
  29612. polyhedra[14] = {
  29613. 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]],
  29614. 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]]
  29615. };
  29616. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29617. var size = options.size;
  29618. var sizeX = options.sizeX || size || 1;
  29619. var sizeY = options.sizeY || size || 1;
  29620. var sizeZ = options.sizeZ || size || 1;
  29621. var data = options.custom || polyhedra[type];
  29622. var nbfaces = data.face.length;
  29623. var faceUV = options.faceUV || new Array(nbfaces);
  29624. var faceColors = options.faceColors;
  29625. var flat = (options.flat === undefined) ? true : options.flat;
  29626. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29627. var positions = new Array();
  29628. var indices = new Array();
  29629. var normals = new Array();
  29630. var uvs = new Array();
  29631. var colors = new Array();
  29632. var index = 0;
  29633. var faceIdx = 0; // face cursor in the array "indexes"
  29634. var indexes = new Array();
  29635. var i = 0;
  29636. var f = 0;
  29637. var u, v, ang, x, y, tmp;
  29638. // default face colors and UV if undefined
  29639. if (flat) {
  29640. for (f = 0; f < nbfaces; f++) {
  29641. if (faceColors && faceColors[f] === undefined) {
  29642. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29643. }
  29644. if (faceUV && faceUV[f] === undefined) {
  29645. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29646. }
  29647. }
  29648. }
  29649. if (!flat) {
  29650. for (i = 0; i < data.vertex.length; i++) {
  29651. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29652. uvs.push(0, 0);
  29653. }
  29654. for (f = 0; f < nbfaces; f++) {
  29655. for (i = 0; i < data.face[f].length - 2; i++) {
  29656. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29657. }
  29658. }
  29659. }
  29660. else {
  29661. for (f = 0; f < nbfaces; f++) {
  29662. var fl = data.face[f].length; // number of vertices of the current face
  29663. ang = 2 * Math.PI / fl;
  29664. x = 0.5 * Math.tan(ang / 2);
  29665. y = 0.5;
  29666. // positions, uvs, colors
  29667. for (i = 0; i < fl; i++) {
  29668. // positions
  29669. 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);
  29670. indexes.push(index);
  29671. index++;
  29672. // uvs
  29673. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29674. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29675. uvs.push(u, v);
  29676. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29677. y = x * Math.sin(ang) + y * Math.cos(ang);
  29678. x = tmp;
  29679. // colors
  29680. if (faceColors) {
  29681. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29682. }
  29683. }
  29684. // indices from indexes
  29685. for (i = 0; i < fl - 2; i++) {
  29686. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29687. }
  29688. faceIdx += fl;
  29689. }
  29690. }
  29691. VertexData.ComputeNormals(positions, indices, normals);
  29692. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29693. var vertexData = new VertexData();
  29694. vertexData.positions = positions;
  29695. vertexData.indices = indices;
  29696. vertexData.normals = normals;
  29697. vertexData.uvs = uvs;
  29698. if (faceColors && flat) {
  29699. vertexData.colors = colors;
  29700. }
  29701. return vertexData;
  29702. };
  29703. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29704. /**
  29705. * Creates the VertexData of the Torus Knot.
  29706. */
  29707. VertexData.CreateTorusKnot = function (options) {
  29708. var indices = new Array();
  29709. var positions = new Array();
  29710. var normals = new Array();
  29711. var uvs = new Array();
  29712. var radius = options.radius || 2;
  29713. var tube = options.tube || 0.5;
  29714. var radialSegments = options.radialSegments || 32;
  29715. var tubularSegments = options.tubularSegments || 32;
  29716. var p = options.p || 2;
  29717. var q = options.q || 3;
  29718. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29719. // Helper
  29720. var getPos = function (angle) {
  29721. var cu = Math.cos(angle);
  29722. var su = Math.sin(angle);
  29723. var quOverP = q / p * angle;
  29724. var cs = Math.cos(quOverP);
  29725. var tx = radius * (2 + cs) * 0.5 * cu;
  29726. var ty = radius * (2 + cs) * su * 0.5;
  29727. var tz = radius * Math.sin(quOverP) * 0.5;
  29728. return new BABYLON.Vector3(tx, ty, tz);
  29729. };
  29730. // Vertices
  29731. var i;
  29732. var j;
  29733. for (i = 0; i <= radialSegments; i++) {
  29734. var modI = i % radialSegments;
  29735. var u = modI / radialSegments * 2 * p * Math.PI;
  29736. var p1 = getPos(u);
  29737. var p2 = getPos(u + 0.01);
  29738. var tang = p2.subtract(p1);
  29739. var n = p2.add(p1);
  29740. var bitan = BABYLON.Vector3.Cross(tang, n);
  29741. n = BABYLON.Vector3.Cross(bitan, tang);
  29742. bitan.normalize();
  29743. n.normalize();
  29744. for (j = 0; j < tubularSegments; j++) {
  29745. var modJ = j % tubularSegments;
  29746. var v = modJ / tubularSegments * 2 * Math.PI;
  29747. var cx = -tube * Math.cos(v);
  29748. var cy = tube * Math.sin(v);
  29749. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29750. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29751. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29752. uvs.push(i / radialSegments);
  29753. uvs.push(j / tubularSegments);
  29754. }
  29755. }
  29756. for (i = 0; i < radialSegments; i++) {
  29757. for (j = 0; j < tubularSegments; j++) {
  29758. var jNext = (j + 1) % tubularSegments;
  29759. var a = i * tubularSegments + j;
  29760. var b = (i + 1) * tubularSegments + j;
  29761. var c = (i + 1) * tubularSegments + jNext;
  29762. var d = i * tubularSegments + jNext;
  29763. indices.push(d);
  29764. indices.push(b);
  29765. indices.push(a);
  29766. indices.push(d);
  29767. indices.push(c);
  29768. indices.push(b);
  29769. }
  29770. }
  29771. // Normals
  29772. VertexData.ComputeNormals(positions, indices, normals);
  29773. // Sides
  29774. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29775. // Result
  29776. var vertexData = new VertexData();
  29777. vertexData.indices = indices;
  29778. vertexData.positions = positions;
  29779. vertexData.normals = normals;
  29780. vertexData.uvs = uvs;
  29781. return vertexData;
  29782. };
  29783. // Tools
  29784. /**
  29785. * @param {any} - positions (number[] or Float32Array)
  29786. * @param {any} - indices (number[] or Uint16Array)
  29787. * @param {any} - normals (number[] or Float32Array)
  29788. * options (optional) :
  29789. * facetPositions : optional array of facet positions (vector3)
  29790. * facetNormals : optional array of facet normals (vector3)
  29791. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  29792. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  29793. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  29794. * bbSize : optional bounding box size data, required for facetPartitioning computation
  29795. * bInfo : optional bounding info, required for facetPartitioning computation
  29796. */
  29797. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  29798. // temporary scalar variables
  29799. var index = 0; // facet index
  29800. var p1p2x = 0.0; // p1p2 vector x coordinate
  29801. var p1p2y = 0.0; // p1p2 vector y coordinate
  29802. var p1p2z = 0.0; // p1p2 vector z coordinate
  29803. var p3p2x = 0.0; // p3p2 vector x coordinate
  29804. var p3p2y = 0.0; // p3p2 vector y coordinate
  29805. var p3p2z = 0.0; // p3p2 vector z coordinate
  29806. var faceNormalx = 0.0; // facet normal x coordinate
  29807. var faceNormaly = 0.0; // facet normal y coordinate
  29808. var faceNormalz = 0.0; // facet normal z coordinate
  29809. var length = 0.0; // facet normal length before normalization
  29810. var v1x = 0; // vector1 x index in the positions array
  29811. var v1y = 0; // vector1 y index in the positions array
  29812. var v1z = 0; // vector1 z index in the positions array
  29813. var v2x = 0; // vector2 x index in the positions array
  29814. var v2y = 0; // vector2 y index in the positions array
  29815. var v2z = 0; // vector2 z index in the positions array
  29816. var v3x = 0; // vector3 x index in the positions array
  29817. var v3y = 0; // vector3 y index in the positions array
  29818. var v3z = 0; // vector3 z index in the positions array
  29819. var computeFacetNormals = false;
  29820. var computeFacetPositions = false;
  29821. var computeFacetPartitioning = false;
  29822. var faceNormalSign = 1;
  29823. var ratio = 0;
  29824. if (options) {
  29825. computeFacetNormals = (options.facetNormals) ? true : false;
  29826. computeFacetPositions = (options.facetPositions) ? true : false;
  29827. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  29828. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  29829. ratio = options.ratio || 0;
  29830. }
  29831. // facetPartitioning reinit if needed
  29832. var xSubRatio = 0;
  29833. var ySubRatio = 0;
  29834. var zSubRatio = 0;
  29835. var subSq = 0;
  29836. if (computeFacetPartitioning && options && options.bbSize) {
  29837. var ox = 0; // X partitioning index for facet position
  29838. var oy = 0; // Y partinioning index for facet position
  29839. var oz = 0; // Z partinioning index for facet position
  29840. var b1x = 0; // X partitioning index for facet v1 vertex
  29841. var b1y = 0; // Y partitioning index for facet v1 vertex
  29842. var b1z = 0; // z partitioning index for facet v1 vertex
  29843. var b2x = 0; // X partitioning index for facet v2 vertex
  29844. var b2y = 0; // Y partitioning index for facet v2 vertex
  29845. var b2z = 0; // Z partitioning index for facet v2 vertex
  29846. var b3x = 0; // X partitioning index for facet v3 vertex
  29847. var b3y = 0; // Y partitioning index for facet v3 vertex
  29848. var b3z = 0; // Z partitioning index for facet v3 vertex
  29849. var block_idx_o = 0; // facet barycenter block index
  29850. var block_idx_v1 = 0; // v1 vertex block index
  29851. var block_idx_v2 = 0; // v2 vertex block index
  29852. var block_idx_v3 = 0; // v3 vertex block index
  29853. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  29854. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  29855. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  29856. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  29857. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  29858. subSq = options.subDiv.max * options.subDiv.max;
  29859. options.facetPartitioning.length = 0;
  29860. }
  29861. // reset the normals
  29862. for (index = 0; index < positions.length; index++) {
  29863. normals[index] = 0.0;
  29864. }
  29865. // Loop : 1 indice triplet = 1 facet
  29866. var nbFaces = indices.length / 3;
  29867. for (index = 0; index < nbFaces; index++) {
  29868. // get the indexes of the coordinates of each vertex of the facet
  29869. v1x = indices[index * 3] * 3;
  29870. v1y = v1x + 1;
  29871. v1z = v1x + 2;
  29872. v2x = indices[index * 3 + 1] * 3;
  29873. v2y = v2x + 1;
  29874. v2z = v2x + 2;
  29875. v3x = indices[index * 3 + 2] * 3;
  29876. v3y = v3x + 1;
  29877. v3z = v3x + 2;
  29878. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  29879. p1p2y = positions[v1y] - positions[v2y];
  29880. p1p2z = positions[v1z] - positions[v2z];
  29881. p3p2x = positions[v3x] - positions[v2x];
  29882. p3p2y = positions[v3y] - positions[v2y];
  29883. p3p2z = positions[v3z] - positions[v2z];
  29884. // compute the face normal with the cross product
  29885. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  29886. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  29887. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  29888. // normalize this normal and store it in the array facetData
  29889. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29890. length = (length === 0) ? 1.0 : length;
  29891. faceNormalx /= length;
  29892. faceNormaly /= length;
  29893. faceNormalz /= length;
  29894. if (computeFacetNormals && options) {
  29895. options.facetNormals[index].x = faceNormalx;
  29896. options.facetNormals[index].y = faceNormaly;
  29897. options.facetNormals[index].z = faceNormalz;
  29898. }
  29899. if (computeFacetPositions && options) {
  29900. // compute and the facet barycenter coordinates in the array facetPositions
  29901. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  29902. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  29903. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  29904. }
  29905. if (computeFacetPartitioning && options) {
  29906. // store the facet indexes in arrays in the main facetPartitioning array :
  29907. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  29908. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  29909. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  29910. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  29911. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29912. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29913. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29914. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29915. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29916. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29917. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29918. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29919. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29920. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  29921. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  29922. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  29923. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  29924. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  29925. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  29926. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  29927. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  29928. // push each facet index in each block containing the vertex
  29929. options.facetPartitioning[block_idx_v1].push(index);
  29930. if (block_idx_v2 != block_idx_v1) {
  29931. options.facetPartitioning[block_idx_v2].push(index);
  29932. }
  29933. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  29934. options.facetPartitioning[block_idx_v3].push(index);
  29935. }
  29936. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  29937. options.facetPartitioning[block_idx_o].push(index);
  29938. }
  29939. }
  29940. // compute the normals anyway
  29941. normals[v1x] += faceNormalx; // accumulate all the normals per face
  29942. normals[v1y] += faceNormaly;
  29943. normals[v1z] += faceNormalz;
  29944. normals[v2x] += faceNormalx;
  29945. normals[v2y] += faceNormaly;
  29946. normals[v2z] += faceNormalz;
  29947. normals[v3x] += faceNormalx;
  29948. normals[v3y] += faceNormaly;
  29949. normals[v3z] += faceNormalz;
  29950. }
  29951. // last normalization of each normal
  29952. for (index = 0; index < normals.length / 3; index++) {
  29953. faceNormalx = normals[index * 3];
  29954. faceNormaly = normals[index * 3 + 1];
  29955. faceNormalz = normals[index * 3 + 2];
  29956. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29957. length = (length === 0) ? 1.0 : length;
  29958. faceNormalx /= length;
  29959. faceNormaly /= length;
  29960. faceNormalz /= length;
  29961. normals[index * 3] = faceNormalx;
  29962. normals[index * 3 + 1] = faceNormaly;
  29963. normals[index * 3 + 2] = faceNormalz;
  29964. }
  29965. };
  29966. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  29967. var li = indices.length;
  29968. var ln = normals.length;
  29969. var i;
  29970. var n;
  29971. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29972. switch (sideOrientation) {
  29973. case BABYLON.Mesh.FRONTSIDE:
  29974. // nothing changed
  29975. break;
  29976. case BABYLON.Mesh.BACKSIDE:
  29977. var tmp;
  29978. // indices
  29979. for (i = 0; i < li; i += 3) {
  29980. tmp = indices[i];
  29981. indices[i] = indices[i + 2];
  29982. indices[i + 2] = tmp;
  29983. }
  29984. // normals
  29985. for (n = 0; n < ln; n++) {
  29986. normals[n] = -normals[n];
  29987. }
  29988. break;
  29989. case BABYLON.Mesh.DOUBLESIDE:
  29990. // positions
  29991. var lp = positions.length;
  29992. var l = lp / 3;
  29993. for (var p = 0; p < lp; p++) {
  29994. positions[lp + p] = positions[p];
  29995. }
  29996. // indices
  29997. for (i = 0; i < li; i += 3) {
  29998. indices[i + li] = indices[i + 2] + l;
  29999. indices[i + 1 + li] = indices[i + 1] + l;
  30000. indices[i + 2 + li] = indices[i] + l;
  30001. }
  30002. // normals
  30003. for (n = 0; n < ln; n++) {
  30004. normals[ln + n] = -normals[n];
  30005. }
  30006. // uvs
  30007. var lu = uvs.length;
  30008. var u = 0;
  30009. for (u = 0; u < lu; u++) {
  30010. uvs[u + lu] = uvs[u];
  30011. }
  30012. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30013. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30014. u = 0;
  30015. for (i = 0; i < lu / 2; i++) {
  30016. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30017. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30018. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30019. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30020. u += 2;
  30021. }
  30022. break;
  30023. }
  30024. };
  30025. /**
  30026. * Creates a new VertexData from the imported parameters.
  30027. */
  30028. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30029. var vertexData = new VertexData();
  30030. // positions
  30031. var positions = parsedVertexData.positions;
  30032. if (positions) {
  30033. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30034. }
  30035. // normals
  30036. var normals = parsedVertexData.normals;
  30037. if (normals) {
  30038. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30039. }
  30040. // tangents
  30041. var tangents = parsedVertexData.tangents;
  30042. if (tangents) {
  30043. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30044. }
  30045. // uvs
  30046. var uvs = parsedVertexData.uvs;
  30047. if (uvs) {
  30048. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30049. }
  30050. // uv2s
  30051. var uv2s = parsedVertexData.uv2s;
  30052. if (uv2s) {
  30053. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30054. }
  30055. // uv3s
  30056. var uv3s = parsedVertexData.uv3s;
  30057. if (uv3s) {
  30058. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30059. }
  30060. // uv4s
  30061. var uv4s = parsedVertexData.uv4s;
  30062. if (uv4s) {
  30063. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30064. }
  30065. // uv5s
  30066. var uv5s = parsedVertexData.uv5s;
  30067. if (uv5s) {
  30068. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30069. }
  30070. // uv6s
  30071. var uv6s = parsedVertexData.uv6s;
  30072. if (uv6s) {
  30073. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30074. }
  30075. // colors
  30076. var colors = parsedVertexData.colors;
  30077. if (colors) {
  30078. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30079. }
  30080. // matricesIndices
  30081. var matricesIndices = parsedVertexData.matricesIndices;
  30082. if (matricesIndices) {
  30083. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30084. }
  30085. // matricesWeights
  30086. var matricesWeights = parsedVertexData.matricesWeights;
  30087. if (matricesWeights) {
  30088. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30089. }
  30090. // indices
  30091. var indices = parsedVertexData.indices;
  30092. if (indices) {
  30093. vertexData.indices = indices;
  30094. }
  30095. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30096. };
  30097. return VertexData;
  30098. }());
  30099. BABYLON.VertexData = VertexData;
  30100. })(BABYLON || (BABYLON = {}));
  30101. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30102. var BABYLON;
  30103. (function (BABYLON) {
  30104. var Geometry = /** @class */ (function () {
  30105. function Geometry(id, scene, vertexData, updatable, mesh) {
  30106. if (updatable === void 0) { updatable = false; }
  30107. if (mesh === void 0) { mesh = null; }
  30108. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30109. this._totalVertices = 0;
  30110. this._isDisposed = false;
  30111. this._indexBufferIsUpdatable = false;
  30112. this.id = id;
  30113. this._engine = scene.getEngine();
  30114. this._meshes = [];
  30115. this._scene = scene;
  30116. //Init vertex buffer cache
  30117. this._vertexBuffers = {};
  30118. this._indices = [];
  30119. this._updatable = updatable;
  30120. // vertexData
  30121. if (vertexData) {
  30122. this.setAllVerticesData(vertexData, updatable);
  30123. }
  30124. else {
  30125. this._totalVertices = 0;
  30126. this._indices = [];
  30127. }
  30128. if (this._engine.getCaps().vertexArrayObject) {
  30129. this._vertexArrayObjects = {};
  30130. }
  30131. // applyToMesh
  30132. if (mesh) {
  30133. if (mesh.getClassName() === "LinesMesh") {
  30134. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30135. this.updateExtend();
  30136. }
  30137. this.applyToMesh(mesh);
  30138. mesh.computeWorldMatrix(true);
  30139. }
  30140. }
  30141. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30142. /**
  30143. * 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
  30144. * @returns The Bias Vector
  30145. */
  30146. get: function () {
  30147. return this._boundingBias;
  30148. },
  30149. set: function (value) {
  30150. if (this._boundingBias && this._boundingBias.equals(value)) {
  30151. return;
  30152. }
  30153. this._boundingBias = value.clone();
  30154. this.updateBoundingInfo(true, null);
  30155. },
  30156. enumerable: true,
  30157. configurable: true
  30158. });
  30159. Geometry.CreateGeometryForMesh = function (mesh) {
  30160. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30161. geometry.applyToMesh(mesh);
  30162. return geometry;
  30163. };
  30164. Object.defineProperty(Geometry.prototype, "extend", {
  30165. get: function () {
  30166. return this._extend;
  30167. },
  30168. enumerable: true,
  30169. configurable: true
  30170. });
  30171. Geometry.prototype.getScene = function () {
  30172. return this._scene;
  30173. };
  30174. Geometry.prototype.getEngine = function () {
  30175. return this._engine;
  30176. };
  30177. Geometry.prototype.isReady = function () {
  30178. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30179. };
  30180. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30181. get: function () {
  30182. for (var index = 0; index < this._meshes.length; index++) {
  30183. if (!this._meshes[index].doNotSerialize) {
  30184. return false;
  30185. }
  30186. }
  30187. return true;
  30188. },
  30189. enumerable: true,
  30190. configurable: true
  30191. });
  30192. Geometry.prototype._rebuild = function () {
  30193. if (this._vertexArrayObjects) {
  30194. this._vertexArrayObjects = {};
  30195. }
  30196. // Index buffer
  30197. if (this._meshes.length !== 0 && this._indices) {
  30198. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30199. }
  30200. // Vertex buffers
  30201. for (var key in this._vertexBuffers) {
  30202. var vertexBuffer = this._vertexBuffers[key];
  30203. vertexBuffer._rebuild();
  30204. }
  30205. };
  30206. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30207. vertexData.applyToGeometry(this, updatable);
  30208. this.notifyUpdate();
  30209. };
  30210. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30211. if (updatable === void 0) { updatable = false; }
  30212. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30213. this.setVerticesBuffer(buffer);
  30214. };
  30215. Geometry.prototype.removeVerticesData = function (kind) {
  30216. if (this._vertexBuffers[kind]) {
  30217. this._vertexBuffers[kind].dispose();
  30218. delete this._vertexBuffers[kind];
  30219. }
  30220. };
  30221. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30222. var kind = buffer.getKind();
  30223. if (this._vertexBuffers[kind]) {
  30224. this._vertexBuffers[kind].dispose();
  30225. }
  30226. this._vertexBuffers[kind] = buffer;
  30227. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30228. var data = buffer.getData();
  30229. var stride = buffer.getStrideSize();
  30230. this._totalVertices = data.length / stride;
  30231. this.updateExtend(data, stride);
  30232. this._resetPointsArrayCache();
  30233. var meshes = this._meshes;
  30234. var numOfMeshes = meshes.length;
  30235. for (var index = 0; index < numOfMeshes; index++) {
  30236. var mesh = meshes[index];
  30237. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30238. mesh._createGlobalSubMesh(false);
  30239. mesh.computeWorldMatrix(true);
  30240. }
  30241. }
  30242. this.notifyUpdate(kind);
  30243. if (this._vertexArrayObjects) {
  30244. this._disposeVertexArrayObjects();
  30245. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30246. }
  30247. };
  30248. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30249. var vertexBuffer = this.getVertexBuffer(kind);
  30250. if (!vertexBuffer) {
  30251. return;
  30252. }
  30253. vertexBuffer.updateDirectly(data, offset);
  30254. this.notifyUpdate(kind);
  30255. };
  30256. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30257. if (updateExtends === void 0) { updateExtends = false; }
  30258. var vertexBuffer = this.getVertexBuffer(kind);
  30259. if (!vertexBuffer) {
  30260. return;
  30261. }
  30262. vertexBuffer.update(data);
  30263. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30264. var stride = vertexBuffer.getStrideSize();
  30265. this._totalVertices = data.length / stride;
  30266. this.updateBoundingInfo(updateExtends, data);
  30267. }
  30268. this.notifyUpdate(kind);
  30269. };
  30270. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30271. if (updateExtends) {
  30272. this.updateExtend(data);
  30273. }
  30274. var meshes = this._meshes;
  30275. var numOfMeshes = meshes.length;
  30276. this._resetPointsArrayCache();
  30277. for (var index = 0; index < numOfMeshes; index++) {
  30278. var mesh = meshes[index];
  30279. if (updateExtends) {
  30280. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30281. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30282. var subMesh = mesh.subMeshes[subIndex];
  30283. subMesh.refreshBoundingInfo();
  30284. }
  30285. }
  30286. }
  30287. };
  30288. Geometry.prototype._bind = function (effect, indexToBind) {
  30289. if (!effect) {
  30290. return;
  30291. }
  30292. if (indexToBind === undefined) {
  30293. indexToBind = this._indexBuffer;
  30294. }
  30295. var vbs = this.getVertexBuffers();
  30296. if (!vbs) {
  30297. return;
  30298. }
  30299. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30300. this._engine.bindBuffers(vbs, indexToBind, effect);
  30301. return;
  30302. }
  30303. // Using VAO
  30304. if (!this._vertexArrayObjects[effect.key]) {
  30305. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30306. }
  30307. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30308. };
  30309. Geometry.prototype.getTotalVertices = function () {
  30310. if (!this.isReady()) {
  30311. return 0;
  30312. }
  30313. return this._totalVertices;
  30314. };
  30315. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30316. var vertexBuffer = this.getVertexBuffer(kind);
  30317. if (!vertexBuffer) {
  30318. return null;
  30319. }
  30320. var orig = vertexBuffer.getData();
  30321. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30322. return orig;
  30323. }
  30324. else {
  30325. var len = orig.length;
  30326. var copy = [];
  30327. for (var i = 0; i < len; i++) {
  30328. copy.push(orig[i]);
  30329. }
  30330. return copy;
  30331. }
  30332. };
  30333. /**
  30334. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30335. * Possible `kind` values :
  30336. * - BABYLON.VertexBuffer.PositionKind
  30337. * - BABYLON.VertexBuffer.UVKind
  30338. * - BABYLON.VertexBuffer.UV2Kind
  30339. * - BABYLON.VertexBuffer.UV3Kind
  30340. * - BABYLON.VertexBuffer.UV4Kind
  30341. * - BABYLON.VertexBuffer.UV5Kind
  30342. * - BABYLON.VertexBuffer.UV6Kind
  30343. * - BABYLON.VertexBuffer.ColorKind
  30344. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30345. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30346. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30347. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30348. */
  30349. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  30350. var vb = this._vertexBuffers[kind];
  30351. if (!vb) {
  30352. return false;
  30353. }
  30354. return vb.isUpdatable();
  30355. };
  30356. Geometry.prototype.getVertexBuffer = function (kind) {
  30357. if (!this.isReady()) {
  30358. return null;
  30359. }
  30360. return this._vertexBuffers[kind];
  30361. };
  30362. Geometry.prototype.getVertexBuffers = function () {
  30363. if (!this.isReady()) {
  30364. return null;
  30365. }
  30366. return this._vertexBuffers;
  30367. };
  30368. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30369. if (!this._vertexBuffers) {
  30370. if (this._delayInfo) {
  30371. return this._delayInfo.indexOf(kind) !== -1;
  30372. }
  30373. return false;
  30374. }
  30375. return this._vertexBuffers[kind] !== undefined;
  30376. };
  30377. Geometry.prototype.getVerticesDataKinds = function () {
  30378. var result = [];
  30379. var kind;
  30380. if (!this._vertexBuffers && this._delayInfo) {
  30381. for (kind in this._delayInfo) {
  30382. result.push(kind);
  30383. }
  30384. }
  30385. else {
  30386. for (kind in this._vertexBuffers) {
  30387. result.push(kind);
  30388. }
  30389. }
  30390. return result;
  30391. };
  30392. Geometry.prototype.updateIndices = function (indices, offset) {
  30393. if (!this._indexBuffer) {
  30394. return;
  30395. }
  30396. if (!this._indexBufferIsUpdatable) {
  30397. this.setIndices(indices, null, true);
  30398. }
  30399. else {
  30400. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  30401. }
  30402. };
  30403. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  30404. if (totalVertices === void 0) { totalVertices = null; }
  30405. if (updatable === void 0) { updatable = false; }
  30406. if (this._indexBuffer) {
  30407. this._engine._releaseBuffer(this._indexBuffer);
  30408. }
  30409. this._disposeVertexArrayObjects();
  30410. this._indices = indices;
  30411. this._indexBufferIsUpdatable = updatable;
  30412. if (this._meshes.length !== 0 && this._indices) {
  30413. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  30414. }
  30415. if (totalVertices != undefined) {
  30416. this._totalVertices = totalVertices;
  30417. }
  30418. var meshes = this._meshes;
  30419. var numOfMeshes = meshes.length;
  30420. for (var index = 0; index < numOfMeshes; index++) {
  30421. meshes[index]._createGlobalSubMesh(true);
  30422. }
  30423. this.notifyUpdate();
  30424. };
  30425. Geometry.prototype.getTotalIndices = function () {
  30426. if (!this.isReady()) {
  30427. return 0;
  30428. }
  30429. return this._indices.length;
  30430. };
  30431. Geometry.prototype.getIndices = function (copyWhenShared) {
  30432. if (!this.isReady()) {
  30433. return null;
  30434. }
  30435. var orig = this._indices;
  30436. if (!copyWhenShared || this._meshes.length === 1) {
  30437. return orig;
  30438. }
  30439. else {
  30440. var len = orig.length;
  30441. var copy = [];
  30442. for (var i = 0; i < len; i++) {
  30443. copy.push(orig[i]);
  30444. }
  30445. return copy;
  30446. }
  30447. };
  30448. Geometry.prototype.getIndexBuffer = function () {
  30449. if (!this.isReady()) {
  30450. return null;
  30451. }
  30452. return this._indexBuffer;
  30453. };
  30454. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  30455. if (effect === void 0) { effect = null; }
  30456. if (!effect || !this._vertexArrayObjects) {
  30457. return;
  30458. }
  30459. if (this._vertexArrayObjects[effect.key]) {
  30460. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  30461. delete this._vertexArrayObjects[effect.key];
  30462. }
  30463. };
  30464. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30465. var meshes = this._meshes;
  30466. var index = meshes.indexOf(mesh);
  30467. if (index === -1) {
  30468. return;
  30469. }
  30470. meshes.splice(index, 1);
  30471. mesh._geometry = null;
  30472. if (meshes.length === 0 && shouldDispose) {
  30473. this.dispose();
  30474. }
  30475. };
  30476. Geometry.prototype.applyToMesh = function (mesh) {
  30477. if (mesh._geometry === this) {
  30478. return;
  30479. }
  30480. var previousGeometry = mesh._geometry;
  30481. if (previousGeometry) {
  30482. previousGeometry.releaseForMesh(mesh);
  30483. }
  30484. var meshes = this._meshes;
  30485. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30486. mesh._geometry = this;
  30487. this._scene.pushGeometry(this);
  30488. meshes.push(mesh);
  30489. if (this.isReady()) {
  30490. this._applyToMesh(mesh);
  30491. }
  30492. else {
  30493. mesh._boundingInfo = this._boundingInfo;
  30494. }
  30495. };
  30496. Geometry.prototype.updateExtend = function (data, stride) {
  30497. if (data === void 0) { data = null; }
  30498. if (!data) {
  30499. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30500. }
  30501. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  30502. };
  30503. Geometry.prototype._applyToMesh = function (mesh) {
  30504. var numOfMeshes = this._meshes.length;
  30505. // vertexBuffers
  30506. for (var kind in this._vertexBuffers) {
  30507. if (numOfMeshes === 1) {
  30508. this._vertexBuffers[kind].create();
  30509. }
  30510. var buffer = this._vertexBuffers[kind].getBuffer();
  30511. if (buffer)
  30512. buffer.references = numOfMeshes;
  30513. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30514. if (!this._extend) {
  30515. this.updateExtend(this._vertexBuffers[kind].getData());
  30516. }
  30517. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30518. mesh._createGlobalSubMesh(false);
  30519. //bounding info was just created again, world matrix should be applied again.
  30520. mesh._updateBoundingInfo();
  30521. }
  30522. }
  30523. // indexBuffer
  30524. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30525. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30526. }
  30527. if (this._indexBuffer) {
  30528. this._indexBuffer.references = numOfMeshes;
  30529. }
  30530. };
  30531. Geometry.prototype.notifyUpdate = function (kind) {
  30532. if (this.onGeometryUpdated) {
  30533. this.onGeometryUpdated(this, kind);
  30534. }
  30535. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30536. var mesh = _a[_i];
  30537. mesh._markSubMeshesAsAttributesDirty();
  30538. }
  30539. };
  30540. Geometry.prototype.load = function (scene, onLoaded) {
  30541. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30542. return;
  30543. }
  30544. if (this.isReady()) {
  30545. if (onLoaded) {
  30546. onLoaded();
  30547. }
  30548. return;
  30549. }
  30550. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30551. this._queueLoad(scene, onLoaded);
  30552. };
  30553. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30554. var _this = this;
  30555. if (!this.delayLoadingFile) {
  30556. return;
  30557. }
  30558. scene._addPendingData(this);
  30559. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30560. if (!_this._delayLoadingFunction) {
  30561. return;
  30562. }
  30563. _this._delayLoadingFunction(JSON.parse(data), _this);
  30564. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30565. _this._delayInfo = [];
  30566. scene._removePendingData(_this);
  30567. var meshes = _this._meshes;
  30568. var numOfMeshes = meshes.length;
  30569. for (var index = 0; index < numOfMeshes; index++) {
  30570. _this._applyToMesh(meshes[index]);
  30571. }
  30572. if (onLoaded) {
  30573. onLoaded();
  30574. }
  30575. }, function () { }, scene.database);
  30576. };
  30577. /**
  30578. * Invert the geometry to move from a right handed system to a left handed one.
  30579. */
  30580. Geometry.prototype.toLeftHanded = function () {
  30581. // Flip faces
  30582. var tIndices = this.getIndices(false);
  30583. if (tIndices != null && tIndices.length > 0) {
  30584. for (var i = 0; i < tIndices.length; i += 3) {
  30585. var tTemp = tIndices[i + 0];
  30586. tIndices[i + 0] = tIndices[i + 2];
  30587. tIndices[i + 2] = tTemp;
  30588. }
  30589. this.setIndices(tIndices);
  30590. }
  30591. // Negate position.z
  30592. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30593. if (tPositions != null && tPositions.length > 0) {
  30594. for (var i = 0; i < tPositions.length; i += 3) {
  30595. tPositions[i + 2] = -tPositions[i + 2];
  30596. }
  30597. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30598. }
  30599. // Negate normal.z
  30600. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30601. if (tNormals != null && tNormals.length > 0) {
  30602. for (var i = 0; i < tNormals.length; i += 3) {
  30603. tNormals[i + 2] = -tNormals[i + 2];
  30604. }
  30605. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30606. }
  30607. };
  30608. // Cache
  30609. Geometry.prototype._resetPointsArrayCache = function () {
  30610. this._positions = null;
  30611. };
  30612. Geometry.prototype._generatePointsArray = function () {
  30613. if (this._positions)
  30614. return true;
  30615. this._positions = [];
  30616. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30617. if (!data) {
  30618. return false;
  30619. }
  30620. for (var index = 0; index < data.length; index += 3) {
  30621. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30622. }
  30623. return true;
  30624. };
  30625. Geometry.prototype.isDisposed = function () {
  30626. return this._isDisposed;
  30627. };
  30628. Geometry.prototype._disposeVertexArrayObjects = function () {
  30629. if (this._vertexArrayObjects) {
  30630. for (var kind in this._vertexArrayObjects) {
  30631. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30632. }
  30633. this._vertexArrayObjects = {};
  30634. }
  30635. };
  30636. Geometry.prototype.dispose = function () {
  30637. var meshes = this._meshes;
  30638. var numOfMeshes = meshes.length;
  30639. var index;
  30640. for (index = 0; index < numOfMeshes; index++) {
  30641. this.releaseForMesh(meshes[index]);
  30642. }
  30643. this._meshes = [];
  30644. this._disposeVertexArrayObjects();
  30645. for (var kind in this._vertexBuffers) {
  30646. this._vertexBuffers[kind].dispose();
  30647. }
  30648. this._vertexBuffers = {};
  30649. this._totalVertices = 0;
  30650. if (this._indexBuffer) {
  30651. this._engine._releaseBuffer(this._indexBuffer);
  30652. }
  30653. this._indexBuffer = null;
  30654. this._indices = [];
  30655. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30656. this.delayLoadingFile = null;
  30657. this._delayLoadingFunction = null;
  30658. this._delayInfo = [];
  30659. this._boundingInfo = null;
  30660. this._scene.removeGeometry(this);
  30661. this._isDisposed = true;
  30662. };
  30663. Geometry.prototype.copy = function (id) {
  30664. var vertexData = new BABYLON.VertexData();
  30665. vertexData.indices = [];
  30666. var indices = this.getIndices();
  30667. if (indices) {
  30668. for (var index = 0; index < indices.length; index++) {
  30669. vertexData.indices.push(indices[index]);
  30670. }
  30671. }
  30672. var updatable = false;
  30673. var stopChecking = false;
  30674. var kind;
  30675. for (kind in this._vertexBuffers) {
  30676. // using slice() to make a copy of the array and not just reference it
  30677. var data = this.getVerticesData(kind);
  30678. if (data instanceof Float32Array) {
  30679. vertexData.set(new Float32Array(data), kind);
  30680. }
  30681. else {
  30682. vertexData.set(data.slice(0), kind);
  30683. }
  30684. if (!stopChecking) {
  30685. var vb = this.getVertexBuffer(kind);
  30686. if (vb) {
  30687. updatable = vb.isUpdatable();
  30688. stopChecking = !updatable;
  30689. }
  30690. }
  30691. }
  30692. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  30693. geometry.delayLoadState = this.delayLoadState;
  30694. geometry.delayLoadingFile = this.delayLoadingFile;
  30695. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30696. for (kind in this._delayInfo) {
  30697. geometry._delayInfo = geometry._delayInfo || [];
  30698. geometry._delayInfo.push(kind);
  30699. }
  30700. // Bounding info
  30701. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30702. return geometry;
  30703. };
  30704. Geometry.prototype.serialize = function () {
  30705. var serializationObject = {};
  30706. serializationObject.id = this.id;
  30707. serializationObject.updatable = this._updatable;
  30708. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30709. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30710. }
  30711. return serializationObject;
  30712. };
  30713. Geometry.prototype.toNumberArray = function (origin) {
  30714. if (Array.isArray(origin)) {
  30715. return origin;
  30716. }
  30717. else {
  30718. return Array.prototype.slice.call(origin);
  30719. }
  30720. };
  30721. Geometry.prototype.serializeVerticeData = function () {
  30722. var serializationObject = this.serialize();
  30723. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30724. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  30725. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30726. serializationObject.positions._updatable = true;
  30727. }
  30728. }
  30729. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30730. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  30731. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30732. serializationObject.normals._updatable = true;
  30733. }
  30734. }
  30735. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30736. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  30737. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  30738. serializationObject.uvs._updatable = true;
  30739. }
  30740. }
  30741. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30742. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  30743. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  30744. serializationObject.uv2s._updatable = true;
  30745. }
  30746. }
  30747. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30748. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  30749. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  30750. serializationObject.uv3s._updatable = true;
  30751. }
  30752. }
  30753. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30754. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  30755. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  30756. serializationObject.uv4s._updatable = true;
  30757. }
  30758. }
  30759. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30760. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  30761. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  30762. serializationObject.uv5s._updatable = true;
  30763. }
  30764. }
  30765. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30766. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  30767. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  30768. serializationObject.uv6s._updatable = true;
  30769. }
  30770. }
  30771. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30772. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  30773. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  30774. serializationObject.colors._updatable = true;
  30775. }
  30776. }
  30777. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30778. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  30779. serializationObject.matricesIndices._isExpanded = true;
  30780. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30781. serializationObject.matricesIndices._updatable = true;
  30782. }
  30783. }
  30784. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30785. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  30786. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30787. serializationObject.matricesWeights._updatable = true;
  30788. }
  30789. }
  30790. serializationObject.indices = this.toNumberArray(this.getIndices());
  30791. return serializationObject;
  30792. };
  30793. // Statics
  30794. Geometry.ExtractFromMesh = function (mesh, id) {
  30795. var geometry = mesh._geometry;
  30796. if (!geometry) {
  30797. return null;
  30798. }
  30799. return geometry.copy(id);
  30800. };
  30801. /**
  30802. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  30803. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  30804. * Be aware Math.random() could cause collisions, but:
  30805. * "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"
  30806. */
  30807. Geometry.RandomId = function () {
  30808. return BABYLON.Tools.RandomId();
  30809. };
  30810. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  30811. var scene = mesh.getScene();
  30812. // Geometry
  30813. var geometryId = parsedGeometry.geometryId;
  30814. if (geometryId) {
  30815. var geometry = scene.getGeometryByID(geometryId);
  30816. if (geometry) {
  30817. geometry.applyToMesh(mesh);
  30818. }
  30819. }
  30820. else if (parsedGeometry instanceof ArrayBuffer) {
  30821. var binaryInfo = mesh._binaryInfo;
  30822. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  30823. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  30824. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  30825. }
  30826. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  30827. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  30828. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  30829. }
  30830. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  30831. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  30832. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  30833. }
  30834. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  30835. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  30836. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  30837. }
  30838. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  30839. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  30840. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  30841. }
  30842. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  30843. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  30844. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  30845. }
  30846. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  30847. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  30848. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  30849. }
  30850. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  30851. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  30852. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  30853. }
  30854. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  30855. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  30856. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  30857. }
  30858. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  30859. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  30860. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  30861. }
  30862. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  30863. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  30864. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  30865. }
  30866. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  30867. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  30868. mesh.setIndices(indicesData, null);
  30869. }
  30870. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  30871. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  30872. mesh.subMeshes = [];
  30873. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  30874. var materialIndex = subMeshesData[(i * 5) + 0];
  30875. var verticesStart = subMeshesData[(i * 5) + 1];
  30876. var verticesCount = subMeshesData[(i * 5) + 2];
  30877. var indexStart = subMeshesData[(i * 5) + 3];
  30878. var indexCount = subMeshesData[(i * 5) + 4];
  30879. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  30880. }
  30881. }
  30882. }
  30883. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  30884. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  30885. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  30886. if (parsedGeometry.uvs) {
  30887. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  30888. }
  30889. if (parsedGeometry.uvs2) {
  30890. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  30891. }
  30892. if (parsedGeometry.uvs3) {
  30893. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  30894. }
  30895. if (parsedGeometry.uvs4) {
  30896. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  30897. }
  30898. if (parsedGeometry.uvs5) {
  30899. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  30900. }
  30901. if (parsedGeometry.uvs6) {
  30902. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  30903. }
  30904. if (parsedGeometry.colors) {
  30905. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  30906. }
  30907. if (parsedGeometry.matricesIndices) {
  30908. if (!parsedGeometry.matricesIndices._isExpanded) {
  30909. var floatIndices = [];
  30910. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  30911. var matricesIndex = parsedGeometry.matricesIndices[i];
  30912. floatIndices.push(matricesIndex & 0x000000FF);
  30913. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30914. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30915. floatIndices.push(matricesIndex >> 24);
  30916. }
  30917. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  30918. }
  30919. else {
  30920. delete parsedGeometry.matricesIndices._isExpanded;
  30921. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  30922. }
  30923. }
  30924. if (parsedGeometry.matricesIndicesExtra) {
  30925. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  30926. var floatIndices = [];
  30927. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  30928. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  30929. floatIndices.push(matricesIndex & 0x000000FF);
  30930. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30931. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30932. floatIndices.push(matricesIndex >> 24);
  30933. }
  30934. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  30935. }
  30936. else {
  30937. delete parsedGeometry.matricesIndices._isExpanded;
  30938. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  30939. }
  30940. }
  30941. if (parsedGeometry.matricesWeights) {
  30942. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  30943. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  30944. }
  30945. if (parsedGeometry.matricesWeightsExtra) {
  30946. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  30947. }
  30948. mesh.setIndices(parsedGeometry.indices, null);
  30949. }
  30950. // SubMeshes
  30951. if (parsedGeometry.subMeshes) {
  30952. mesh.subMeshes = [];
  30953. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  30954. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  30955. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  30956. }
  30957. }
  30958. // Flat shading
  30959. if (mesh._shouldGenerateFlatShading) {
  30960. mesh.convertToFlatShadedMesh();
  30961. delete mesh._shouldGenerateFlatShading;
  30962. }
  30963. // Update
  30964. mesh.computeWorldMatrix(true);
  30965. // Octree
  30966. if (scene['_selectionOctree']) {
  30967. scene['_selectionOctree'].addMesh(mesh);
  30968. }
  30969. };
  30970. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  30971. var epsilon = 1e-3;
  30972. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  30973. return;
  30974. }
  30975. var noInfluenceBoneIndex = 0.0;
  30976. if (parsedGeometry.skeletonId > -1) {
  30977. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  30978. if (!skeleton) {
  30979. return;
  30980. }
  30981. noInfluenceBoneIndex = skeleton.bones.length;
  30982. }
  30983. else {
  30984. return;
  30985. }
  30986. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30987. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  30988. var matricesWeights = parsedGeometry.matricesWeights;
  30989. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  30990. var influencers = parsedGeometry.numBoneInfluencer;
  30991. var size = matricesWeights.length;
  30992. for (var i = 0; i < size; i += 4) {
  30993. var weight = 0.0;
  30994. var firstZeroWeight = -1;
  30995. for (var j = 0; j < 4; j++) {
  30996. var w = matricesWeights[i + j];
  30997. weight += w;
  30998. if (w < epsilon && firstZeroWeight < 0) {
  30999. firstZeroWeight = j;
  31000. }
  31001. }
  31002. if (matricesWeightsExtra) {
  31003. for (var j = 0; j < 4; j++) {
  31004. var w = matricesWeightsExtra[i + j];
  31005. weight += w;
  31006. if (w < epsilon && firstZeroWeight < 0) {
  31007. firstZeroWeight = j + 4;
  31008. }
  31009. }
  31010. }
  31011. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31012. firstZeroWeight = influencers - 1;
  31013. }
  31014. if (weight > epsilon) {
  31015. var mweight = 1.0 / weight;
  31016. for (var j = 0; j < 4; j++) {
  31017. matricesWeights[i + j] *= mweight;
  31018. }
  31019. if (matricesWeightsExtra) {
  31020. for (var j = 0; j < 4; j++) {
  31021. matricesWeightsExtra[i + j] *= mweight;
  31022. }
  31023. }
  31024. }
  31025. else {
  31026. if (firstZeroWeight >= 4) {
  31027. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31028. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31029. }
  31030. else {
  31031. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31032. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31033. }
  31034. }
  31035. }
  31036. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31037. if (parsedGeometry.matricesWeightsExtra) {
  31038. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31039. }
  31040. };
  31041. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31042. if (scene.getGeometryByID(parsedVertexData.id)) {
  31043. return null; // null since geometry could be something else than a box...
  31044. }
  31045. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31046. if (BABYLON.Tags) {
  31047. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31048. }
  31049. if (parsedVertexData.delayLoadingFile) {
  31050. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31051. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31052. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31053. geometry._delayInfo = [];
  31054. if (parsedVertexData.hasUVs) {
  31055. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31056. }
  31057. if (parsedVertexData.hasUVs2) {
  31058. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31059. }
  31060. if (parsedVertexData.hasUVs3) {
  31061. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31062. }
  31063. if (parsedVertexData.hasUVs4) {
  31064. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31065. }
  31066. if (parsedVertexData.hasUVs5) {
  31067. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31068. }
  31069. if (parsedVertexData.hasUVs6) {
  31070. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31071. }
  31072. if (parsedVertexData.hasColors) {
  31073. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31074. }
  31075. if (parsedVertexData.hasMatricesIndices) {
  31076. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31077. }
  31078. if (parsedVertexData.hasMatricesWeights) {
  31079. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31080. }
  31081. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31082. }
  31083. else {
  31084. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31085. }
  31086. scene.pushGeometry(geometry, true);
  31087. return geometry;
  31088. };
  31089. return Geometry;
  31090. }());
  31091. BABYLON.Geometry = Geometry;
  31092. /////// Primitives //////////////////////////////////////////////
  31093. (function (Geometry) {
  31094. var Primitives;
  31095. (function (Primitives) {
  31096. /// Abstract class
  31097. var _Primitive = /** @class */ (function (_super) {
  31098. __extends(_Primitive, _super);
  31099. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31100. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31101. if (mesh === void 0) { mesh = null; }
  31102. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31103. _this._canBeRegenerated = _canBeRegenerated;
  31104. _this._beingRegenerated = true;
  31105. _this.regenerate();
  31106. _this._beingRegenerated = false;
  31107. return _this;
  31108. }
  31109. _Primitive.prototype.canBeRegenerated = function () {
  31110. return this._canBeRegenerated;
  31111. };
  31112. _Primitive.prototype.regenerate = function () {
  31113. if (!this._canBeRegenerated) {
  31114. return;
  31115. }
  31116. this._beingRegenerated = true;
  31117. this.setAllVerticesData(this._regenerateVertexData(), false);
  31118. this._beingRegenerated = false;
  31119. };
  31120. _Primitive.prototype.asNewGeometry = function (id) {
  31121. return _super.prototype.copy.call(this, id);
  31122. };
  31123. // overrides
  31124. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31125. if (!this._beingRegenerated) {
  31126. return;
  31127. }
  31128. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31129. };
  31130. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31131. if (!this._beingRegenerated) {
  31132. return;
  31133. }
  31134. _super.prototype.setVerticesData.call(this, kind, data, false);
  31135. };
  31136. // to override
  31137. // protected
  31138. _Primitive.prototype._regenerateVertexData = function () {
  31139. throw new Error("Abstract method");
  31140. };
  31141. _Primitive.prototype.copy = function (id) {
  31142. throw new Error("Must be overriden in sub-classes.");
  31143. };
  31144. _Primitive.prototype.serialize = function () {
  31145. var serializationObject = _super.prototype.serialize.call(this);
  31146. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31147. return serializationObject;
  31148. };
  31149. return _Primitive;
  31150. }(Geometry));
  31151. Primitives._Primitive = _Primitive;
  31152. var Ribbon = /** @class */ (function (_super) {
  31153. __extends(Ribbon, _super);
  31154. // Members
  31155. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31156. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31157. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31158. _this.pathArray = pathArray;
  31159. _this.closeArray = closeArray;
  31160. _this.closePath = closePath;
  31161. _this.offset = offset;
  31162. _this.side = side;
  31163. return _this;
  31164. }
  31165. Ribbon.prototype._regenerateVertexData = function () {
  31166. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31167. };
  31168. Ribbon.prototype.copy = function (id) {
  31169. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31170. };
  31171. return Ribbon;
  31172. }(_Primitive));
  31173. Primitives.Ribbon = Ribbon;
  31174. var Box = /** @class */ (function (_super) {
  31175. __extends(Box, _super);
  31176. // Members
  31177. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31178. if (mesh === void 0) { mesh = null; }
  31179. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31180. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31181. _this.size = size;
  31182. _this.side = side;
  31183. return _this;
  31184. }
  31185. Box.prototype._regenerateVertexData = function () {
  31186. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31187. };
  31188. Box.prototype.copy = function (id) {
  31189. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31190. };
  31191. Box.prototype.serialize = function () {
  31192. var serializationObject = _super.prototype.serialize.call(this);
  31193. serializationObject.size = this.size;
  31194. return serializationObject;
  31195. };
  31196. Box.Parse = function (parsedBox, scene) {
  31197. if (scene.getGeometryByID(parsedBox.id)) {
  31198. return null; // null since geometry could be something else than a box...
  31199. }
  31200. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31201. if (BABYLON.Tags) {
  31202. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31203. }
  31204. scene.pushGeometry(box, true);
  31205. return box;
  31206. };
  31207. return Box;
  31208. }(_Primitive));
  31209. Primitives.Box = Box;
  31210. var Sphere = /** @class */ (function (_super) {
  31211. __extends(Sphere, _super);
  31212. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31213. if (mesh === void 0) { mesh = null; }
  31214. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31215. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31216. _this.segments = segments;
  31217. _this.diameter = diameter;
  31218. _this.side = side;
  31219. return _this;
  31220. }
  31221. Sphere.prototype._regenerateVertexData = function () {
  31222. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31223. };
  31224. Sphere.prototype.copy = function (id) {
  31225. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31226. };
  31227. Sphere.prototype.serialize = function () {
  31228. var serializationObject = _super.prototype.serialize.call(this);
  31229. serializationObject.segments = this.segments;
  31230. serializationObject.diameter = this.diameter;
  31231. return serializationObject;
  31232. };
  31233. Sphere.Parse = function (parsedSphere, scene) {
  31234. if (scene.getGeometryByID(parsedSphere.id)) {
  31235. return null; // null since geometry could be something else than a sphere...
  31236. }
  31237. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31238. if (BABYLON.Tags) {
  31239. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31240. }
  31241. scene.pushGeometry(sphere, true);
  31242. return sphere;
  31243. };
  31244. return Sphere;
  31245. }(_Primitive));
  31246. Primitives.Sphere = Sphere;
  31247. var Disc = /** @class */ (function (_super) {
  31248. __extends(Disc, _super);
  31249. // Members
  31250. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31251. if (mesh === void 0) { mesh = null; }
  31252. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31253. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31254. _this.radius = radius;
  31255. _this.tessellation = tessellation;
  31256. _this.side = side;
  31257. return _this;
  31258. }
  31259. Disc.prototype._regenerateVertexData = function () {
  31260. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31261. };
  31262. Disc.prototype.copy = function (id) {
  31263. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31264. };
  31265. return Disc;
  31266. }(_Primitive));
  31267. Primitives.Disc = Disc;
  31268. var Cylinder = /** @class */ (function (_super) {
  31269. __extends(Cylinder, _super);
  31270. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31271. if (subdivisions === void 0) { subdivisions = 1; }
  31272. if (mesh === void 0) { mesh = null; }
  31273. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31274. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31275. _this.height = height;
  31276. _this.diameterTop = diameterTop;
  31277. _this.diameterBottom = diameterBottom;
  31278. _this.tessellation = tessellation;
  31279. _this.subdivisions = subdivisions;
  31280. _this.side = side;
  31281. return _this;
  31282. }
  31283. Cylinder.prototype._regenerateVertexData = function () {
  31284. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31285. };
  31286. Cylinder.prototype.copy = function (id) {
  31287. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31288. };
  31289. Cylinder.prototype.serialize = function () {
  31290. var serializationObject = _super.prototype.serialize.call(this);
  31291. serializationObject.height = this.height;
  31292. serializationObject.diameterTop = this.diameterTop;
  31293. serializationObject.diameterBottom = this.diameterBottom;
  31294. serializationObject.tessellation = this.tessellation;
  31295. return serializationObject;
  31296. };
  31297. Cylinder.Parse = function (parsedCylinder, scene) {
  31298. if (scene.getGeometryByID(parsedCylinder.id)) {
  31299. return null; // null since geometry could be something else than a cylinder...
  31300. }
  31301. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31302. if (BABYLON.Tags) {
  31303. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31304. }
  31305. scene.pushGeometry(cylinder, true);
  31306. return cylinder;
  31307. };
  31308. return Cylinder;
  31309. }(_Primitive));
  31310. Primitives.Cylinder = Cylinder;
  31311. var Torus = /** @class */ (function (_super) {
  31312. __extends(Torus, _super);
  31313. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31314. if (mesh === void 0) { mesh = null; }
  31315. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31316. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31317. _this.diameter = diameter;
  31318. _this.thickness = thickness;
  31319. _this.tessellation = tessellation;
  31320. _this.side = side;
  31321. return _this;
  31322. }
  31323. Torus.prototype._regenerateVertexData = function () {
  31324. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31325. };
  31326. Torus.prototype.copy = function (id) {
  31327. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31328. };
  31329. Torus.prototype.serialize = function () {
  31330. var serializationObject = _super.prototype.serialize.call(this);
  31331. serializationObject.diameter = this.diameter;
  31332. serializationObject.thickness = this.thickness;
  31333. serializationObject.tessellation = this.tessellation;
  31334. return serializationObject;
  31335. };
  31336. Torus.Parse = function (parsedTorus, scene) {
  31337. if (scene.getGeometryByID(parsedTorus.id)) {
  31338. return null; // null since geometry could be something else than a torus...
  31339. }
  31340. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31341. if (BABYLON.Tags) {
  31342. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31343. }
  31344. scene.pushGeometry(torus, true);
  31345. return torus;
  31346. };
  31347. return Torus;
  31348. }(_Primitive));
  31349. Primitives.Torus = Torus;
  31350. var Ground = /** @class */ (function (_super) {
  31351. __extends(Ground, _super);
  31352. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31353. if (mesh === void 0) { mesh = null; }
  31354. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31355. _this.width = width;
  31356. _this.height = height;
  31357. _this.subdivisions = subdivisions;
  31358. return _this;
  31359. }
  31360. Ground.prototype._regenerateVertexData = function () {
  31361. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31362. };
  31363. Ground.prototype.copy = function (id) {
  31364. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31365. };
  31366. Ground.prototype.serialize = function () {
  31367. var serializationObject = _super.prototype.serialize.call(this);
  31368. serializationObject.width = this.width;
  31369. serializationObject.height = this.height;
  31370. serializationObject.subdivisions = this.subdivisions;
  31371. return serializationObject;
  31372. };
  31373. Ground.Parse = function (parsedGround, scene) {
  31374. if (scene.getGeometryByID(parsedGround.id)) {
  31375. return null; // null since geometry could be something else than a ground...
  31376. }
  31377. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31378. if (BABYLON.Tags) {
  31379. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31380. }
  31381. scene.pushGeometry(ground, true);
  31382. return ground;
  31383. };
  31384. return Ground;
  31385. }(_Primitive));
  31386. Primitives.Ground = Ground;
  31387. var TiledGround = /** @class */ (function (_super) {
  31388. __extends(TiledGround, _super);
  31389. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31390. if (mesh === void 0) { mesh = null; }
  31391. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31392. _this.xmin = xmin;
  31393. _this.zmin = zmin;
  31394. _this.xmax = xmax;
  31395. _this.zmax = zmax;
  31396. _this.subdivisions = subdivisions;
  31397. _this.precision = precision;
  31398. return _this;
  31399. }
  31400. TiledGround.prototype._regenerateVertexData = function () {
  31401. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31402. };
  31403. TiledGround.prototype.copy = function (id) {
  31404. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31405. };
  31406. return TiledGround;
  31407. }(_Primitive));
  31408. Primitives.TiledGround = TiledGround;
  31409. var Plane = /** @class */ (function (_super) {
  31410. __extends(Plane, _super);
  31411. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31412. if (mesh === void 0) { mesh = null; }
  31413. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31414. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31415. _this.size = size;
  31416. _this.side = side;
  31417. return _this;
  31418. }
  31419. Plane.prototype._regenerateVertexData = function () {
  31420. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31421. };
  31422. Plane.prototype.copy = function (id) {
  31423. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31424. };
  31425. Plane.prototype.serialize = function () {
  31426. var serializationObject = _super.prototype.serialize.call(this);
  31427. serializationObject.size = this.size;
  31428. return serializationObject;
  31429. };
  31430. Plane.Parse = function (parsedPlane, scene) {
  31431. if (scene.getGeometryByID(parsedPlane.id)) {
  31432. return null; // null since geometry could be something else than a ground...
  31433. }
  31434. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31435. if (BABYLON.Tags) {
  31436. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31437. }
  31438. scene.pushGeometry(plane, true);
  31439. return plane;
  31440. };
  31441. return Plane;
  31442. }(_Primitive));
  31443. Primitives.Plane = Plane;
  31444. var TorusKnot = /** @class */ (function (_super) {
  31445. __extends(TorusKnot, _super);
  31446. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31447. if (mesh === void 0) { mesh = null; }
  31448. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31449. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31450. _this.radius = radius;
  31451. _this.tube = tube;
  31452. _this.radialSegments = radialSegments;
  31453. _this.tubularSegments = tubularSegments;
  31454. _this.p = p;
  31455. _this.q = q;
  31456. _this.side = side;
  31457. return _this;
  31458. }
  31459. TorusKnot.prototype._regenerateVertexData = function () {
  31460. 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 });
  31461. };
  31462. TorusKnot.prototype.copy = function (id) {
  31463. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31464. };
  31465. TorusKnot.prototype.serialize = function () {
  31466. var serializationObject = _super.prototype.serialize.call(this);
  31467. serializationObject.radius = this.radius;
  31468. serializationObject.tube = this.tube;
  31469. serializationObject.radialSegments = this.radialSegments;
  31470. serializationObject.tubularSegments = this.tubularSegments;
  31471. serializationObject.p = this.p;
  31472. serializationObject.q = this.q;
  31473. return serializationObject;
  31474. };
  31475. ;
  31476. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31477. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31478. return null; // null since geometry could be something else than a ground...
  31479. }
  31480. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31481. if (BABYLON.Tags) {
  31482. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31483. }
  31484. scene.pushGeometry(torusKnot, true);
  31485. return torusKnot;
  31486. };
  31487. return TorusKnot;
  31488. }(_Primitive));
  31489. Primitives.TorusKnot = TorusKnot;
  31490. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31491. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31492. })(BABYLON || (BABYLON = {}));
  31493. //# sourceMappingURL=babylon.geometry.js.map
  31494. var BABYLON;
  31495. (function (BABYLON) {
  31496. var PostProcessManager = /** @class */ (function () {
  31497. function PostProcessManager(scene) {
  31498. this._vertexBuffers = {};
  31499. this._scene = scene;
  31500. }
  31501. PostProcessManager.prototype._prepareBuffers = function () {
  31502. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31503. return;
  31504. }
  31505. // VBO
  31506. var vertices = [];
  31507. vertices.push(1, 1);
  31508. vertices.push(-1, 1);
  31509. vertices.push(-1, -1);
  31510. vertices.push(1, -1);
  31511. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31512. this._buildIndexBuffer();
  31513. };
  31514. PostProcessManager.prototype._buildIndexBuffer = function () {
  31515. // Indices
  31516. var indices = [];
  31517. indices.push(0);
  31518. indices.push(1);
  31519. indices.push(2);
  31520. indices.push(0);
  31521. indices.push(2);
  31522. indices.push(3);
  31523. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31524. };
  31525. PostProcessManager.prototype._rebuild = function () {
  31526. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31527. if (!vb) {
  31528. return;
  31529. }
  31530. vb._rebuild();
  31531. this._buildIndexBuffer();
  31532. };
  31533. // Methods
  31534. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31535. if (sourceTexture === void 0) { sourceTexture = null; }
  31536. if (postProcesses === void 0) { postProcesses = null; }
  31537. var camera = this._scene.activeCamera;
  31538. if (!camera) {
  31539. return false;
  31540. }
  31541. var postProcesses = postProcesses || camera._postProcesses;
  31542. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31543. return false;
  31544. }
  31545. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31546. return true;
  31547. };
  31548. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31549. if (targetTexture === void 0) { targetTexture = null; }
  31550. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31551. if (!this._scene.activeCamera) {
  31552. return;
  31553. }
  31554. var engine = this._scene.getEngine();
  31555. for (var index = 0; index < postProcesses.length; index++) {
  31556. if (index < postProcesses.length - 1) {
  31557. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31558. }
  31559. else {
  31560. if (targetTexture) {
  31561. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31562. }
  31563. else {
  31564. engine.restoreDefaultFramebuffer();
  31565. }
  31566. }
  31567. var pp = postProcesses[index];
  31568. var effect = pp.apply();
  31569. if (effect) {
  31570. pp.onBeforeRenderObservable.notifyObservers(effect);
  31571. // VBOs
  31572. this._prepareBuffers();
  31573. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31574. // Draw order
  31575. engine.draw(true, 0, 6);
  31576. pp.onAfterRenderObservable.notifyObservers(effect);
  31577. }
  31578. }
  31579. // Restore depth buffer
  31580. engine.setDepthBuffer(true);
  31581. engine.setDepthWrite(true);
  31582. };
  31583. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31584. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31585. var camera = this._scene.activeCamera;
  31586. if (!camera) {
  31587. return;
  31588. }
  31589. postProcesses = postProcesses || camera._postProcesses;
  31590. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31591. return;
  31592. }
  31593. var engine = this._scene.getEngine();
  31594. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31595. if (index < len - 1) {
  31596. postProcesses[index + 1].activate(camera, targetTexture);
  31597. }
  31598. else {
  31599. if (targetTexture) {
  31600. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31601. }
  31602. else {
  31603. engine.restoreDefaultFramebuffer();
  31604. }
  31605. }
  31606. if (doNotPresent) {
  31607. break;
  31608. }
  31609. var pp = postProcesses[index];
  31610. var effect = pp.apply();
  31611. if (effect) {
  31612. pp.onBeforeRenderObservable.notifyObservers(effect);
  31613. // VBOs
  31614. this._prepareBuffers();
  31615. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31616. // Draw order
  31617. engine.draw(true, 0, 6);
  31618. pp.onAfterRenderObservable.notifyObservers(effect);
  31619. }
  31620. }
  31621. // Restore states
  31622. engine.setDepthBuffer(true);
  31623. engine.setDepthWrite(true);
  31624. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31625. };
  31626. PostProcessManager.prototype.dispose = function () {
  31627. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31628. if (buffer) {
  31629. buffer.dispose();
  31630. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31631. }
  31632. if (this._indexBuffer) {
  31633. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31634. this._indexBuffer = null;
  31635. }
  31636. };
  31637. return PostProcessManager;
  31638. }());
  31639. BABYLON.PostProcessManager = PostProcessManager;
  31640. })(BABYLON || (BABYLON = {}));
  31641. //# sourceMappingURL=babylon.postProcessManager.js.map
  31642. var BABYLON;
  31643. (function (BABYLON) {
  31644. /**
  31645. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31646. */
  31647. var PerformanceMonitor = /** @class */ (function () {
  31648. /**
  31649. * constructor
  31650. * @param frameSampleSize The number of samples required to saturate the sliding window
  31651. */
  31652. function PerformanceMonitor(frameSampleSize) {
  31653. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31654. this._enabled = true;
  31655. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31656. }
  31657. /**
  31658. * Samples current frame
  31659. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31660. */
  31661. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31662. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31663. if (!this._enabled)
  31664. return;
  31665. if (this._lastFrameTimeMs != null) {
  31666. var dt = timeMs - this._lastFrameTimeMs;
  31667. this._rollingFrameTime.add(dt);
  31668. }
  31669. this._lastFrameTimeMs = timeMs;
  31670. };
  31671. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31672. /**
  31673. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31674. * @return Average frame time in milliseconds
  31675. */
  31676. get: function () {
  31677. return this._rollingFrameTime.average;
  31678. },
  31679. enumerable: true,
  31680. configurable: true
  31681. });
  31682. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  31683. /**
  31684. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31685. * @return Frame time variance in milliseconds squared
  31686. */
  31687. get: function () {
  31688. return this._rollingFrameTime.variance;
  31689. },
  31690. enumerable: true,
  31691. configurable: true
  31692. });
  31693. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  31694. /**
  31695. * Returns the frame time of the most recent frame
  31696. * @return Frame time in milliseconds
  31697. */
  31698. get: function () {
  31699. return this._rollingFrameTime.history(0);
  31700. },
  31701. enumerable: true,
  31702. configurable: true
  31703. });
  31704. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  31705. /**
  31706. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  31707. * @return Framerate in frames per second
  31708. */
  31709. get: function () {
  31710. return 1000.0 / this._rollingFrameTime.average;
  31711. },
  31712. enumerable: true,
  31713. configurable: true
  31714. });
  31715. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  31716. /**
  31717. * Returns the average framerate in frames per second using the most recent frame time
  31718. * @return Framerate in frames per second
  31719. */
  31720. get: function () {
  31721. var history = this._rollingFrameTime.history(0);
  31722. if (history === 0) {
  31723. return 0;
  31724. }
  31725. return 1000.0 / history;
  31726. },
  31727. enumerable: true,
  31728. configurable: true
  31729. });
  31730. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  31731. /**
  31732. * Returns true if enough samples have been taken to completely fill the sliding window
  31733. * @return true if saturated
  31734. */
  31735. get: function () {
  31736. return this._rollingFrameTime.isSaturated();
  31737. },
  31738. enumerable: true,
  31739. configurable: true
  31740. });
  31741. /**
  31742. * Enables contributions to the sliding window sample set
  31743. */
  31744. PerformanceMonitor.prototype.enable = function () {
  31745. this._enabled = true;
  31746. };
  31747. /**
  31748. * Disables contributions to the sliding window sample set
  31749. * Samples will not be interpolated over the disabled period
  31750. */
  31751. PerformanceMonitor.prototype.disable = function () {
  31752. this._enabled = false;
  31753. //clear last sample to avoid interpolating over the disabled period when next enabled
  31754. this._lastFrameTimeMs = null;
  31755. this._lastChangeTimeMs = null;
  31756. };
  31757. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  31758. /**
  31759. * Returns true if sampling is enabled
  31760. * @return true if enabled
  31761. */
  31762. get: function () {
  31763. return this._enabled;
  31764. },
  31765. enumerable: true,
  31766. configurable: true
  31767. });
  31768. /**
  31769. * Resets performance monitor
  31770. */
  31771. PerformanceMonitor.prototype.reset = function () {
  31772. //clear last sample to avoid interpolating over the disabled period when next enabled
  31773. this._lastFrameTimeMs = null;
  31774. this._lastChangeTimeMs = null;
  31775. //wipe record
  31776. this._rollingFrameTime.reset();
  31777. };
  31778. return PerformanceMonitor;
  31779. }());
  31780. BABYLON.PerformanceMonitor = PerformanceMonitor;
  31781. /**
  31782. * RollingAverage
  31783. *
  31784. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  31785. */
  31786. var RollingAverage = /** @class */ (function () {
  31787. /**
  31788. * constructor
  31789. * @param length The number of samples required to saturate the sliding window
  31790. */
  31791. function RollingAverage(length) {
  31792. this._samples = new Array(length);
  31793. this.reset();
  31794. }
  31795. /**
  31796. * Adds a sample to the sample set
  31797. * @param v The sample value
  31798. */
  31799. RollingAverage.prototype.add = function (v) {
  31800. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  31801. var delta;
  31802. //we need to check if we've already wrapped round
  31803. if (this.isSaturated()) {
  31804. //remove bottom of stack from mean
  31805. var bottomValue = this._samples[this._pos];
  31806. delta = bottomValue - this.average;
  31807. this.average -= delta / (this._sampleCount - 1);
  31808. this._m2 -= delta * (bottomValue - this.average);
  31809. }
  31810. else {
  31811. this._sampleCount++;
  31812. }
  31813. //add new value to mean
  31814. delta = v - this.average;
  31815. this.average += delta / (this._sampleCount);
  31816. this._m2 += delta * (v - this.average);
  31817. //set the new variance
  31818. this.variance = this._m2 / (this._sampleCount - 1);
  31819. this._samples[this._pos] = v;
  31820. this._pos++;
  31821. this._pos %= this._samples.length; //positive wrap around
  31822. };
  31823. /**
  31824. * Returns previously added values or null if outside of history or outside the sliding window domain
  31825. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  31826. * @return Value previously recorded with add() or null if outside of range
  31827. */
  31828. RollingAverage.prototype.history = function (i) {
  31829. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  31830. return 0;
  31831. }
  31832. var i0 = this._wrapPosition(this._pos - 1.0);
  31833. return this._samples[this._wrapPosition(i0 - i)];
  31834. };
  31835. /**
  31836. * Returns true if enough samples have been taken to completely fill the sliding window
  31837. * @return true if sample-set saturated
  31838. */
  31839. RollingAverage.prototype.isSaturated = function () {
  31840. return this._sampleCount >= this._samples.length;
  31841. };
  31842. /**
  31843. * Resets the rolling average (equivalent to 0 samples taken so far)
  31844. */
  31845. RollingAverage.prototype.reset = function () {
  31846. this.average = 0;
  31847. this.variance = 0;
  31848. this._sampleCount = 0;
  31849. this._pos = 0;
  31850. this._m2 = 0;
  31851. };
  31852. /**
  31853. * Wraps a value around the sample range boundaries
  31854. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  31855. * @return Wrapped position in sample range
  31856. */
  31857. RollingAverage.prototype._wrapPosition = function (i) {
  31858. var max = this._samples.length;
  31859. return ((i % max) + max) % max;
  31860. };
  31861. return RollingAverage;
  31862. }());
  31863. BABYLON.RollingAverage = RollingAverage;
  31864. })(BABYLON || (BABYLON = {}));
  31865. //# sourceMappingURL=babylon.performanceMonitor.js.map
  31866. var BABYLON;
  31867. (function (BABYLON) {
  31868. /**
  31869. * This groups together the common properties used for image processing either in direct forward pass
  31870. * or through post processing effect depending on the use of the image processing pipeline in your scene
  31871. * or not.
  31872. */
  31873. var ImageProcessingConfiguration = /** @class */ (function () {
  31874. function ImageProcessingConfiguration() {
  31875. /**
  31876. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  31877. */
  31878. this.colorCurves = new BABYLON.ColorCurves();
  31879. this._colorCurvesEnabled = false;
  31880. this._colorGradingEnabled = false;
  31881. this._colorGradingWithGreenDepth = true;
  31882. this._colorGradingBGR = true;
  31883. this._exposure = 1.0;
  31884. this._toneMappingEnabled = false;
  31885. this._contrast = 1.0;
  31886. /**
  31887. * Vignette stretch size.
  31888. */
  31889. this.vignetteStretch = 0;
  31890. /**
  31891. * Vignette centre X Offset.
  31892. */
  31893. this.vignetteCentreX = 0;
  31894. /**
  31895. * Vignette centre Y Offset.
  31896. */
  31897. this.vignetteCentreY = 0;
  31898. /**
  31899. * Vignette weight or intensity of the vignette effect.
  31900. */
  31901. this.vignetteWeight = 1.5;
  31902. /**
  31903. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  31904. * if vignetteEnabled is set to true.
  31905. */
  31906. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  31907. /**
  31908. * Camera field of view used by the Vignette effect.
  31909. */
  31910. this.vignetteCameraFov = 0.5;
  31911. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  31912. this._vignetteEnabled = false;
  31913. this._applyByPostProcess = false;
  31914. /**
  31915. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  31916. * @type {BABYLON.Observable}
  31917. */
  31918. this.onUpdateParameters = new BABYLON.Observable();
  31919. }
  31920. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  31921. /**
  31922. * Gets wether the color curves effect is enabled.
  31923. */
  31924. get: function () {
  31925. return this._colorCurvesEnabled;
  31926. },
  31927. /**
  31928. * Sets wether the color curves effect is enabled.
  31929. */
  31930. set: function (value) {
  31931. if (this._colorCurvesEnabled === value) {
  31932. return;
  31933. }
  31934. this._colorCurvesEnabled = value;
  31935. this._updateParameters();
  31936. },
  31937. enumerable: true,
  31938. configurable: true
  31939. });
  31940. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  31941. /**
  31942. * Gets wether the color grading effect is enabled.
  31943. */
  31944. get: function () {
  31945. return this._colorGradingEnabled;
  31946. },
  31947. /**
  31948. * Sets wether the color grading effect is enabled.
  31949. */
  31950. set: function (value) {
  31951. if (this._colorGradingEnabled === value) {
  31952. return;
  31953. }
  31954. this._colorGradingEnabled = value;
  31955. this._updateParameters();
  31956. },
  31957. enumerable: true,
  31958. configurable: true
  31959. });
  31960. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  31961. /**
  31962. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  31963. */
  31964. get: function () {
  31965. return this._colorGradingWithGreenDepth;
  31966. },
  31967. /**
  31968. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  31969. */
  31970. set: function (value) {
  31971. if (this._colorGradingWithGreenDepth === value) {
  31972. return;
  31973. }
  31974. this._colorGradingWithGreenDepth = value;
  31975. this._updateParameters();
  31976. },
  31977. enumerable: true,
  31978. configurable: true
  31979. });
  31980. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  31981. /**
  31982. * Gets wether the color grading texture contains BGR values.
  31983. */
  31984. get: function () {
  31985. return this._colorGradingBGR;
  31986. },
  31987. /**
  31988. * Sets wether the color grading texture contains BGR values.
  31989. */
  31990. set: function (value) {
  31991. if (this._colorGradingBGR === value) {
  31992. return;
  31993. }
  31994. this._colorGradingBGR = value;
  31995. this._updateParameters();
  31996. },
  31997. enumerable: true,
  31998. configurable: true
  31999. });
  32000. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32001. /**
  32002. * Gets the Exposure used in the effect.
  32003. */
  32004. get: function () {
  32005. return this._exposure;
  32006. },
  32007. /**
  32008. * Sets the Exposure used in the effect.
  32009. */
  32010. set: function (value) {
  32011. if (this._exposure === value) {
  32012. return;
  32013. }
  32014. this._exposure = value;
  32015. this._updateParameters();
  32016. },
  32017. enumerable: true,
  32018. configurable: true
  32019. });
  32020. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32021. /**
  32022. * Gets wether the tone mapping effect is enabled.
  32023. */
  32024. get: function () {
  32025. return this._toneMappingEnabled;
  32026. },
  32027. /**
  32028. * Sets wether the tone mapping effect is enabled.
  32029. */
  32030. set: function (value) {
  32031. if (this._toneMappingEnabled === value) {
  32032. return;
  32033. }
  32034. this._toneMappingEnabled = value;
  32035. this._updateParameters();
  32036. },
  32037. enumerable: true,
  32038. configurable: true
  32039. });
  32040. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32041. /**
  32042. * Gets the contrast used in the effect.
  32043. */
  32044. get: function () {
  32045. return this._contrast;
  32046. },
  32047. /**
  32048. * Sets the contrast used in the effect.
  32049. */
  32050. set: function (value) {
  32051. if (this._contrast === value) {
  32052. return;
  32053. }
  32054. this._contrast = value;
  32055. this._updateParameters();
  32056. },
  32057. enumerable: true,
  32058. configurable: true
  32059. });
  32060. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32061. /**
  32062. * Gets the vignette blend mode allowing different kind of effect.
  32063. */
  32064. get: function () {
  32065. return this._vignetteBlendMode;
  32066. },
  32067. /**
  32068. * Sets the vignette blend mode allowing different kind of effect.
  32069. */
  32070. set: function (value) {
  32071. if (this._vignetteBlendMode === value) {
  32072. return;
  32073. }
  32074. this._vignetteBlendMode = value;
  32075. this._updateParameters();
  32076. },
  32077. enumerable: true,
  32078. configurable: true
  32079. });
  32080. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32081. /**
  32082. * Gets wether the vignette effect is enabled.
  32083. */
  32084. get: function () {
  32085. return this._vignetteEnabled;
  32086. },
  32087. /**
  32088. * Sets wether the vignette effect is enabled.
  32089. */
  32090. set: function (value) {
  32091. if (this._vignetteEnabled === value) {
  32092. return;
  32093. }
  32094. this._vignetteEnabled = value;
  32095. this._updateParameters();
  32096. },
  32097. enumerable: true,
  32098. configurable: true
  32099. });
  32100. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32101. /**
  32102. * Gets wether the image processing is applied through a post process or not.
  32103. */
  32104. get: function () {
  32105. return this._applyByPostProcess;
  32106. },
  32107. /**
  32108. * Sets wether the image processing is applied through a post process or not.
  32109. */
  32110. set: function (value) {
  32111. if (this._applyByPostProcess === value) {
  32112. return;
  32113. }
  32114. this._applyByPostProcess = value;
  32115. this._updateParameters();
  32116. },
  32117. enumerable: true,
  32118. configurable: true
  32119. });
  32120. /**
  32121. * Method called each time the image processing information changes requires to recompile the effect.
  32122. */
  32123. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32124. this.onUpdateParameters.notifyObservers(this);
  32125. };
  32126. ImageProcessingConfiguration.prototype.getClassName = function () {
  32127. return "ImageProcessingConfiguration";
  32128. };
  32129. /**
  32130. * Prepare the list of uniforms associated with the Image Processing effects.
  32131. * @param uniformsList The list of uniforms used in the effect
  32132. * @param defines the list of defines currently in use
  32133. */
  32134. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32135. if (defines.EXPOSURE) {
  32136. uniforms.push("exposureLinear");
  32137. }
  32138. if (defines.CONTRAST) {
  32139. uniforms.push("contrast");
  32140. }
  32141. if (defines.COLORGRADING) {
  32142. uniforms.push("colorTransformSettings");
  32143. }
  32144. if (defines.VIGNETTE) {
  32145. uniforms.push("vInverseScreenSize");
  32146. uniforms.push("vignetteSettings1");
  32147. uniforms.push("vignetteSettings2");
  32148. }
  32149. if (defines.COLORCURVES) {
  32150. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32151. }
  32152. };
  32153. /**
  32154. * Prepare the list of samplers associated with the Image Processing effects.
  32155. * @param uniformsList The list of uniforms used in the effect
  32156. * @param defines the list of defines currently in use
  32157. */
  32158. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32159. if (defines.COLORGRADING) {
  32160. samplersList.push("txColorTransform");
  32161. }
  32162. };
  32163. /**
  32164. * Prepare the list of defines associated to the shader.
  32165. * @param defines the list of defines to complete
  32166. */
  32167. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32168. if (forPostProcess === void 0) { forPostProcess = false; }
  32169. if (forPostProcess !== this.applyByPostProcess) {
  32170. defines.VIGNETTE = false;
  32171. defines.TONEMAPPING = false;
  32172. defines.CONTRAST = false;
  32173. defines.EXPOSURE = false;
  32174. defines.COLORCURVES = false;
  32175. defines.COLORGRADING = false;
  32176. defines.COLORGRADING3D = false;
  32177. defines.IMAGEPROCESSING = false;
  32178. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32179. return;
  32180. }
  32181. defines.VIGNETTE = this.vignetteEnabled;
  32182. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32183. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32184. defines.TONEMAPPING = this.toneMappingEnabled;
  32185. defines.CONTRAST = (this.contrast !== 1.0);
  32186. defines.EXPOSURE = (this.exposure !== 1.0);
  32187. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32188. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32189. if (defines.COLORGRADING) {
  32190. var texture = this.colorGradingTexture;
  32191. defines.COLORGRADING3D = (texture.getScene().getEngine().webGLVersion > 1) ? true : false;
  32192. }
  32193. else {
  32194. defines.COLORGRADING3D = false;
  32195. }
  32196. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32197. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32198. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32199. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32200. };
  32201. /**
  32202. * Returns true if all the image processing information are ready.
  32203. */
  32204. ImageProcessingConfiguration.prototype.isReady = function () {
  32205. // Color Grading texure can not be none blocking.
  32206. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32207. };
  32208. /**
  32209. * Binds the image processing to the shader.
  32210. * @param effect The effect to bind to
  32211. */
  32212. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32213. if (aspectRatio === void 0) { aspectRatio = 1; }
  32214. // Color Curves
  32215. if (this._colorCurvesEnabled && this.colorCurves) {
  32216. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32217. }
  32218. // Vignette
  32219. if (this._vignetteEnabled) {
  32220. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32221. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32222. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32223. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32224. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32225. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32226. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32227. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32228. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32229. var vignettePower = -2.0 * this.vignetteWeight;
  32230. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32231. }
  32232. // Exposure
  32233. effect.setFloat("exposureLinear", this.exposure);
  32234. // Contrast
  32235. effect.setFloat("contrast", this.contrast);
  32236. // Color transform settings
  32237. if (this.colorGradingTexture) {
  32238. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32239. var textureSize = this.colorGradingTexture.getSize().height;
  32240. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32241. 0.5 / textureSize, // textureOffset
  32242. textureSize, // textureSize
  32243. this.colorGradingTexture.level // weight
  32244. );
  32245. }
  32246. };
  32247. /**
  32248. * Clones the current image processing instance.
  32249. * @return The cloned image processing
  32250. */
  32251. ImageProcessingConfiguration.prototype.clone = function () {
  32252. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32253. };
  32254. /**
  32255. * Serializes the current image processing instance to a json representation.
  32256. * @return a JSON representation
  32257. */
  32258. ImageProcessingConfiguration.prototype.serialize = function () {
  32259. return BABYLON.SerializationHelper.Serialize(this);
  32260. };
  32261. /**
  32262. * Parses the image processing from a json representation.
  32263. * @param source the JSON source to parse
  32264. * @return The parsed image processing
  32265. */
  32266. ImageProcessingConfiguration.Parse = function (source) {
  32267. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32268. };
  32269. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32270. /**
  32271. * Used to apply the vignette as a mix with the pixel color.
  32272. */
  32273. get: function () {
  32274. return this._VIGNETTEMODE_MULTIPLY;
  32275. },
  32276. enumerable: true,
  32277. configurable: true
  32278. });
  32279. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32280. /**
  32281. * Used to apply the vignette as a replacement of the pixel color.
  32282. */
  32283. get: function () {
  32284. return this._VIGNETTEMODE_OPAQUE;
  32285. },
  32286. enumerable: true,
  32287. configurable: true
  32288. });
  32289. // Static constants associated to the image processing.
  32290. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32291. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32292. __decorate([
  32293. BABYLON.serializeAsColorCurves()
  32294. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32295. __decorate([
  32296. BABYLON.serialize()
  32297. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32298. __decorate([
  32299. BABYLON.serializeAsTexture()
  32300. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32301. __decorate([
  32302. BABYLON.serialize()
  32303. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32304. __decorate([
  32305. BABYLON.serialize()
  32306. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32307. __decorate([
  32308. BABYLON.serialize()
  32309. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32310. __decorate([
  32311. BABYLON.serialize()
  32312. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32313. __decorate([
  32314. BABYLON.serialize()
  32315. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32316. __decorate([
  32317. BABYLON.serialize()
  32318. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32319. __decorate([
  32320. BABYLON.serialize()
  32321. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32322. __decorate([
  32323. BABYLON.serialize()
  32324. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32325. __decorate([
  32326. BABYLON.serialize()
  32327. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32328. __decorate([
  32329. BABYLON.serialize()
  32330. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32331. __decorate([
  32332. BABYLON.serializeAsColor4()
  32333. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32334. __decorate([
  32335. BABYLON.serialize()
  32336. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32337. __decorate([
  32338. BABYLON.serialize()
  32339. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32340. __decorate([
  32341. BABYLON.serialize()
  32342. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32343. __decorate([
  32344. BABYLON.serialize()
  32345. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32346. return ImageProcessingConfiguration;
  32347. }());
  32348. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  32349. })(BABYLON || (BABYLON = {}));
  32350. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  32351. var BABYLON;
  32352. (function (BABYLON) {
  32353. /**
  32354. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  32355. * It can help converting any input color in a desired output one. This can then be used to create effects
  32356. * from sepia, black and white to sixties or futuristic rendering...
  32357. *
  32358. * The only supported format is currently 3dl.
  32359. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  32360. */
  32361. var ColorGradingTexture = /** @class */ (function (_super) {
  32362. __extends(ColorGradingTexture, _super);
  32363. /**
  32364. * Instantiates a ColorGradingTexture from the following parameters.
  32365. *
  32366. * @param url The location of the color gradind data (currently only supporting 3dl)
  32367. * @param scene The scene the texture will be used in
  32368. */
  32369. function ColorGradingTexture(url, scene) {
  32370. var _this = _super.call(this, scene) || this;
  32371. if (!url) {
  32372. return _this;
  32373. }
  32374. _this._engine = scene.getEngine();
  32375. _this._textureMatrix = BABYLON.Matrix.Identity();
  32376. _this.name = url;
  32377. _this.url = url;
  32378. _this.hasAlpha = false;
  32379. _this.isCube = false;
  32380. _this.is3D = _this._engine.webGLVersion > 1;
  32381. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32382. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32383. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32384. _this.anisotropicFilteringLevel = 1;
  32385. _this._texture = _this._getFromCache(url, true);
  32386. if (!_this._texture) {
  32387. if (!scene.useDelayedTextureLoading) {
  32388. _this.loadTexture();
  32389. }
  32390. else {
  32391. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32392. }
  32393. }
  32394. return _this;
  32395. }
  32396. /**
  32397. * Returns the texture matrix used in most of the material.
  32398. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  32399. */
  32400. ColorGradingTexture.prototype.getTextureMatrix = function () {
  32401. return this._textureMatrix;
  32402. };
  32403. /**
  32404. * Occurs when the file being loaded is a .3dl LUT file.
  32405. */
  32406. ColorGradingTexture.prototype.load3dlTexture = function () {
  32407. var engine = this._engine;
  32408. var texture;
  32409. if (engine.webGLVersion === 1) {
  32410. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32411. }
  32412. else {
  32413. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32414. }
  32415. this._texture = texture;
  32416. var callback = function (text) {
  32417. var data = null;
  32418. var tempData = null;
  32419. var line;
  32420. var lines = text.split('\n');
  32421. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  32422. var maxColor = 0;
  32423. for (var i = 0; i < lines.length; i++) {
  32424. line = lines[i];
  32425. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  32426. continue;
  32427. if (line.indexOf('#') === 0)
  32428. continue;
  32429. var words = line.split(" ");
  32430. if (size === 0) {
  32431. // Number of space + one
  32432. size = words.length;
  32433. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  32434. tempData = new Float32Array(size * size * size * 4);
  32435. continue;
  32436. }
  32437. if (size != 0) {
  32438. var r = Math.max(parseInt(words[0]), 0);
  32439. var g = Math.max(parseInt(words[1]), 0);
  32440. var b = Math.max(parseInt(words[2]), 0);
  32441. maxColor = Math.max(r, maxColor);
  32442. maxColor = Math.max(g, maxColor);
  32443. maxColor = Math.max(b, maxColor);
  32444. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  32445. if (tempData) {
  32446. tempData[pixelStorageIndex + 0] = r;
  32447. tempData[pixelStorageIndex + 1] = g;
  32448. tempData[pixelStorageIndex + 2] = b;
  32449. }
  32450. pixelIndexSlice++;
  32451. if (pixelIndexSlice % size == 0) {
  32452. pixelIndexH++;
  32453. pixelIndexSlice = 0;
  32454. if (pixelIndexH % size == 0) {
  32455. pixelIndexW++;
  32456. pixelIndexH = 0;
  32457. }
  32458. }
  32459. }
  32460. }
  32461. if (tempData && data) {
  32462. for (var i = 0; i < tempData.length; i++) {
  32463. if (i > 0 && (i + 1) % 4 === 0) {
  32464. data[i] = 255;
  32465. }
  32466. else {
  32467. var value = tempData[i];
  32468. data[i] = (value / maxColor * 255);
  32469. }
  32470. }
  32471. }
  32472. if (texture.is3D) {
  32473. texture.updateSize(size, size, size);
  32474. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32475. }
  32476. else {
  32477. texture.updateSize(size * size, size);
  32478. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32479. }
  32480. };
  32481. BABYLON.Tools.LoadFile(this.url, callback);
  32482. return this._texture;
  32483. };
  32484. /**
  32485. * Starts the loading process of the texture.
  32486. */
  32487. ColorGradingTexture.prototype.loadTexture = function () {
  32488. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  32489. this.load3dlTexture();
  32490. }
  32491. };
  32492. /**
  32493. * Clones the color gradind texture.
  32494. */
  32495. ColorGradingTexture.prototype.clone = function () {
  32496. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  32497. // Base texture
  32498. newTexture.level = this.level;
  32499. return newTexture;
  32500. };
  32501. /**
  32502. * Called during delayed load for textures.
  32503. */
  32504. ColorGradingTexture.prototype.delayLoad = function () {
  32505. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32506. return;
  32507. }
  32508. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32509. this._texture = this._getFromCache(this.url, true);
  32510. if (!this._texture) {
  32511. this.loadTexture();
  32512. }
  32513. };
  32514. /**
  32515. * Parses a color grading texture serialized by Babylon.
  32516. * @param parsedTexture The texture information being parsedTexture
  32517. * @param scene The scene to load the texture in
  32518. * @param rootUrl The root url of the data assets to load
  32519. * @return A color gradind texture
  32520. */
  32521. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32522. var texture = null;
  32523. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  32524. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  32525. texture.name = parsedTexture.name;
  32526. texture.level = parsedTexture.level;
  32527. }
  32528. return texture;
  32529. };
  32530. /**
  32531. * Serializes the LUT texture to json format.
  32532. */
  32533. ColorGradingTexture.prototype.serialize = function () {
  32534. if (!this.name) {
  32535. return null;
  32536. }
  32537. var serializationObject = {};
  32538. serializationObject.name = this.name;
  32539. serializationObject.level = this.level;
  32540. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32541. return serializationObject;
  32542. };
  32543. /**
  32544. * Empty line regex stored for GC.
  32545. */
  32546. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32547. return ColorGradingTexture;
  32548. }(BABYLON.BaseTexture));
  32549. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32550. })(BABYLON || (BABYLON = {}));
  32551. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32552. var BABYLON;
  32553. (function (BABYLON) {
  32554. /**
  32555. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32556. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32557. * 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;
  32558. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32559. */
  32560. var ColorCurves = /** @class */ (function () {
  32561. function ColorCurves() {
  32562. this._dirty = true;
  32563. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32564. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32565. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32566. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32567. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32568. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32569. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32570. this._globalHue = 30;
  32571. this._globalDensity = 0;
  32572. this._globalSaturation = 0;
  32573. this._globalExposure = 0;
  32574. this._highlightsHue = 30;
  32575. this._highlightsDensity = 0;
  32576. this._highlightsSaturation = 0;
  32577. this._highlightsExposure = 0;
  32578. this._midtonesHue = 30;
  32579. this._midtonesDensity = 0;
  32580. this._midtonesSaturation = 0;
  32581. this._midtonesExposure = 0;
  32582. this._shadowsHue = 30;
  32583. this._shadowsDensity = 0;
  32584. this._shadowsSaturation = 0;
  32585. this._shadowsExposure = 0;
  32586. }
  32587. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32588. /**
  32589. * Gets the global Hue value.
  32590. * 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).
  32591. */
  32592. get: function () {
  32593. return this._globalHue;
  32594. },
  32595. /**
  32596. * Sets the global Hue value.
  32597. * 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).
  32598. */
  32599. set: function (value) {
  32600. this._globalHue = value;
  32601. this._dirty = true;
  32602. },
  32603. enumerable: true,
  32604. configurable: true
  32605. });
  32606. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32607. /**
  32608. * Gets the global Density value.
  32609. * 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.
  32610. * Values less than zero provide a filter of opposite hue.
  32611. */
  32612. get: function () {
  32613. return this._globalDensity;
  32614. },
  32615. /**
  32616. * Sets the global Density value.
  32617. * 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.
  32618. * Values less than zero provide a filter of opposite hue.
  32619. */
  32620. set: function (value) {
  32621. this._globalDensity = value;
  32622. this._dirty = true;
  32623. },
  32624. enumerable: true,
  32625. configurable: true
  32626. });
  32627. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32628. /**
  32629. * Gets the global Saturation value.
  32630. * 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.
  32631. */
  32632. get: function () {
  32633. return this._globalSaturation;
  32634. },
  32635. /**
  32636. * Sets the global Saturation value.
  32637. * 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.
  32638. */
  32639. set: function (value) {
  32640. this._globalSaturation = value;
  32641. this._dirty = true;
  32642. },
  32643. enumerable: true,
  32644. configurable: true
  32645. });
  32646. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32647. /**
  32648. * Gets the highlights Hue value.
  32649. * 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).
  32650. */
  32651. get: function () {
  32652. return this._highlightsHue;
  32653. },
  32654. /**
  32655. * Sets the highlights Hue value.
  32656. * 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).
  32657. */
  32658. set: function (value) {
  32659. this._highlightsHue = value;
  32660. this._dirty = true;
  32661. },
  32662. enumerable: true,
  32663. configurable: true
  32664. });
  32665. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32666. /**
  32667. * Gets the highlights Density value.
  32668. * 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.
  32669. * Values less than zero provide a filter of opposite hue.
  32670. */
  32671. get: function () {
  32672. return this._highlightsDensity;
  32673. },
  32674. /**
  32675. * Sets the highlights Density value.
  32676. * 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.
  32677. * Values less than zero provide a filter of opposite hue.
  32678. */
  32679. set: function (value) {
  32680. this._highlightsDensity = value;
  32681. this._dirty = true;
  32682. },
  32683. enumerable: true,
  32684. configurable: true
  32685. });
  32686. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  32687. /**
  32688. * Gets the highlights Saturation value.
  32689. * 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.
  32690. */
  32691. get: function () {
  32692. return this._highlightsSaturation;
  32693. },
  32694. /**
  32695. * Sets the highlights Saturation value.
  32696. * 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.
  32697. */
  32698. set: function (value) {
  32699. this._highlightsSaturation = value;
  32700. this._dirty = true;
  32701. },
  32702. enumerable: true,
  32703. configurable: true
  32704. });
  32705. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  32706. /**
  32707. * Gets the highlights Exposure value.
  32708. * 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.
  32709. */
  32710. get: function () {
  32711. return this._highlightsExposure;
  32712. },
  32713. /**
  32714. * Sets the highlights Exposure value.
  32715. * 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.
  32716. */
  32717. set: function (value) {
  32718. this._highlightsExposure = value;
  32719. this._dirty = true;
  32720. },
  32721. enumerable: true,
  32722. configurable: true
  32723. });
  32724. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  32725. /**
  32726. * Gets the midtones Hue value.
  32727. * 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).
  32728. */
  32729. get: function () {
  32730. return this._midtonesHue;
  32731. },
  32732. /**
  32733. * Sets the midtones Hue value.
  32734. * 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).
  32735. */
  32736. set: function (value) {
  32737. this._midtonesHue = value;
  32738. this._dirty = true;
  32739. },
  32740. enumerable: true,
  32741. configurable: true
  32742. });
  32743. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  32744. /**
  32745. * Gets the midtones Density value.
  32746. * 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.
  32747. * Values less than zero provide a filter of opposite hue.
  32748. */
  32749. get: function () {
  32750. return this._midtonesDensity;
  32751. },
  32752. /**
  32753. * Sets the midtones Density value.
  32754. * 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.
  32755. * Values less than zero provide a filter of opposite hue.
  32756. */
  32757. set: function (value) {
  32758. this._midtonesDensity = value;
  32759. this._dirty = true;
  32760. },
  32761. enumerable: true,
  32762. configurable: true
  32763. });
  32764. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  32765. /**
  32766. * Gets the midtones Saturation value.
  32767. * 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.
  32768. */
  32769. get: function () {
  32770. return this._midtonesSaturation;
  32771. },
  32772. /**
  32773. * Sets the midtones Saturation value.
  32774. * 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.
  32775. */
  32776. set: function (value) {
  32777. this._midtonesSaturation = value;
  32778. this._dirty = true;
  32779. },
  32780. enumerable: true,
  32781. configurable: true
  32782. });
  32783. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  32784. /**
  32785. * Gets the midtones Exposure value.
  32786. * 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.
  32787. */
  32788. get: function () {
  32789. return this._midtonesExposure;
  32790. },
  32791. /**
  32792. * Sets the midtones Exposure value.
  32793. * 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.
  32794. */
  32795. set: function (value) {
  32796. this._midtonesExposure = value;
  32797. this._dirty = true;
  32798. },
  32799. enumerable: true,
  32800. configurable: true
  32801. });
  32802. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  32803. /**
  32804. * Gets the shadows Hue value.
  32805. * 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).
  32806. */
  32807. get: function () {
  32808. return this._shadowsHue;
  32809. },
  32810. /**
  32811. * Sets the shadows Hue value.
  32812. * 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).
  32813. */
  32814. set: function (value) {
  32815. this._shadowsHue = value;
  32816. this._dirty = true;
  32817. },
  32818. enumerable: true,
  32819. configurable: true
  32820. });
  32821. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  32822. /**
  32823. * Gets the shadows Density value.
  32824. * 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.
  32825. * Values less than zero provide a filter of opposite hue.
  32826. */
  32827. get: function () {
  32828. return this._shadowsDensity;
  32829. },
  32830. /**
  32831. * Sets the shadows Density value.
  32832. * 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.
  32833. * Values less than zero provide a filter of opposite hue.
  32834. */
  32835. set: function (value) {
  32836. this._shadowsDensity = value;
  32837. this._dirty = true;
  32838. },
  32839. enumerable: true,
  32840. configurable: true
  32841. });
  32842. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  32843. /**
  32844. * Gets the shadows Saturation value.
  32845. * 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.
  32846. */
  32847. get: function () {
  32848. return this._shadowsSaturation;
  32849. },
  32850. /**
  32851. * Sets the shadows Saturation value.
  32852. * 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.
  32853. */
  32854. set: function (value) {
  32855. this._shadowsSaturation = value;
  32856. this._dirty = true;
  32857. },
  32858. enumerable: true,
  32859. configurable: true
  32860. });
  32861. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  32862. /**
  32863. * Gets the shadows Exposure value.
  32864. * 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.
  32865. */
  32866. get: function () {
  32867. return this._shadowsExposure;
  32868. },
  32869. /**
  32870. * Sets the shadows Exposure value.
  32871. * 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.
  32872. */
  32873. set: function (value) {
  32874. this._shadowsExposure = value;
  32875. this._dirty = true;
  32876. },
  32877. enumerable: true,
  32878. configurable: true
  32879. });
  32880. ColorCurves.prototype.getClassName = function () {
  32881. return "ColorCurves";
  32882. };
  32883. /**
  32884. * Binds the color curves to the shader.
  32885. * @param colorCurves The color curve to bind
  32886. * @param effect The effect to bind to
  32887. */
  32888. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  32889. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  32890. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  32891. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  32892. if (colorCurves._dirty) {
  32893. colorCurves._dirty = false;
  32894. // Fill in global info.
  32895. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  32896. // Compute highlights info.
  32897. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  32898. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  32899. // Compute midtones info.
  32900. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  32901. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  32902. // Compute shadows info.
  32903. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  32904. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  32905. // Compute deltas (neutral is midtones).
  32906. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  32907. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  32908. }
  32909. if (effect) {
  32910. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  32911. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  32912. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  32913. }
  32914. };
  32915. /**
  32916. * Prepare the list of uniforms associated with the ColorCurves effects.
  32917. * @param uniformsList The list of uniforms used in the effect
  32918. */
  32919. ColorCurves.PrepareUniforms = function (uniformsList) {
  32920. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  32921. };
  32922. /**
  32923. * Returns color grading data based on a hue, density, saturation and exposure value.
  32924. * @param filterHue The hue of the color filter.
  32925. * @param filterDensity The density of the color filter.
  32926. * @param saturation The saturation.
  32927. * @param exposure The exposure.
  32928. * @param result The result data container.
  32929. */
  32930. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  32931. if (hue == null) {
  32932. return;
  32933. }
  32934. hue = ColorCurves.clamp(hue, 0, 360);
  32935. density = ColorCurves.clamp(density, -100, 100);
  32936. saturation = ColorCurves.clamp(saturation, -100, 100);
  32937. exposure = ColorCurves.clamp(exposure, -100, 100);
  32938. // Remap the slider/config filter density with non-linear mapping and also scale by half
  32939. // so that the maximum filter density is only 50% control. This provides fine control
  32940. // for small values and reasonable range.
  32941. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  32942. density *= 0.5;
  32943. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  32944. if (density < 0) {
  32945. density *= -1;
  32946. hue = (hue + 180) % 360;
  32947. }
  32948. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  32949. result.scaleToRef(2, result);
  32950. result.a = 1 + 0.01 * saturation;
  32951. };
  32952. /**
  32953. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  32954. * @param value The input slider value in range [-100,100].
  32955. * @returns Adjusted value.
  32956. */
  32957. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  32958. value /= 100;
  32959. var x = Math.abs(value);
  32960. x = Math.pow(x, 2);
  32961. if (value < 0) {
  32962. x *= -1;
  32963. }
  32964. x *= 100;
  32965. return x;
  32966. };
  32967. /**
  32968. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  32969. * @param hue The hue (H) input.
  32970. * @param saturation The saturation (S) input.
  32971. * @param brightness The brightness (B) input.
  32972. * @result An RGBA color represented as Vector4.
  32973. */
  32974. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  32975. var h = ColorCurves.clamp(hue, 0, 360);
  32976. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  32977. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  32978. if (s === 0) {
  32979. result.r = v;
  32980. result.g = v;
  32981. result.b = v;
  32982. }
  32983. else {
  32984. // sector 0 to 5
  32985. h /= 60;
  32986. var i = Math.floor(h);
  32987. // fractional part of h
  32988. var f = h - i;
  32989. var p = v * (1 - s);
  32990. var q = v * (1 - s * f);
  32991. var t = v * (1 - s * (1 - f));
  32992. switch (i) {
  32993. case 0:
  32994. result.r = v;
  32995. result.g = t;
  32996. result.b = p;
  32997. break;
  32998. case 1:
  32999. result.r = q;
  33000. result.g = v;
  33001. result.b = p;
  33002. break;
  33003. case 2:
  33004. result.r = p;
  33005. result.g = v;
  33006. result.b = t;
  33007. break;
  33008. case 3:
  33009. result.r = p;
  33010. result.g = q;
  33011. result.b = v;
  33012. break;
  33013. case 4:
  33014. result.r = t;
  33015. result.g = p;
  33016. result.b = v;
  33017. break;
  33018. default:// case 5:
  33019. result.r = v;
  33020. result.g = p;
  33021. result.b = q;
  33022. break;
  33023. }
  33024. }
  33025. result.a = 1;
  33026. };
  33027. /**
  33028. * Returns a value clamped between min and max
  33029. * @param value The value to clamp
  33030. * @param min The minimum of value
  33031. * @param max The maximum of value
  33032. * @returns The clamped value.
  33033. */
  33034. ColorCurves.clamp = function (value, min, max) {
  33035. return Math.min(Math.max(value, min), max);
  33036. };
  33037. /**
  33038. * Clones the current color curve instance.
  33039. * @return The cloned curves
  33040. */
  33041. ColorCurves.prototype.clone = function () {
  33042. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33043. };
  33044. /**
  33045. * Serializes the current color curve instance to a json representation.
  33046. * @return a JSON representation
  33047. */
  33048. ColorCurves.prototype.serialize = function () {
  33049. return BABYLON.SerializationHelper.Serialize(this);
  33050. };
  33051. /**
  33052. * Parses the color curve from a json representation.
  33053. * @param source the JSON source to parse
  33054. * @return The parsed curves
  33055. */
  33056. ColorCurves.Parse = function (source) {
  33057. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33058. };
  33059. __decorate([
  33060. BABYLON.serialize()
  33061. ], ColorCurves.prototype, "_globalHue", void 0);
  33062. __decorate([
  33063. BABYLON.serialize()
  33064. ], ColorCurves.prototype, "_globalDensity", void 0);
  33065. __decorate([
  33066. BABYLON.serialize()
  33067. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33068. __decorate([
  33069. BABYLON.serialize()
  33070. ], ColorCurves.prototype, "_globalExposure", void 0);
  33071. __decorate([
  33072. BABYLON.serialize()
  33073. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33074. __decorate([
  33075. BABYLON.serialize()
  33076. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33077. __decorate([
  33078. BABYLON.serialize()
  33079. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33080. __decorate([
  33081. BABYLON.serialize()
  33082. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33083. __decorate([
  33084. BABYLON.serialize()
  33085. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33086. __decorate([
  33087. BABYLON.serialize()
  33088. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33089. __decorate([
  33090. BABYLON.serialize()
  33091. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33092. __decorate([
  33093. BABYLON.serialize()
  33094. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33095. return ColorCurves;
  33096. }());
  33097. BABYLON.ColorCurves = ColorCurves;
  33098. })(BABYLON || (BABYLON = {}));
  33099. //# sourceMappingURL=babylon.colorCurves.js.map
  33100. var BABYLON;
  33101. (function (BABYLON) {
  33102. var StandardMaterialDefines = /** @class */ (function (_super) {
  33103. __extends(StandardMaterialDefines, _super);
  33104. function StandardMaterialDefines() {
  33105. var _this = _super.call(this) || this;
  33106. _this.MAINUV1 = false;
  33107. _this.MAINUV2 = false;
  33108. _this.DIFFUSE = false;
  33109. _this.DIFFUSEDIRECTUV = 0;
  33110. _this.AMBIENT = false;
  33111. _this.AMBIENTDIRECTUV = 0;
  33112. _this.OPACITY = false;
  33113. _this.OPACITYDIRECTUV = 0;
  33114. _this.OPACITYRGB = false;
  33115. _this.REFLECTION = false;
  33116. _this.EMISSIVE = false;
  33117. _this.EMISSIVEDIRECTUV = 0;
  33118. _this.SPECULAR = false;
  33119. _this.SPECULARDIRECTUV = 0;
  33120. _this.BUMP = false;
  33121. _this.BUMPDIRECTUV = 0;
  33122. _this.PARALLAX = false;
  33123. _this.PARALLAXOCCLUSION = false;
  33124. _this.SPECULAROVERALPHA = false;
  33125. _this.CLIPPLANE = false;
  33126. _this.ALPHATEST = false;
  33127. _this.DEPTHPREPASS = false;
  33128. _this.ALPHAFROMDIFFUSE = false;
  33129. _this.POINTSIZE = false;
  33130. _this.FOG = false;
  33131. _this.SPECULARTERM = false;
  33132. _this.DIFFUSEFRESNEL = false;
  33133. _this.OPACITYFRESNEL = false;
  33134. _this.REFLECTIONFRESNEL = false;
  33135. _this.REFRACTIONFRESNEL = false;
  33136. _this.EMISSIVEFRESNEL = false;
  33137. _this.FRESNEL = false;
  33138. _this.NORMAL = false;
  33139. _this.UV1 = false;
  33140. _this.UV2 = false;
  33141. _this.VERTEXCOLOR = false;
  33142. _this.VERTEXALPHA = false;
  33143. _this.NUM_BONE_INFLUENCERS = 0;
  33144. _this.BonesPerMesh = 0;
  33145. _this.INSTANCES = false;
  33146. _this.GLOSSINESS = false;
  33147. _this.ROUGHNESS = false;
  33148. _this.EMISSIVEASILLUMINATION = false;
  33149. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33150. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33151. _this.LIGHTMAP = false;
  33152. _this.LIGHTMAPDIRECTUV = 0;
  33153. _this.USELIGHTMAPASSHADOWMAP = false;
  33154. _this.REFLECTIONMAP_3D = false;
  33155. _this.REFLECTIONMAP_SPHERICAL = false;
  33156. _this.REFLECTIONMAP_PLANAR = false;
  33157. _this.REFLECTIONMAP_CUBIC = false;
  33158. _this.REFLECTIONMAP_PROJECTION = false;
  33159. _this.REFLECTIONMAP_SKYBOX = false;
  33160. _this.REFLECTIONMAP_EXPLICIT = false;
  33161. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33162. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33163. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33164. _this.INVERTCUBICMAP = false;
  33165. _this.LOGARITHMICDEPTH = false;
  33166. _this.REFRACTION = false;
  33167. _this.REFRACTIONMAP_3D = false;
  33168. _this.REFLECTIONOVERALPHA = false;
  33169. _this.TWOSIDEDLIGHTING = false;
  33170. _this.SHADOWFLOAT = false;
  33171. _this.MORPHTARGETS = false;
  33172. _this.MORPHTARGETS_NORMAL = false;
  33173. _this.MORPHTARGETS_TANGENT = false;
  33174. _this.NUM_MORPH_INFLUENCERS = 0;
  33175. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33176. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33177. _this.IMAGEPROCESSING = false;
  33178. _this.VIGNETTE = false;
  33179. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33180. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33181. _this.TONEMAPPING = false;
  33182. _this.CONTRAST = false;
  33183. _this.COLORCURVES = false;
  33184. _this.COLORGRADING = false;
  33185. _this.COLORGRADING3D = false;
  33186. _this.SAMPLER3DGREENDEPTH = false;
  33187. _this.SAMPLER3DBGRMAP = false;
  33188. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33189. _this.EXPOSURE = false;
  33190. _this.rebuild();
  33191. return _this;
  33192. }
  33193. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33194. var modes = [
  33195. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33196. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33197. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33198. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33199. ];
  33200. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33201. var mode = modes_1[_i];
  33202. this[mode] = (mode === modeToEnable);
  33203. }
  33204. };
  33205. return StandardMaterialDefines;
  33206. }(BABYLON.MaterialDefines));
  33207. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33208. var StandardMaterial = /** @class */ (function (_super) {
  33209. __extends(StandardMaterial, _super);
  33210. function StandardMaterial(name, scene) {
  33211. var _this = _super.call(this, name, scene) || this;
  33212. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33213. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33214. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33215. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33216. _this.specularPower = 64;
  33217. _this._useAlphaFromDiffuseTexture = false;
  33218. _this._useEmissiveAsIllumination = false;
  33219. _this._linkEmissiveWithDiffuse = false;
  33220. _this._useSpecularOverAlpha = false;
  33221. _this._useReflectionOverAlpha = false;
  33222. _this._disableLighting = false;
  33223. _this._useParallax = false;
  33224. _this._useParallaxOcclusion = false;
  33225. _this.parallaxScaleBias = 0.05;
  33226. _this._roughness = 0;
  33227. _this.indexOfRefraction = 0.98;
  33228. _this.invertRefractionY = true;
  33229. _this._useLightmapAsShadowmap = false;
  33230. _this._useReflectionFresnelFromSpecular = false;
  33231. _this._useGlossinessFromSpecularMapAlpha = false;
  33232. _this._maxSimultaneousLights = 4;
  33233. /**
  33234. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33235. */
  33236. _this._invertNormalMapX = false;
  33237. /**
  33238. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33239. */
  33240. _this._invertNormalMapY = false;
  33241. /**
  33242. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33243. */
  33244. _this._twoSidedLighting = false;
  33245. _this._renderTargets = new BABYLON.SmartArray(16);
  33246. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33247. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33248. // Setup the default processing configuration to the scene.
  33249. _this._attachImageProcessingConfiguration(null);
  33250. _this.getRenderTargetTextures = function () {
  33251. _this._renderTargets.reset();
  33252. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33253. _this._renderTargets.push(_this._reflectionTexture);
  33254. }
  33255. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33256. _this._renderTargets.push(_this._refractionTexture);
  33257. }
  33258. return _this._renderTargets;
  33259. };
  33260. return _this;
  33261. }
  33262. ;
  33263. ;
  33264. ;
  33265. ;
  33266. ;
  33267. ;
  33268. ;
  33269. ;
  33270. ;
  33271. ;
  33272. ;
  33273. ;
  33274. ;
  33275. ;
  33276. ;
  33277. ;
  33278. ;
  33279. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33280. /**
  33281. * Gets the image processing configuration used either in this material.
  33282. */
  33283. get: function () {
  33284. return this._imageProcessingConfiguration;
  33285. },
  33286. /**
  33287. * Sets the Default image processing configuration used either in the this material.
  33288. *
  33289. * If sets to null, the scene one is in use.
  33290. */
  33291. set: function (value) {
  33292. this._attachImageProcessingConfiguration(value);
  33293. // Ensure the effect will be rebuilt.
  33294. this._markAllSubMeshesAsTexturesDirty();
  33295. },
  33296. enumerable: true,
  33297. configurable: true
  33298. });
  33299. /**
  33300. * Attaches a new image processing configuration to the Standard Material.
  33301. * @param configuration
  33302. */
  33303. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33304. var _this = this;
  33305. if (configuration === this._imageProcessingConfiguration) {
  33306. return;
  33307. }
  33308. // Detaches observer.
  33309. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33310. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33311. }
  33312. // Pick the scene configuration if needed.
  33313. if (!configuration) {
  33314. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33315. }
  33316. else {
  33317. this._imageProcessingConfiguration = configuration;
  33318. }
  33319. // Attaches observer.
  33320. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33321. _this._markAllSubMeshesAsImageProcessingDirty();
  33322. });
  33323. };
  33324. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33325. /**
  33326. * Gets wether the color curves effect is enabled.
  33327. */
  33328. get: function () {
  33329. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33330. },
  33331. /**
  33332. * Sets wether the color curves effect is enabled.
  33333. */
  33334. set: function (value) {
  33335. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33336. },
  33337. enumerable: true,
  33338. configurable: true
  33339. });
  33340. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33341. /**
  33342. * Gets wether the color grading effect is enabled.
  33343. */
  33344. get: function () {
  33345. return this.imageProcessingConfiguration.colorGradingEnabled;
  33346. },
  33347. /**
  33348. * Gets wether the color grading effect is enabled.
  33349. */
  33350. set: function (value) {
  33351. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33352. },
  33353. enumerable: true,
  33354. configurable: true
  33355. });
  33356. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  33357. /**
  33358. * Gets wether tonemapping is enabled or not.
  33359. */
  33360. get: function () {
  33361. return this._imageProcessingConfiguration.toneMappingEnabled;
  33362. },
  33363. /**
  33364. * Sets wether tonemapping is enabled or not
  33365. */
  33366. set: function (value) {
  33367. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33368. },
  33369. enumerable: true,
  33370. configurable: true
  33371. });
  33372. ;
  33373. ;
  33374. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  33375. /**
  33376. * The camera exposure used on this material.
  33377. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33378. * This corresponds to a photographic exposure.
  33379. */
  33380. get: function () {
  33381. return this._imageProcessingConfiguration.exposure;
  33382. },
  33383. /**
  33384. * The camera exposure used on this material.
  33385. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33386. * This corresponds to a photographic exposure.
  33387. */
  33388. set: function (value) {
  33389. this._imageProcessingConfiguration.exposure = value;
  33390. },
  33391. enumerable: true,
  33392. configurable: true
  33393. });
  33394. ;
  33395. ;
  33396. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  33397. /**
  33398. * Gets The camera contrast used on this material.
  33399. */
  33400. get: function () {
  33401. return this._imageProcessingConfiguration.contrast;
  33402. },
  33403. /**
  33404. * Sets The camera contrast used on this material.
  33405. */
  33406. set: function (value) {
  33407. this._imageProcessingConfiguration.contrast = value;
  33408. },
  33409. enumerable: true,
  33410. configurable: true
  33411. });
  33412. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  33413. /**
  33414. * Gets the Color Grading 2D Lookup Texture.
  33415. */
  33416. get: function () {
  33417. return this._imageProcessingConfiguration.colorGradingTexture;
  33418. },
  33419. /**
  33420. * Sets the Color Grading 2D Lookup Texture.
  33421. */
  33422. set: function (value) {
  33423. this._imageProcessingConfiguration.colorGradingTexture = value;
  33424. },
  33425. enumerable: true,
  33426. configurable: true
  33427. });
  33428. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  33429. /**
  33430. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33431. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33432. * 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;
  33433. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33434. */
  33435. get: function () {
  33436. return this._imageProcessingConfiguration.colorCurves;
  33437. },
  33438. /**
  33439. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33440. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33441. * 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;
  33442. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33443. */
  33444. set: function (value) {
  33445. this._imageProcessingConfiguration.colorCurves = value;
  33446. },
  33447. enumerable: true,
  33448. configurable: true
  33449. });
  33450. StandardMaterial.prototype.getClassName = function () {
  33451. return "StandardMaterial";
  33452. };
  33453. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  33454. get: function () {
  33455. return this._useLogarithmicDepth;
  33456. },
  33457. set: function (value) {
  33458. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33459. this._markAllSubMeshesAsMiscDirty();
  33460. },
  33461. enumerable: true,
  33462. configurable: true
  33463. });
  33464. StandardMaterial.prototype.needAlphaBlending = function () {
  33465. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  33466. };
  33467. StandardMaterial.prototype.needAlphaTesting = function () {
  33468. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  33469. };
  33470. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  33471. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  33472. };
  33473. StandardMaterial.prototype.getAlphaTestTexture = function () {
  33474. return this._diffuseTexture;
  33475. };
  33476. /**
  33477. * Child classes can use it to update shaders
  33478. */
  33479. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33480. if (useInstances === void 0) { useInstances = false; }
  33481. if (subMesh.effect && this.isFrozen) {
  33482. if (this._wasPreviouslyReady && subMesh.effect) {
  33483. return true;
  33484. }
  33485. }
  33486. if (!subMesh._materialDefines) {
  33487. subMesh._materialDefines = new StandardMaterialDefines();
  33488. }
  33489. var scene = this.getScene();
  33490. var defines = subMesh._materialDefines;
  33491. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33492. if (defines._renderId === scene.getRenderId()) {
  33493. return true;
  33494. }
  33495. }
  33496. var engine = scene.getEngine();
  33497. // Lights
  33498. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33499. // Textures
  33500. if (defines._areTexturesDirty) {
  33501. defines._needUVs = false;
  33502. defines.MAINUV1 = false;
  33503. defines.MAINUV2 = false;
  33504. if (scene.texturesEnabled) {
  33505. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33506. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  33507. return false;
  33508. }
  33509. else {
  33510. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  33511. }
  33512. }
  33513. else {
  33514. defines.DIFFUSE = false;
  33515. }
  33516. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33517. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33518. return false;
  33519. }
  33520. else {
  33521. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33522. }
  33523. }
  33524. else {
  33525. defines.AMBIENT = false;
  33526. }
  33527. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33528. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33529. return false;
  33530. }
  33531. else {
  33532. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33533. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33534. }
  33535. }
  33536. else {
  33537. defines.OPACITY = false;
  33538. }
  33539. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33540. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  33541. return false;
  33542. }
  33543. else {
  33544. defines._needNormals = true;
  33545. defines.REFLECTION = true;
  33546. defines.ROUGHNESS = (this._roughness > 0);
  33547. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  33548. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  33549. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  33550. switch (this._reflectionTexture.coordinatesMode) {
  33551. case BABYLON.Texture.CUBIC_MODE:
  33552. case BABYLON.Texture.INVCUBIC_MODE:
  33553. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33554. break;
  33555. case BABYLON.Texture.EXPLICIT_MODE:
  33556. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33557. break;
  33558. case BABYLON.Texture.PLANAR_MODE:
  33559. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33560. break;
  33561. case BABYLON.Texture.PROJECTION_MODE:
  33562. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33563. break;
  33564. case BABYLON.Texture.SKYBOX_MODE:
  33565. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33566. break;
  33567. case BABYLON.Texture.SPHERICAL_MODE:
  33568. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33569. break;
  33570. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33571. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33572. break;
  33573. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33574. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33575. break;
  33576. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33577. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33578. break;
  33579. }
  33580. }
  33581. }
  33582. else {
  33583. defines.REFLECTION = false;
  33584. }
  33585. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33586. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33587. return false;
  33588. }
  33589. else {
  33590. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33591. }
  33592. }
  33593. else {
  33594. defines.EMISSIVE = false;
  33595. }
  33596. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33597. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33598. return false;
  33599. }
  33600. else {
  33601. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33602. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33603. }
  33604. }
  33605. else {
  33606. defines.LIGHTMAP = false;
  33607. }
  33608. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33609. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33610. return false;
  33611. }
  33612. else {
  33613. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33614. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33615. }
  33616. }
  33617. else {
  33618. defines.SPECULAR = false;
  33619. }
  33620. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33621. // Bump texure can not be not blocking.
  33622. if (!this._bumpTexture.isReady()) {
  33623. return false;
  33624. }
  33625. else {
  33626. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33627. defines.PARALLAX = this._useParallax;
  33628. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33629. }
  33630. }
  33631. else {
  33632. defines.BUMP = false;
  33633. }
  33634. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33635. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33636. return false;
  33637. }
  33638. else {
  33639. defines._needUVs = true;
  33640. defines.REFRACTION = true;
  33641. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33642. }
  33643. }
  33644. else {
  33645. defines.REFRACTION = false;
  33646. }
  33647. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33648. }
  33649. else {
  33650. defines.DIFFUSE = false;
  33651. defines.AMBIENT = false;
  33652. defines.OPACITY = false;
  33653. defines.REFLECTION = false;
  33654. defines.EMISSIVE = false;
  33655. defines.LIGHTMAP = false;
  33656. defines.BUMP = false;
  33657. defines.REFRACTION = false;
  33658. }
  33659. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33660. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33661. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33662. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33663. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33664. }
  33665. if (defines._areImageProcessingDirty) {
  33666. if (!this._imageProcessingConfiguration.isReady()) {
  33667. return false;
  33668. }
  33669. this._imageProcessingConfiguration.prepareDefines(defines);
  33670. }
  33671. if (defines._areFresnelDirty) {
  33672. if (StandardMaterial.FresnelEnabled) {
  33673. // Fresnel
  33674. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33675. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  33676. this._reflectionFresnelParameters) {
  33677. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  33678. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  33679. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  33680. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  33681. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  33682. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  33683. defines._needNormals = true;
  33684. defines.FRESNEL = true;
  33685. }
  33686. }
  33687. else {
  33688. defines.FRESNEL = false;
  33689. }
  33690. }
  33691. // Misc.
  33692. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  33693. // Attribs
  33694. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  33695. // Values that need to be evaluated on every frame
  33696. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  33697. // Get correct effect
  33698. if (defines.isDirty) {
  33699. defines.markAsProcessed();
  33700. scene.resetCachedMaterial();
  33701. // Fallbacks
  33702. var fallbacks = new BABYLON.EffectFallbacks();
  33703. if (defines.REFLECTION) {
  33704. fallbacks.addFallback(0, "REFLECTION");
  33705. }
  33706. if (defines.SPECULAR) {
  33707. fallbacks.addFallback(0, "SPECULAR");
  33708. }
  33709. if (defines.BUMP) {
  33710. fallbacks.addFallback(0, "BUMP");
  33711. }
  33712. if (defines.PARALLAX) {
  33713. fallbacks.addFallback(1, "PARALLAX");
  33714. }
  33715. if (defines.PARALLAXOCCLUSION) {
  33716. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  33717. }
  33718. if (defines.SPECULAROVERALPHA) {
  33719. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  33720. }
  33721. if (defines.FOG) {
  33722. fallbacks.addFallback(1, "FOG");
  33723. }
  33724. if (defines.POINTSIZE) {
  33725. fallbacks.addFallback(0, "POINTSIZE");
  33726. }
  33727. if (defines.LOGARITHMICDEPTH) {
  33728. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  33729. }
  33730. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  33731. if (defines.SPECULARTERM) {
  33732. fallbacks.addFallback(0, "SPECULARTERM");
  33733. }
  33734. if (defines.DIFFUSEFRESNEL) {
  33735. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  33736. }
  33737. if (defines.OPACITYFRESNEL) {
  33738. fallbacks.addFallback(2, "OPACITYFRESNEL");
  33739. }
  33740. if (defines.REFLECTIONFRESNEL) {
  33741. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  33742. }
  33743. if (defines.EMISSIVEFRESNEL) {
  33744. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  33745. }
  33746. if (defines.FRESNEL) {
  33747. fallbacks.addFallback(4, "FRESNEL");
  33748. }
  33749. //Attributes
  33750. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33751. if (defines.NORMAL) {
  33752. attribs.push(BABYLON.VertexBuffer.NormalKind);
  33753. }
  33754. if (defines.UV1) {
  33755. attribs.push(BABYLON.VertexBuffer.UVKind);
  33756. }
  33757. if (defines.UV2) {
  33758. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33759. }
  33760. if (defines.VERTEXCOLOR) {
  33761. attribs.push(BABYLON.VertexBuffer.ColorKind);
  33762. }
  33763. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  33764. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  33765. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  33766. var shaderName = "default";
  33767. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  33768. "vFogInfos", "vFogColor", "pointSize",
  33769. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  33770. "mBones",
  33771. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  33772. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  33773. "logarithmicDepthConstant", "vTangentSpaceParams"
  33774. ];
  33775. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  33776. var uniformBuffers = ["Material", "Scene"];
  33777. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  33778. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  33779. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  33780. uniformsNames: uniforms,
  33781. uniformBuffersNames: uniformBuffers,
  33782. samplers: samplers,
  33783. defines: defines,
  33784. maxSimultaneousLights: this._maxSimultaneousLights
  33785. });
  33786. if (this.customShaderNameResolve) {
  33787. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  33788. }
  33789. var join = defines.toString();
  33790. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  33791. attributes: attribs,
  33792. uniformsNames: uniforms,
  33793. uniformBuffersNames: uniformBuffers,
  33794. samplers: samplers,
  33795. defines: join,
  33796. fallbacks: fallbacks,
  33797. onCompiled: this.onCompiled,
  33798. onError: this.onError,
  33799. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  33800. }, engine), defines);
  33801. this.buildUniformLayout();
  33802. }
  33803. if (!subMesh.effect || !subMesh.effect.isReady()) {
  33804. return false;
  33805. }
  33806. defines._renderId = scene.getRenderId();
  33807. this._wasPreviouslyReady = true;
  33808. return true;
  33809. };
  33810. StandardMaterial.prototype.buildUniformLayout = function () {
  33811. // Order is important !
  33812. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  33813. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  33814. this._uniformBuffer.addUniform("opacityParts", 4);
  33815. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  33816. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  33817. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  33818. this._uniformBuffer.addUniform("refractionRightColor", 4);
  33819. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  33820. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  33821. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  33822. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  33823. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  33824. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  33825. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  33826. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  33827. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  33828. this._uniformBuffer.addUniform("vBumpInfos", 3);
  33829. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  33830. this._uniformBuffer.addUniform("ambientMatrix", 16);
  33831. this._uniformBuffer.addUniform("opacityMatrix", 16);
  33832. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  33833. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  33834. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  33835. this._uniformBuffer.addUniform("specularMatrix", 16);
  33836. this._uniformBuffer.addUniform("bumpMatrix", 16);
  33837. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  33838. this._uniformBuffer.addUniform("refractionMatrix", 16);
  33839. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  33840. this._uniformBuffer.addUniform("vSpecularColor", 4);
  33841. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  33842. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  33843. this._uniformBuffer.addUniform("pointSize", 1);
  33844. this._uniformBuffer.create();
  33845. };
  33846. StandardMaterial.prototype.unbind = function () {
  33847. if (this._activeEffect) {
  33848. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  33849. this._activeEffect.setTexture("reflection2DSampler", null);
  33850. }
  33851. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  33852. this._activeEffect.setTexture("refraction2DSampler", null);
  33853. }
  33854. }
  33855. _super.prototype.unbind.call(this);
  33856. };
  33857. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  33858. var scene = this.getScene();
  33859. var defines = subMesh._materialDefines;
  33860. if (!defines) {
  33861. return;
  33862. }
  33863. var effect = subMesh.effect;
  33864. if (!effect) {
  33865. return;
  33866. }
  33867. this._activeEffect = effect;
  33868. // Matrices
  33869. this.bindOnlyWorldMatrix(world);
  33870. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  33871. // Bones
  33872. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  33873. if (mustRebind) {
  33874. this._uniformBuffer.bindToEffect(effect, "Material");
  33875. this.bindViewProjection(effect);
  33876. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  33877. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  33878. // Fresnel
  33879. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  33880. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  33881. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  33882. }
  33883. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  33884. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  33885. }
  33886. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  33887. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  33888. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  33889. }
  33890. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  33891. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  33892. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  33893. }
  33894. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  33895. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  33896. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  33897. }
  33898. }
  33899. // Textures
  33900. if (scene.texturesEnabled) {
  33901. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33902. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  33903. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  33904. }
  33905. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33906. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  33907. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  33908. }
  33909. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33910. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  33911. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  33912. }
  33913. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33914. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  33915. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  33916. }
  33917. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33918. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  33919. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  33920. }
  33921. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33922. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  33923. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  33924. }
  33925. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33926. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  33927. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  33928. }
  33929. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  33930. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  33931. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  33932. if (scene._mirroredCameraPosition) {
  33933. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  33934. }
  33935. else {
  33936. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  33937. }
  33938. }
  33939. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33940. var depth = 1.0;
  33941. if (!this._refractionTexture.isCube) {
  33942. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  33943. if (this._refractionTexture.depth) {
  33944. depth = this._refractionTexture.depth;
  33945. }
  33946. }
  33947. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  33948. }
  33949. }
  33950. // Point size
  33951. if (this.pointsCloud) {
  33952. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  33953. }
  33954. if (defines.SPECULARTERM) {
  33955. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  33956. }
  33957. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  33958. // Diffuse
  33959. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  33960. }
  33961. // Textures
  33962. if (scene.texturesEnabled) {
  33963. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33964. effect.setTexture("diffuseSampler", this._diffuseTexture);
  33965. }
  33966. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33967. effect.setTexture("ambientSampler", this._ambientTexture);
  33968. }
  33969. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33970. effect.setTexture("opacitySampler", this._opacityTexture);
  33971. }
  33972. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33973. if (this._reflectionTexture.isCube) {
  33974. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  33975. }
  33976. else {
  33977. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  33978. }
  33979. }
  33980. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33981. effect.setTexture("emissiveSampler", this._emissiveTexture);
  33982. }
  33983. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33984. effect.setTexture("lightmapSampler", this._lightmapTexture);
  33985. }
  33986. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33987. effect.setTexture("specularSampler", this._specularTexture);
  33988. }
  33989. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  33990. effect.setTexture("bumpSampler", this._bumpTexture);
  33991. }
  33992. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33993. var depth = 1.0;
  33994. if (this._refractionTexture.isCube) {
  33995. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  33996. }
  33997. else {
  33998. effect.setTexture("refraction2DSampler", this._refractionTexture);
  33999. }
  34000. }
  34001. }
  34002. // Clip plane
  34003. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34004. // Colors
  34005. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34006. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34007. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34008. }
  34009. if (mustRebind || !this.isFrozen) {
  34010. // Lights
  34011. if (scene.lightsEnabled && !this._disableLighting) {
  34012. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34013. }
  34014. // View
  34015. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34016. this.bindView(effect);
  34017. }
  34018. // Fog
  34019. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34020. // Morph targets
  34021. if (defines.NUM_MORPH_INFLUENCERS) {
  34022. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34023. }
  34024. // Log. depth
  34025. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34026. // image processing
  34027. this._imageProcessingConfiguration.bind(this._activeEffect);
  34028. }
  34029. this._uniformBuffer.update();
  34030. this._afterBind(mesh, this._activeEffect);
  34031. };
  34032. StandardMaterial.prototype.getAnimatables = function () {
  34033. var results = [];
  34034. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34035. results.push(this._diffuseTexture);
  34036. }
  34037. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34038. results.push(this._ambientTexture);
  34039. }
  34040. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34041. results.push(this._opacityTexture);
  34042. }
  34043. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34044. results.push(this._reflectionTexture);
  34045. }
  34046. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34047. results.push(this._emissiveTexture);
  34048. }
  34049. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34050. results.push(this._specularTexture);
  34051. }
  34052. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34053. results.push(this._bumpTexture);
  34054. }
  34055. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34056. results.push(this._lightmapTexture);
  34057. }
  34058. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34059. results.push(this._refractionTexture);
  34060. }
  34061. return results;
  34062. };
  34063. StandardMaterial.prototype.getActiveTextures = function () {
  34064. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34065. if (this._diffuseTexture) {
  34066. activeTextures.push(this._diffuseTexture);
  34067. }
  34068. if (this._ambientTexture) {
  34069. activeTextures.push(this._ambientTexture);
  34070. }
  34071. if (this._opacityTexture) {
  34072. activeTextures.push(this._opacityTexture);
  34073. }
  34074. if (this._reflectionTexture) {
  34075. activeTextures.push(this._reflectionTexture);
  34076. }
  34077. if (this._emissiveTexture) {
  34078. activeTextures.push(this._emissiveTexture);
  34079. }
  34080. if (this._specularTexture) {
  34081. activeTextures.push(this._specularTexture);
  34082. }
  34083. if (this._bumpTexture) {
  34084. activeTextures.push(this._bumpTexture);
  34085. }
  34086. if (this._lightmapTexture) {
  34087. activeTextures.push(this._lightmapTexture);
  34088. }
  34089. if (this._refractionTexture) {
  34090. activeTextures.push(this._refractionTexture);
  34091. }
  34092. return activeTextures;
  34093. };
  34094. StandardMaterial.prototype.hasTexture = function (texture) {
  34095. if (_super.prototype.hasTexture.call(this, texture)) {
  34096. return true;
  34097. }
  34098. if (this._diffuseTexture === texture) {
  34099. return true;
  34100. }
  34101. if (this._ambientTexture === texture) {
  34102. return true;
  34103. }
  34104. if (this._opacityTexture === texture) {
  34105. return true;
  34106. }
  34107. if (this._reflectionTexture === texture) {
  34108. return true;
  34109. }
  34110. if (this._emissiveTexture === texture) {
  34111. return true;
  34112. }
  34113. if (this._specularTexture === texture) {
  34114. return true;
  34115. }
  34116. if (this._bumpTexture === texture) {
  34117. return true;
  34118. }
  34119. if (this._lightmapTexture === texture) {
  34120. return true;
  34121. }
  34122. if (this._refractionTexture === texture) {
  34123. return true;
  34124. }
  34125. return false;
  34126. };
  34127. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34128. if (forceDisposeTextures) {
  34129. if (this._diffuseTexture) {
  34130. this._diffuseTexture.dispose();
  34131. }
  34132. if (this._ambientTexture) {
  34133. this._ambientTexture.dispose();
  34134. }
  34135. if (this._opacityTexture) {
  34136. this._opacityTexture.dispose();
  34137. }
  34138. if (this._reflectionTexture) {
  34139. this._reflectionTexture.dispose();
  34140. }
  34141. if (this._emissiveTexture) {
  34142. this._emissiveTexture.dispose();
  34143. }
  34144. if (this._specularTexture) {
  34145. this._specularTexture.dispose();
  34146. }
  34147. if (this._bumpTexture) {
  34148. this._bumpTexture.dispose();
  34149. }
  34150. if (this._lightmapTexture) {
  34151. this._lightmapTexture.dispose();
  34152. }
  34153. if (this._refractionTexture) {
  34154. this._refractionTexture.dispose();
  34155. }
  34156. }
  34157. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34158. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34159. }
  34160. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34161. };
  34162. StandardMaterial.prototype.clone = function (name) {
  34163. var _this = this;
  34164. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34165. result.name = name;
  34166. result.id = name;
  34167. return result;
  34168. };
  34169. StandardMaterial.prototype.serialize = function () {
  34170. return BABYLON.SerializationHelper.Serialize(this);
  34171. };
  34172. // Statics
  34173. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34174. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34175. };
  34176. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34177. get: function () {
  34178. return StandardMaterial._DiffuseTextureEnabled;
  34179. },
  34180. set: function (value) {
  34181. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34182. return;
  34183. }
  34184. StandardMaterial._DiffuseTextureEnabled = value;
  34185. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34186. },
  34187. enumerable: true,
  34188. configurable: true
  34189. });
  34190. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34191. get: function () {
  34192. return StandardMaterial._AmbientTextureEnabled;
  34193. },
  34194. set: function (value) {
  34195. if (StandardMaterial._AmbientTextureEnabled === value) {
  34196. return;
  34197. }
  34198. StandardMaterial._AmbientTextureEnabled = value;
  34199. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34200. },
  34201. enumerable: true,
  34202. configurable: true
  34203. });
  34204. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34205. get: function () {
  34206. return StandardMaterial._OpacityTextureEnabled;
  34207. },
  34208. set: function (value) {
  34209. if (StandardMaterial._OpacityTextureEnabled === value) {
  34210. return;
  34211. }
  34212. StandardMaterial._OpacityTextureEnabled = value;
  34213. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34214. },
  34215. enumerable: true,
  34216. configurable: true
  34217. });
  34218. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34219. get: function () {
  34220. return StandardMaterial._ReflectionTextureEnabled;
  34221. },
  34222. set: function (value) {
  34223. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34224. return;
  34225. }
  34226. StandardMaterial._ReflectionTextureEnabled = value;
  34227. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34228. },
  34229. enumerable: true,
  34230. configurable: true
  34231. });
  34232. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34233. get: function () {
  34234. return StandardMaterial._EmissiveTextureEnabled;
  34235. },
  34236. set: function (value) {
  34237. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34238. return;
  34239. }
  34240. StandardMaterial._EmissiveTextureEnabled = value;
  34241. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34242. },
  34243. enumerable: true,
  34244. configurable: true
  34245. });
  34246. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34247. get: function () {
  34248. return StandardMaterial._SpecularTextureEnabled;
  34249. },
  34250. set: function (value) {
  34251. if (StandardMaterial._SpecularTextureEnabled === value) {
  34252. return;
  34253. }
  34254. StandardMaterial._SpecularTextureEnabled = value;
  34255. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34256. },
  34257. enumerable: true,
  34258. configurable: true
  34259. });
  34260. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34261. get: function () {
  34262. return StandardMaterial._BumpTextureEnabled;
  34263. },
  34264. set: function (value) {
  34265. if (StandardMaterial._BumpTextureEnabled === value) {
  34266. return;
  34267. }
  34268. StandardMaterial._BumpTextureEnabled = value;
  34269. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34270. },
  34271. enumerable: true,
  34272. configurable: true
  34273. });
  34274. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34275. get: function () {
  34276. return StandardMaterial._LightmapTextureEnabled;
  34277. },
  34278. set: function (value) {
  34279. if (StandardMaterial._LightmapTextureEnabled === value) {
  34280. return;
  34281. }
  34282. StandardMaterial._LightmapTextureEnabled = value;
  34283. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34284. },
  34285. enumerable: true,
  34286. configurable: true
  34287. });
  34288. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34289. get: function () {
  34290. return StandardMaterial._RefractionTextureEnabled;
  34291. },
  34292. set: function (value) {
  34293. if (StandardMaterial._RefractionTextureEnabled === value) {
  34294. return;
  34295. }
  34296. StandardMaterial._RefractionTextureEnabled = value;
  34297. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34298. },
  34299. enumerable: true,
  34300. configurable: true
  34301. });
  34302. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34303. get: function () {
  34304. return StandardMaterial._ColorGradingTextureEnabled;
  34305. },
  34306. set: function (value) {
  34307. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34308. return;
  34309. }
  34310. StandardMaterial._ColorGradingTextureEnabled = value;
  34311. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34312. },
  34313. enumerable: true,
  34314. configurable: true
  34315. });
  34316. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34317. get: function () {
  34318. return StandardMaterial._FresnelEnabled;
  34319. },
  34320. set: function (value) {
  34321. if (StandardMaterial._FresnelEnabled === value) {
  34322. return;
  34323. }
  34324. StandardMaterial._FresnelEnabled = value;
  34325. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34326. },
  34327. enumerable: true,
  34328. configurable: true
  34329. });
  34330. // Flags used to enable or disable a type of texture for all Standard Materials
  34331. StandardMaterial._DiffuseTextureEnabled = true;
  34332. StandardMaterial._AmbientTextureEnabled = true;
  34333. StandardMaterial._OpacityTextureEnabled = true;
  34334. StandardMaterial._ReflectionTextureEnabled = true;
  34335. StandardMaterial._EmissiveTextureEnabled = true;
  34336. StandardMaterial._SpecularTextureEnabled = true;
  34337. StandardMaterial._BumpTextureEnabled = true;
  34338. StandardMaterial._LightmapTextureEnabled = true;
  34339. StandardMaterial._RefractionTextureEnabled = true;
  34340. StandardMaterial._ColorGradingTextureEnabled = true;
  34341. StandardMaterial._FresnelEnabled = true;
  34342. __decorate([
  34343. BABYLON.serializeAsTexture("diffuseTexture")
  34344. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34345. __decorate([
  34346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34347. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34348. __decorate([
  34349. BABYLON.serializeAsTexture("ambientTexture")
  34350. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  34351. __decorate([
  34352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34353. ], StandardMaterial.prototype, "ambientTexture", void 0);
  34354. __decorate([
  34355. BABYLON.serializeAsTexture("opacityTexture")
  34356. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  34357. __decorate([
  34358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34359. ], StandardMaterial.prototype, "opacityTexture", void 0);
  34360. __decorate([
  34361. BABYLON.serializeAsTexture("reflectionTexture")
  34362. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  34363. __decorate([
  34364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34365. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  34366. __decorate([
  34367. BABYLON.serializeAsTexture("emissiveTexture")
  34368. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  34369. __decorate([
  34370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34371. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  34372. __decorate([
  34373. BABYLON.serializeAsTexture("specularTexture")
  34374. ], StandardMaterial.prototype, "_specularTexture", void 0);
  34375. __decorate([
  34376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34377. ], StandardMaterial.prototype, "specularTexture", void 0);
  34378. __decorate([
  34379. BABYLON.serializeAsTexture("bumpTexture")
  34380. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  34381. __decorate([
  34382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34383. ], StandardMaterial.prototype, "bumpTexture", void 0);
  34384. __decorate([
  34385. BABYLON.serializeAsTexture("lightmapTexture")
  34386. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  34387. __decorate([
  34388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34389. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  34390. __decorate([
  34391. BABYLON.serializeAsTexture("refractionTexture")
  34392. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  34393. __decorate([
  34394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34395. ], StandardMaterial.prototype, "refractionTexture", void 0);
  34396. __decorate([
  34397. BABYLON.serializeAsColor3("ambient")
  34398. ], StandardMaterial.prototype, "ambientColor", void 0);
  34399. __decorate([
  34400. BABYLON.serializeAsColor3("diffuse")
  34401. ], StandardMaterial.prototype, "diffuseColor", void 0);
  34402. __decorate([
  34403. BABYLON.serializeAsColor3("specular")
  34404. ], StandardMaterial.prototype, "specularColor", void 0);
  34405. __decorate([
  34406. BABYLON.serializeAsColor3("emissive")
  34407. ], StandardMaterial.prototype, "emissiveColor", void 0);
  34408. __decorate([
  34409. BABYLON.serialize()
  34410. ], StandardMaterial.prototype, "specularPower", void 0);
  34411. __decorate([
  34412. BABYLON.serialize("useAlphaFromDiffuseTexture")
  34413. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  34414. __decorate([
  34415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34416. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  34417. __decorate([
  34418. BABYLON.serialize("useEmissiveAsIllumination")
  34419. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  34420. __decorate([
  34421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34422. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  34423. __decorate([
  34424. BABYLON.serialize("linkEmissiveWithDiffuse")
  34425. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  34426. __decorate([
  34427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34428. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  34429. __decorate([
  34430. BABYLON.serialize("useSpecularOverAlpha")
  34431. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  34432. __decorate([
  34433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34434. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  34435. __decorate([
  34436. BABYLON.serialize("useReflectionOverAlpha")
  34437. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  34438. __decorate([
  34439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34440. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  34441. __decorate([
  34442. BABYLON.serialize("disableLighting")
  34443. ], StandardMaterial.prototype, "_disableLighting", void 0);
  34444. __decorate([
  34445. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34446. ], StandardMaterial.prototype, "disableLighting", void 0);
  34447. __decorate([
  34448. BABYLON.serialize("useParallax")
  34449. ], StandardMaterial.prototype, "_useParallax", void 0);
  34450. __decorate([
  34451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34452. ], StandardMaterial.prototype, "useParallax", void 0);
  34453. __decorate([
  34454. BABYLON.serialize("useParallaxOcclusion")
  34455. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  34456. __decorate([
  34457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34458. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  34459. __decorate([
  34460. BABYLON.serialize()
  34461. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  34462. __decorate([
  34463. BABYLON.serialize("roughness")
  34464. ], StandardMaterial.prototype, "_roughness", void 0);
  34465. __decorate([
  34466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34467. ], StandardMaterial.prototype, "roughness", void 0);
  34468. __decorate([
  34469. BABYLON.serialize()
  34470. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  34471. __decorate([
  34472. BABYLON.serialize()
  34473. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  34474. __decorate([
  34475. BABYLON.serialize("useLightmapAsShadowmap")
  34476. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  34477. __decorate([
  34478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34479. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34480. __decorate([
  34481. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  34482. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  34483. __decorate([
  34484. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34485. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  34486. __decorate([
  34487. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  34488. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  34489. __decorate([
  34490. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34491. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  34492. __decorate([
  34493. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  34494. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  34495. __decorate([
  34496. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34497. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  34498. __decorate([
  34499. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  34500. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  34501. __decorate([
  34502. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34503. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  34504. __decorate([
  34505. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  34506. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  34507. __decorate([
  34508. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34509. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  34510. __decorate([
  34511. BABYLON.serialize("useReflectionFresnelFromSpecular")
  34512. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  34513. __decorate([
  34514. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34515. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  34516. __decorate([
  34517. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  34518. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  34519. __decorate([
  34520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34521. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  34522. __decorate([
  34523. BABYLON.serialize("maxSimultaneousLights")
  34524. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  34525. __decorate([
  34526. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34527. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  34528. __decorate([
  34529. BABYLON.serialize("invertNormalMapX")
  34530. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  34531. __decorate([
  34532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34533. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  34534. __decorate([
  34535. BABYLON.serialize("invertNormalMapY")
  34536. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  34537. __decorate([
  34538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34539. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  34540. __decorate([
  34541. BABYLON.serialize("twoSidedLighting")
  34542. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  34543. __decorate([
  34544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34545. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  34546. __decorate([
  34547. BABYLON.serialize()
  34548. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  34549. return StandardMaterial;
  34550. }(BABYLON.PushMaterial));
  34551. BABYLON.StandardMaterial = StandardMaterial;
  34552. })(BABYLON || (BABYLON = {}));
  34553. //# sourceMappingURL=babylon.standardMaterial.js.map
  34554. var BABYLON;
  34555. (function (BABYLON) {
  34556. var PBRMaterialDefines = /** @class */ (function (_super) {
  34557. __extends(PBRMaterialDefines, _super);
  34558. function PBRMaterialDefines() {
  34559. var _this = _super.call(this) || this;
  34560. _this.PBR = true;
  34561. _this.MAINUV1 = false;
  34562. _this.MAINUV2 = false;
  34563. _this.UV1 = false;
  34564. _this.UV2 = false;
  34565. _this.ALBEDO = false;
  34566. _this.ALBEDODIRECTUV = 0;
  34567. _this.VERTEXCOLOR = false;
  34568. _this.AMBIENT = false;
  34569. _this.AMBIENTDIRECTUV = 0;
  34570. _this.AMBIENTINGRAYSCALE = false;
  34571. _this.OPACITY = false;
  34572. _this.VERTEXALPHA = false;
  34573. _this.OPACITYDIRECTUV = 0;
  34574. _this.OPACITYRGB = false;
  34575. _this.ALPHATEST = false;
  34576. _this.DEPTHPREPASS = false;
  34577. _this.ALPHABLEND = false;
  34578. _this.ALPHAFROMALBEDO = false;
  34579. _this.ALPHATESTVALUE = 0.5;
  34580. _this.SPECULAROVERALPHA = false;
  34581. _this.RADIANCEOVERALPHA = false;
  34582. _this.ALPHAFRESNEL = false;
  34583. _this.PREMULTIPLYALPHA = false;
  34584. _this.EMISSIVE = false;
  34585. _this.EMISSIVEDIRECTUV = 0;
  34586. _this.REFLECTIVITY = false;
  34587. _this.REFLECTIVITYDIRECTUV = 0;
  34588. _this.SPECULARTERM = false;
  34589. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34590. _this.MICROSURFACEAUTOMATIC = false;
  34591. _this.LODBASEDMICROSFURACE = false;
  34592. _this.MICROSURFACEMAP = false;
  34593. _this.MICROSURFACEMAPDIRECTUV = 0;
  34594. _this.METALLICWORKFLOW = false;
  34595. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34596. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34597. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34598. _this.AOSTOREINMETALMAPRED = false;
  34599. _this.ENVIRONMENTBRDF = false;
  34600. _this.NORMAL = false;
  34601. _this.TANGENT = false;
  34602. _this.BUMP = false;
  34603. _this.BUMPDIRECTUV = 0;
  34604. _this.PARALLAX = false;
  34605. _this.PARALLAXOCCLUSION = false;
  34606. _this.NORMALXYSCALE = true;
  34607. _this.LIGHTMAP = false;
  34608. _this.LIGHTMAPDIRECTUV = 0;
  34609. _this.USELIGHTMAPASSHADOWMAP = false;
  34610. _this.REFLECTION = false;
  34611. _this.REFLECTIONMAP_3D = false;
  34612. _this.REFLECTIONMAP_SPHERICAL = false;
  34613. _this.REFLECTIONMAP_PLANAR = false;
  34614. _this.REFLECTIONMAP_CUBIC = false;
  34615. _this.REFLECTIONMAP_PROJECTION = false;
  34616. _this.REFLECTIONMAP_SKYBOX = false;
  34617. _this.REFLECTIONMAP_EXPLICIT = false;
  34618. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34619. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34620. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34621. _this.INVERTCUBICMAP = false;
  34622. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34623. _this.USESPHERICALINFRAGMENT = false;
  34624. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34625. _this.LODINREFLECTIONALPHA = false;
  34626. _this.GAMMAREFLECTION = false;
  34627. _this.REFRACTION = false;
  34628. _this.REFRACTIONMAP_3D = false;
  34629. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34630. _this.LODINREFRACTIONALPHA = false;
  34631. _this.GAMMAREFRACTION = false;
  34632. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34633. _this.INSTANCES = false;
  34634. _this.NUM_BONE_INFLUENCERS = 0;
  34635. _this.BonesPerMesh = 0;
  34636. _this.NONUNIFORMSCALING = false;
  34637. _this.MORPHTARGETS = false;
  34638. _this.MORPHTARGETS_NORMAL = false;
  34639. _this.MORPHTARGETS_TANGENT = false;
  34640. _this.NUM_MORPH_INFLUENCERS = 0;
  34641. _this.IMAGEPROCESSING = false;
  34642. _this.VIGNETTE = false;
  34643. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34644. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34645. _this.TONEMAPPING = false;
  34646. _this.CONTRAST = false;
  34647. _this.COLORCURVES = false;
  34648. _this.COLORGRADING = false;
  34649. _this.COLORGRADING3D = false;
  34650. _this.SAMPLER3DGREENDEPTH = false;
  34651. _this.SAMPLER3DBGRMAP = false;
  34652. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34653. _this.EXPOSURE = false;
  34654. _this.USEPHYSICALLIGHTFALLOFF = false;
  34655. _this.TWOSIDEDLIGHTING = false;
  34656. _this.SHADOWFLOAT = false;
  34657. _this.CLIPPLANE = false;
  34658. _this.POINTSIZE = false;
  34659. _this.FOG = false;
  34660. _this.LOGARITHMICDEPTH = false;
  34661. _this.FORCENORMALFORWARD = false;
  34662. _this.rebuild();
  34663. return _this;
  34664. }
  34665. PBRMaterialDefines.prototype.reset = function () {
  34666. _super.prototype.reset.call(this);
  34667. this.ALPHATESTVALUE = 0.5;
  34668. this.PBR = true;
  34669. };
  34670. return PBRMaterialDefines;
  34671. }(BABYLON.MaterialDefines));
  34672. /**
  34673. * The Physically based material base class of BJS.
  34674. *
  34675. * This offers the main features of a standard PBR material.
  34676. * For more information, please refer to the documentation :
  34677. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34678. */
  34679. var PBRBaseMaterial = /** @class */ (function (_super) {
  34680. __extends(PBRBaseMaterial, _super);
  34681. /**
  34682. * Instantiates a new PBRMaterial instance.
  34683. *
  34684. * @param name The material name
  34685. * @param scene The scene the material will be use in.
  34686. */
  34687. function PBRBaseMaterial(name, scene) {
  34688. var _this = _super.call(this, name, scene) || this;
  34689. /**
  34690. * Intensity of the direct lights e.g. the four lights available in your scene.
  34691. * This impacts both the direct diffuse and specular highlights.
  34692. */
  34693. _this._directIntensity = 1.0;
  34694. /**
  34695. * Intensity of the emissive part of the material.
  34696. * This helps controlling the emissive effect without modifying the emissive color.
  34697. */
  34698. _this._emissiveIntensity = 1.0;
  34699. /**
  34700. * Intensity of the environment e.g. how much the environment will light the object
  34701. * either through harmonics for rough material or through the refelction for shiny ones.
  34702. */
  34703. _this._environmentIntensity = 1.0;
  34704. /**
  34705. * This is a special control allowing the reduction of the specular highlights coming from the
  34706. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34707. */
  34708. _this._specularIntensity = 1.0;
  34709. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34710. /**
  34711. * Debug Control allowing disabling the bump map on this material.
  34712. */
  34713. _this._disableBumpMap = false;
  34714. /**
  34715. * AKA Occlusion Texture Intensity in other nomenclature.
  34716. */
  34717. _this._ambientTextureStrength = 1.0;
  34718. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34719. /**
  34720. * AKA Diffuse Color in other nomenclature.
  34721. */
  34722. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34723. /**
  34724. * AKA Specular Color in other nomenclature.
  34725. */
  34726. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34727. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  34728. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34729. /**
  34730. * AKA Glossiness in other nomenclature.
  34731. */
  34732. _this._microSurface = 0.9;
  34733. /**
  34734. * source material index of refraction (IOR)' / 'destination material IOR.
  34735. */
  34736. _this._indexOfRefraction = 0.66;
  34737. /**
  34738. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34739. */
  34740. _this._invertRefractionY = false;
  34741. /**
  34742. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34743. * Materials half opaque for instance using refraction could benefit from this control.
  34744. */
  34745. _this._linkRefractionWithTransparency = false;
  34746. _this._useLightmapAsShadowmap = false;
  34747. /**
  34748. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34749. */
  34750. _this._useAlphaFromAlbedoTexture = false;
  34751. /**
  34752. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34753. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34754. */
  34755. _this._useSpecularOverAlpha = true;
  34756. /**
  34757. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34758. */
  34759. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34760. /**
  34761. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34762. */
  34763. _this._useRoughnessFromMetallicTextureAlpha = true;
  34764. /**
  34765. * Specifies if the metallic texture contains the roughness information in its green channel.
  34766. */
  34767. _this._useRoughnessFromMetallicTextureGreen = false;
  34768. /**
  34769. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34770. */
  34771. _this._useMetallnessFromMetallicTextureBlue = false;
  34772. /**
  34773. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34774. */
  34775. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34776. /**
  34777. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34778. */
  34779. _this._useAmbientInGrayScale = false;
  34780. /**
  34781. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34782. * The material will try to infer what glossiness each pixel should be.
  34783. */
  34784. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34785. /**
  34786. * BJS is using an harcoded light falloff based on a manually sets up range.
  34787. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34788. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34789. */
  34790. _this._usePhysicalLightFalloff = true;
  34791. /**
  34792. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34793. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34794. */
  34795. _this._useRadianceOverAlpha = true;
  34796. /**
  34797. * Allows using the bump map in parallax mode.
  34798. */
  34799. _this._useParallax = false;
  34800. /**
  34801. * Allows using the bump map in parallax occlusion mode.
  34802. */
  34803. _this._useParallaxOcclusion = false;
  34804. /**
  34805. * Controls the scale bias of the parallax mode.
  34806. */
  34807. _this._parallaxScaleBias = 0.05;
  34808. /**
  34809. * If sets to true, disables all the lights affecting the material.
  34810. */
  34811. _this._disableLighting = false;
  34812. /**
  34813. * Number of Simultaneous lights allowed on the material.
  34814. */
  34815. _this._maxSimultaneousLights = 4;
  34816. /**
  34817. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  34818. */
  34819. _this._invertNormalMapX = false;
  34820. /**
  34821. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  34822. */
  34823. _this._invertNormalMapY = false;
  34824. /**
  34825. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34826. */
  34827. _this._twoSidedLighting = false;
  34828. /**
  34829. * Defines the alpha limits in alpha test mode.
  34830. */
  34831. _this._alphaCutOff = 0.4;
  34832. /**
  34833. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34834. */
  34835. _this._forceAlphaTest = false;
  34836. /**
  34837. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34838. * And/Or occlude the blended part.
  34839. */
  34840. _this._useAlphaFresnel = false;
  34841. /**
  34842. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  34843. * from cos thetav and roughness:
  34844. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  34845. */
  34846. _this._environmentBRDFTexture = null;
  34847. /**
  34848. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  34849. */
  34850. _this._forceIrradianceInFragment = false;
  34851. /**
  34852. * Force normal to face away from face.
  34853. * (Temporary internal fix to remove before 3.1)
  34854. */
  34855. _this._forceNormalForward = false;
  34856. _this._renderTargets = new BABYLON.SmartArray(16);
  34857. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34858. // Setup the default processing configuration to the scene.
  34859. _this._attachImageProcessingConfiguration(null);
  34860. _this.getRenderTargetTextures = function () {
  34861. _this._renderTargets.reset();
  34862. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34863. _this._renderTargets.push(_this._reflectionTexture);
  34864. }
  34865. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34866. _this._renderTargets.push(_this._refractionTexture);
  34867. }
  34868. return _this._renderTargets;
  34869. };
  34870. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  34871. return _this;
  34872. }
  34873. /**
  34874. * Attaches a new image processing configuration to the PBR Material.
  34875. * @param configuration
  34876. */
  34877. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34878. var _this = this;
  34879. if (configuration === this._imageProcessingConfiguration) {
  34880. return;
  34881. }
  34882. // Detaches observer.
  34883. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34884. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34885. }
  34886. // Pick the scene configuration if needed.
  34887. if (!configuration) {
  34888. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34889. }
  34890. else {
  34891. this._imageProcessingConfiguration = configuration;
  34892. }
  34893. // Attaches observer.
  34894. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34895. _this._markAllSubMeshesAsImageProcessingDirty();
  34896. });
  34897. };
  34898. PBRBaseMaterial.prototype.getClassName = function () {
  34899. return "PBRBaseMaterial";
  34900. };
  34901. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  34902. get: function () {
  34903. return this._useLogarithmicDepth;
  34904. },
  34905. set: function (value) {
  34906. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34907. },
  34908. enumerable: true,
  34909. configurable: true
  34910. });
  34911. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  34912. if (this._linkRefractionWithTransparency) {
  34913. return false;
  34914. }
  34915. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  34916. };
  34917. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  34918. if (this._forceAlphaTest) {
  34919. return true;
  34920. }
  34921. if (this._linkRefractionWithTransparency) {
  34922. return false;
  34923. }
  34924. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  34925. };
  34926. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34927. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  34928. };
  34929. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  34930. return this._albedoTexture;
  34931. };
  34932. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34933. var _this = this;
  34934. if (subMesh.effect && this.isFrozen) {
  34935. if (this._wasPreviouslyReady) {
  34936. return true;
  34937. }
  34938. }
  34939. if (!subMesh._materialDefines) {
  34940. subMesh._materialDefines = new PBRMaterialDefines();
  34941. }
  34942. var scene = this.getScene();
  34943. var defines = subMesh._materialDefines;
  34944. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34945. if (defines._renderId === scene.getRenderId()) {
  34946. return true;
  34947. }
  34948. }
  34949. var engine = scene.getEngine();
  34950. // Lights
  34951. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34952. defines._needNormals = true;
  34953. // Textures
  34954. if (defines._areTexturesDirty) {
  34955. defines._needUVs = false;
  34956. if (scene.texturesEnabled) {
  34957. if (scene.getEngine().getCaps().textureLOD) {
  34958. defines.LODBASEDMICROSFURACE = true;
  34959. }
  34960. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34961. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  34962. return false;
  34963. }
  34964. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  34965. }
  34966. else {
  34967. defines.ALBEDO = false;
  34968. }
  34969. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34970. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34971. return false;
  34972. }
  34973. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34974. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  34975. }
  34976. else {
  34977. defines.AMBIENT = false;
  34978. }
  34979. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34980. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34981. return false;
  34982. }
  34983. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34984. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34985. }
  34986. else {
  34987. defines.OPACITY = false;
  34988. }
  34989. var reflectionTexture = this._getReflectionTexture();
  34990. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34991. if (!reflectionTexture.isReadyOrNotBlocking()) {
  34992. return false;
  34993. }
  34994. defines.REFLECTION = true;
  34995. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  34996. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  34997. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  34998. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  34999. defines.INVERTCUBICMAP = true;
  35000. }
  35001. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35002. switch (reflectionTexture.coordinatesMode) {
  35003. case BABYLON.Texture.CUBIC_MODE:
  35004. case BABYLON.Texture.INVCUBIC_MODE:
  35005. defines.REFLECTIONMAP_CUBIC = true;
  35006. break;
  35007. case BABYLON.Texture.EXPLICIT_MODE:
  35008. defines.REFLECTIONMAP_EXPLICIT = true;
  35009. break;
  35010. case BABYLON.Texture.PLANAR_MODE:
  35011. defines.REFLECTIONMAP_PLANAR = true;
  35012. break;
  35013. case BABYLON.Texture.PROJECTION_MODE:
  35014. defines.REFLECTIONMAP_PROJECTION = true;
  35015. break;
  35016. case BABYLON.Texture.SKYBOX_MODE:
  35017. defines.REFLECTIONMAP_SKYBOX = true;
  35018. break;
  35019. case BABYLON.Texture.SPHERICAL_MODE:
  35020. defines.REFLECTIONMAP_SPHERICAL = true;
  35021. break;
  35022. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35023. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35024. break;
  35025. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35026. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35027. break;
  35028. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35029. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35030. break;
  35031. }
  35032. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35033. if (reflectionTexture.sphericalPolynomial) {
  35034. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35035. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35036. defines.USESPHERICALINFRAGMENT = true;
  35037. }
  35038. }
  35039. }
  35040. }
  35041. else {
  35042. defines.REFLECTION = false;
  35043. defines.REFLECTIONMAP_3D = false;
  35044. defines.REFLECTIONMAP_SPHERICAL = false;
  35045. defines.REFLECTIONMAP_PLANAR = false;
  35046. defines.REFLECTIONMAP_CUBIC = false;
  35047. defines.REFLECTIONMAP_PROJECTION = false;
  35048. defines.REFLECTIONMAP_SKYBOX = false;
  35049. defines.REFLECTIONMAP_EXPLICIT = false;
  35050. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35051. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35052. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35053. defines.INVERTCUBICMAP = false;
  35054. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35055. defines.USESPHERICALINFRAGMENT = false;
  35056. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35057. defines.LODINREFLECTIONALPHA = false;
  35058. defines.GAMMAREFLECTION = false;
  35059. }
  35060. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35061. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35062. return false;
  35063. }
  35064. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35065. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35066. }
  35067. else {
  35068. defines.LIGHTMAP = false;
  35069. }
  35070. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35071. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35072. return false;
  35073. }
  35074. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35075. }
  35076. else {
  35077. defines.EMISSIVE = false;
  35078. }
  35079. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35080. if (this._metallicTexture) {
  35081. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35082. return false;
  35083. }
  35084. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35085. defines.METALLICWORKFLOW = true;
  35086. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35087. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35088. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35089. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35090. }
  35091. else if (this._reflectivityTexture) {
  35092. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35093. return false;
  35094. }
  35095. defines.METALLICWORKFLOW = false;
  35096. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35097. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35098. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35099. }
  35100. else {
  35101. defines.METALLICWORKFLOW = false;
  35102. defines.REFLECTIVITY = false;
  35103. }
  35104. if (this._microSurfaceTexture) {
  35105. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35106. return false;
  35107. }
  35108. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35109. }
  35110. else {
  35111. defines.MICROSURFACEMAP = false;
  35112. }
  35113. }
  35114. else {
  35115. defines.REFLECTIVITY = false;
  35116. defines.MICROSURFACEMAP = false;
  35117. }
  35118. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35119. // Bump texure can not be none blocking.
  35120. if (!this._bumpTexture.isReady()) {
  35121. return false;
  35122. }
  35123. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35124. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35125. defines.PARALLAX = true;
  35126. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35127. }
  35128. else {
  35129. defines.PARALLAX = false;
  35130. }
  35131. }
  35132. else {
  35133. defines.BUMP = false;
  35134. }
  35135. var refractionTexture = this._getRefractionTexture();
  35136. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35137. if (!refractionTexture.isReadyOrNotBlocking()) {
  35138. return false;
  35139. }
  35140. defines.REFRACTION = true;
  35141. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35142. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35143. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35144. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35145. if (this._linkRefractionWithTransparency) {
  35146. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35147. }
  35148. }
  35149. else {
  35150. defines.REFRACTION = false;
  35151. }
  35152. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35153. // This is blocking.
  35154. if (!this._environmentBRDFTexture.isReady()) {
  35155. return false;
  35156. }
  35157. defines.ENVIRONMENTBRDF = true;
  35158. }
  35159. else {
  35160. defines.ENVIRONMENTBRDF = false;
  35161. }
  35162. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35163. defines.ALPHAFROMALBEDO = true;
  35164. }
  35165. else {
  35166. defines.ALPHAFROMALBEDO = false;
  35167. }
  35168. }
  35169. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35170. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35171. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35172. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35173. defines.METALLICWORKFLOW = true;
  35174. }
  35175. else {
  35176. defines.METALLICWORKFLOW = false;
  35177. }
  35178. if (!this.backFaceCulling && this._twoSidedLighting) {
  35179. defines.TWOSIDEDLIGHTING = true;
  35180. }
  35181. else {
  35182. defines.TWOSIDEDLIGHTING = false;
  35183. }
  35184. defines.ALPHATESTVALUE = this._alphaCutOff;
  35185. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35186. defines.ALPHABLEND = this.needAlphaBlending();
  35187. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35188. }
  35189. if (defines._areImageProcessingDirty) {
  35190. if (!this._imageProcessingConfiguration.isReady()) {
  35191. return false;
  35192. }
  35193. this._imageProcessingConfiguration.prepareDefines(defines);
  35194. }
  35195. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35196. // Misc.
  35197. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35198. // Values that need to be evaluated on every frame
  35199. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35200. // Attribs
  35201. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35202. if (mesh) {
  35203. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35204. mesh.createNormals(true);
  35205. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35206. }
  35207. }
  35208. }
  35209. // Get correct effect
  35210. if (defines.isDirty) {
  35211. defines.markAsProcessed();
  35212. scene.resetCachedMaterial();
  35213. // Fallbacks
  35214. var fallbacks = new BABYLON.EffectFallbacks();
  35215. if (defines.ENVIRONMENTBRDF) {
  35216. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  35217. }
  35218. if (defines.REFLECTION) {
  35219. fallbacks.addFallback(0, "REFLECTION");
  35220. }
  35221. if (defines.REFRACTION) {
  35222. fallbacks.addFallback(0, "REFRACTION");
  35223. }
  35224. if (defines.REFLECTIVITY) {
  35225. fallbacks.addFallback(0, "REFLECTIVITY");
  35226. }
  35227. if (defines.BUMP) {
  35228. fallbacks.addFallback(0, "BUMP");
  35229. }
  35230. if (defines.PARALLAX) {
  35231. fallbacks.addFallback(1, "PARALLAX");
  35232. }
  35233. if (defines.PARALLAXOCCLUSION) {
  35234. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35235. }
  35236. if (defines.SPECULAROVERALPHA) {
  35237. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35238. }
  35239. if (defines.FOG) {
  35240. fallbacks.addFallback(1, "FOG");
  35241. }
  35242. if (defines.POINTSIZE) {
  35243. fallbacks.addFallback(0, "POINTSIZE");
  35244. }
  35245. if (defines.LOGARITHMICDEPTH) {
  35246. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35247. }
  35248. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35249. if (defines.SPECULARTERM) {
  35250. fallbacks.addFallback(0, "SPECULARTERM");
  35251. }
  35252. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35253. fallbacks.addCPUSkinningFallback(0, mesh);
  35254. }
  35255. //Attributes
  35256. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35257. if (defines.NORMAL) {
  35258. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35259. }
  35260. if (defines.TANGENT) {
  35261. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35262. }
  35263. if (defines.UV1) {
  35264. attribs.push(BABYLON.VertexBuffer.UVKind);
  35265. }
  35266. if (defines.UV2) {
  35267. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35268. }
  35269. if (defines.VERTEXCOLOR) {
  35270. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35271. }
  35272. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35273. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35274. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35275. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35276. "vFogInfos", "vFogColor", "pointSize",
  35277. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35278. "mBones",
  35279. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35280. "vLightingIntensity",
  35281. "logarithmicDepthConstant",
  35282. "vSphericalX", "vSphericalY", "vSphericalZ",
  35283. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35284. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35285. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  35286. "vTangentSpaceParams"
  35287. ];
  35288. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35289. "bumpSampler", "lightmapSampler", "opacitySampler",
  35290. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35291. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35292. "microSurfaceSampler", "environmentBrdfSampler"];
  35293. var uniformBuffers = ["Material", "Scene"];
  35294. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35295. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35296. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35297. uniformsNames: uniforms,
  35298. uniformBuffersNames: uniformBuffers,
  35299. samplers: samplers,
  35300. defines: defines,
  35301. maxSimultaneousLights: this._maxSimultaneousLights
  35302. });
  35303. var onCompiled = function (effect) {
  35304. if (_this.onCompiled) {
  35305. _this.onCompiled(effect);
  35306. }
  35307. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35308. };
  35309. var join = defines.toString();
  35310. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35311. attributes: attribs,
  35312. uniformsNames: uniforms,
  35313. uniformBuffersNames: uniformBuffers,
  35314. samplers: samplers,
  35315. defines: join,
  35316. fallbacks: fallbacks,
  35317. onCompiled: onCompiled,
  35318. onError: this.onError,
  35319. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35320. }, engine), defines);
  35321. this.buildUniformLayout();
  35322. }
  35323. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35324. return false;
  35325. }
  35326. defines._renderId = scene.getRenderId();
  35327. this._wasPreviouslyReady = true;
  35328. return true;
  35329. };
  35330. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35331. // Order is important !
  35332. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35333. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35334. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35335. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35336. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35337. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35338. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35339. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35340. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35341. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35342. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35343. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35344. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35345. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35346. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35347. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35348. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35349. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35350. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35351. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35352. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35353. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35354. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35355. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35356. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35357. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35358. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35359. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35360. this._uniformBuffer.addUniform("pointSize", 1);
  35361. this._uniformBuffer.create();
  35362. };
  35363. PBRBaseMaterial.prototype.unbind = function () {
  35364. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35365. this._uniformBuffer.setTexture("reflectionSampler", null);
  35366. }
  35367. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35368. this._uniformBuffer.setTexture("refractionSampler", null);
  35369. }
  35370. _super.prototype.unbind.call(this);
  35371. };
  35372. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35373. this._activeEffect.setMatrix("world", world);
  35374. };
  35375. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35376. var scene = this.getScene();
  35377. var defines = subMesh._materialDefines;
  35378. if (!defines) {
  35379. return;
  35380. }
  35381. var effect = subMesh.effect;
  35382. if (!effect) {
  35383. return;
  35384. }
  35385. this._activeEffect = effect;
  35386. // Matrices
  35387. this.bindOnlyWorldMatrix(world);
  35388. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35389. // Bones
  35390. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35391. var reflectionTexture = null;
  35392. if (mustRebind) {
  35393. this._uniformBuffer.bindToEffect(effect, "Material");
  35394. this.bindViewProjection(effect);
  35395. reflectionTexture = this._getReflectionTexture();
  35396. var refractionTexture = this._getRefractionTexture();
  35397. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35398. // Texture uniforms
  35399. if (scene.texturesEnabled) {
  35400. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35401. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35402. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35403. }
  35404. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35405. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35406. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35407. }
  35408. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35409. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35410. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35411. }
  35412. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35413. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35414. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35415. var polynomials = reflectionTexture.sphericalPolynomial;
  35416. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  35417. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35418. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35419. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35420. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35421. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35422. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35423. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35424. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35425. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35426. }
  35427. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35428. }
  35429. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35430. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35431. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35432. }
  35433. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35434. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35435. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35436. }
  35437. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35438. if (this._metallicTexture) {
  35439. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35440. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35441. }
  35442. else if (this._reflectivityTexture) {
  35443. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35444. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35445. }
  35446. if (this._microSurfaceTexture) {
  35447. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35448. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35449. }
  35450. }
  35451. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35452. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35453. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35454. if (scene._mirroredCameraPosition) {
  35455. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35456. }
  35457. else {
  35458. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35459. }
  35460. }
  35461. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35462. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35463. var depth = 1.0;
  35464. if (!refractionTexture.isCube) {
  35465. if (refractionTexture.depth) {
  35466. depth = refractionTexture.depth;
  35467. }
  35468. }
  35469. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35470. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35471. }
  35472. }
  35473. // Point size
  35474. if (this.pointsCloud) {
  35475. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35476. }
  35477. // Colors
  35478. if (defines.METALLICWORKFLOW) {
  35479. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35480. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35481. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35482. }
  35483. else {
  35484. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35485. }
  35486. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35487. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35488. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35489. // Misc
  35490. this._lightingInfos.x = this._directIntensity;
  35491. this._lightingInfos.y = this._emissiveIntensity;
  35492. this._lightingInfos.z = this._environmentIntensity;
  35493. this._lightingInfos.w = this._specularIntensity;
  35494. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35495. }
  35496. // Textures
  35497. if (scene.texturesEnabled) {
  35498. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35499. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35500. }
  35501. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35502. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35503. }
  35504. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35505. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35506. }
  35507. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35508. if (defines.LODBASEDMICROSFURACE) {
  35509. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35510. }
  35511. else {
  35512. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35513. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35514. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35515. }
  35516. }
  35517. if (defines.ENVIRONMENTBRDF) {
  35518. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35519. }
  35520. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35521. if (defines.LODBASEDMICROSFURACE) {
  35522. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35523. }
  35524. else {
  35525. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35526. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35527. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35528. }
  35529. }
  35530. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35531. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35532. }
  35533. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35534. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35535. }
  35536. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35537. if (this._metallicTexture) {
  35538. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35539. }
  35540. else if (this._reflectivityTexture) {
  35541. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35542. }
  35543. if (this._microSurfaceTexture) {
  35544. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35545. }
  35546. }
  35547. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35548. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35549. }
  35550. }
  35551. // Clip plane
  35552. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35553. // Colors
  35554. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35555. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35556. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  35557. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  35558. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35559. }
  35560. if (mustRebind || !this.isFrozen) {
  35561. // Lights
  35562. if (scene.lightsEnabled && !this._disableLighting) {
  35563. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35564. }
  35565. // View
  35566. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35567. this.bindView(effect);
  35568. }
  35569. // Fog
  35570. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35571. // Morph targets
  35572. if (defines.NUM_MORPH_INFLUENCERS) {
  35573. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35574. }
  35575. // image processing
  35576. this._imageProcessingConfiguration.bind(this._activeEffect);
  35577. // Log. depth
  35578. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35579. }
  35580. this._uniformBuffer.update();
  35581. this._afterBind(mesh);
  35582. };
  35583. PBRBaseMaterial.prototype.getAnimatables = function () {
  35584. var results = [];
  35585. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35586. results.push(this._albedoTexture);
  35587. }
  35588. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35589. results.push(this._ambientTexture);
  35590. }
  35591. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35592. results.push(this._opacityTexture);
  35593. }
  35594. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35595. results.push(this._reflectionTexture);
  35596. }
  35597. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35598. results.push(this._emissiveTexture);
  35599. }
  35600. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35601. results.push(this._metallicTexture);
  35602. }
  35603. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35604. results.push(this._reflectivityTexture);
  35605. }
  35606. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35607. results.push(this._bumpTexture);
  35608. }
  35609. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35610. results.push(this._lightmapTexture);
  35611. }
  35612. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35613. results.push(this._refractionTexture);
  35614. }
  35615. return results;
  35616. };
  35617. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  35618. if (this._reflectionTexture) {
  35619. return this._reflectionTexture;
  35620. }
  35621. return this.getScene().environmentTexture;
  35622. };
  35623. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  35624. if (this._refractionTexture) {
  35625. return this._refractionTexture;
  35626. }
  35627. if (this._linkRefractionWithTransparency) {
  35628. return this.getScene().environmentTexture;
  35629. }
  35630. return null;
  35631. };
  35632. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35633. if (forceDisposeTextures) {
  35634. if (this._albedoTexture) {
  35635. this._albedoTexture.dispose();
  35636. }
  35637. if (this._ambientTexture) {
  35638. this._ambientTexture.dispose();
  35639. }
  35640. if (this._opacityTexture) {
  35641. this._opacityTexture.dispose();
  35642. }
  35643. if (this._reflectionTexture) {
  35644. this._reflectionTexture.dispose();
  35645. }
  35646. if (this._environmentBRDFTexture) {
  35647. this._environmentBRDFTexture.dispose();
  35648. }
  35649. if (this._emissiveTexture) {
  35650. this._emissiveTexture.dispose();
  35651. }
  35652. if (this._metallicTexture) {
  35653. this._metallicTexture.dispose();
  35654. }
  35655. if (this._reflectivityTexture) {
  35656. this._reflectivityTexture.dispose();
  35657. }
  35658. if (this._bumpTexture) {
  35659. this._bumpTexture.dispose();
  35660. }
  35661. if (this._lightmapTexture) {
  35662. this._lightmapTexture.dispose();
  35663. }
  35664. if (this._refractionTexture) {
  35665. this._refractionTexture.dispose();
  35666. }
  35667. }
  35668. this._renderTargets.dispose();
  35669. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35670. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35671. }
  35672. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35673. };
  35674. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35675. __decorate([
  35676. BABYLON.serializeAsImageProcessingConfiguration()
  35677. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35678. __decorate([
  35679. BABYLON.serialize()
  35680. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35681. return PBRBaseMaterial;
  35682. }(BABYLON.PushMaterial));
  35683. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35684. })(BABYLON || (BABYLON = {}));
  35685. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35686. var BABYLON;
  35687. (function (BABYLON) {
  35688. var Internals;
  35689. (function (Internals) {
  35690. /**
  35691. * The Physically based simple base material of BJS.
  35692. *
  35693. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35694. * It is used as the base class for both the specGloss and metalRough conventions.
  35695. */
  35696. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  35697. __extends(PBRBaseSimpleMaterial, _super);
  35698. /**
  35699. * Instantiates a new PBRMaterial instance.
  35700. *
  35701. * @param name The material name
  35702. * @param scene The scene the material will be use in.
  35703. */
  35704. function PBRBaseSimpleMaterial(name, scene) {
  35705. var _this = _super.call(this, name, scene) || this;
  35706. /**
  35707. * Number of Simultaneous lights allowed on the material.
  35708. */
  35709. _this.maxSimultaneousLights = 4;
  35710. /**
  35711. * If sets to true, disables all the lights affecting the material.
  35712. */
  35713. _this.disableLighting = false;
  35714. /**
  35715. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35716. */
  35717. _this.invertNormalMapX = false;
  35718. /**
  35719. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35720. */
  35721. _this.invertNormalMapY = false;
  35722. /**
  35723. * Emissivie color used to self-illuminate the model.
  35724. */
  35725. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35726. /**
  35727. * Occlusion Channel Strenght.
  35728. */
  35729. _this.occlusionStrength = 1.0;
  35730. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35731. _this._useAmbientInGrayScale = true;
  35732. return _this;
  35733. }
  35734. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35735. /**
  35736. * Gets the current transparency mode.
  35737. */
  35738. get: function () {
  35739. return this._transparencyMode;
  35740. },
  35741. /**
  35742. * Sets the transparency mode of the material.
  35743. */
  35744. set: function (value) {
  35745. if (this._transparencyMode === value) {
  35746. return;
  35747. }
  35748. this._transparencyMode = value;
  35749. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35750. this._forceAlphaTest = true;
  35751. }
  35752. else {
  35753. this._forceAlphaTest = false;
  35754. }
  35755. this._markAllSubMeshesAsTexturesDirty();
  35756. },
  35757. enumerable: true,
  35758. configurable: true
  35759. });
  35760. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35761. /**
  35762. * Gets the current double sided mode.
  35763. */
  35764. get: function () {
  35765. return this._twoSidedLighting;
  35766. },
  35767. /**
  35768. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35769. */
  35770. set: function (value) {
  35771. if (this._twoSidedLighting === value) {
  35772. return;
  35773. }
  35774. this._twoSidedLighting = value;
  35775. this.backFaceCulling = !value;
  35776. this._markAllSubMeshesAsTexturesDirty();
  35777. },
  35778. enumerable: true,
  35779. configurable: true
  35780. });
  35781. /**
  35782. * Specifies wether or not the alpha value of the albedo texture should be used.
  35783. */
  35784. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35785. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35786. };
  35787. /**
  35788. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35789. */
  35790. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35791. if (this._linkRefractionWithTransparency) {
  35792. return false;
  35793. }
  35794. return (this.alpha < 1.0) ||
  35795. (this._shouldUseAlphaFromAlbedoTexture() &&
  35796. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35797. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35798. };
  35799. /**
  35800. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35801. */
  35802. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35803. if (this._linkRefractionWithTransparency) {
  35804. return false;
  35805. }
  35806. return this._shouldUseAlphaFromAlbedoTexture() &&
  35807. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35808. };
  35809. /**
  35810. * Return the active textures of the material.
  35811. */
  35812. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  35813. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35814. if (this.environmentTexture) {
  35815. activeTextures.push(this.environmentTexture);
  35816. }
  35817. if (this.normalTexture) {
  35818. activeTextures.push(this.normalTexture);
  35819. }
  35820. if (this.emissiveTexture) {
  35821. activeTextures.push(this.emissiveTexture);
  35822. }
  35823. if (this.occlusionTexture) {
  35824. activeTextures.push(this.occlusionTexture);
  35825. }
  35826. return activeTextures;
  35827. };
  35828. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  35829. return "PBRBaseSimpleMaterial";
  35830. };
  35831. __decorate([
  35832. BABYLON.serialize(),
  35833. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35834. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35835. __decorate([
  35836. BABYLON.serialize(),
  35837. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35838. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35839. __decorate([
  35840. BABYLON.serializeAsTexture(),
  35841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35842. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35843. __decorate([
  35844. BABYLON.serialize(),
  35845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35846. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  35847. __decorate([
  35848. BABYLON.serialize(),
  35849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35850. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  35851. __decorate([
  35852. BABYLON.serializeAsTexture(),
  35853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  35854. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  35855. __decorate([
  35856. BABYLON.serializeAsColor3("emissive"),
  35857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35858. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  35859. __decorate([
  35860. BABYLON.serializeAsTexture(),
  35861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35862. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  35863. __decorate([
  35864. BABYLON.serialize(),
  35865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  35866. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  35867. __decorate([
  35868. BABYLON.serializeAsTexture(),
  35869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  35870. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  35871. __decorate([
  35872. BABYLON.serialize(),
  35873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  35874. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  35875. __decorate([
  35876. BABYLON.serialize()
  35877. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  35878. __decorate([
  35879. BABYLON.serialize()
  35880. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  35881. return PBRBaseSimpleMaterial;
  35882. }(BABYLON.PBRBaseMaterial));
  35883. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  35884. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35885. })(BABYLON || (BABYLON = {}));
  35886. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  35887. var BABYLON;
  35888. (function (BABYLON) {
  35889. /**
  35890. * The Physically based material of BJS.
  35891. *
  35892. * This offers the main features of a standard PBR material.
  35893. * For more information, please refer to the documentation :
  35894. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35895. */
  35896. var PBRMaterial = /** @class */ (function (_super) {
  35897. __extends(PBRMaterial, _super);
  35898. /**
  35899. * Instantiates a new PBRMaterial instance.
  35900. *
  35901. * @param name The material name
  35902. * @param scene The scene the material will be use in.
  35903. */
  35904. function PBRMaterial(name, scene) {
  35905. var _this = _super.call(this, name, scene) || this;
  35906. /**
  35907. * Intensity of the direct lights e.g. the four lights available in your scene.
  35908. * This impacts both the direct diffuse and specular highlights.
  35909. */
  35910. _this.directIntensity = 1.0;
  35911. /**
  35912. * Intensity of the emissive part of the material.
  35913. * This helps controlling the emissive effect without modifying the emissive color.
  35914. */
  35915. _this.emissiveIntensity = 1.0;
  35916. /**
  35917. * Intensity of the environment e.g. how much the environment will light the object
  35918. * either through harmonics for rough material or through the refelction for shiny ones.
  35919. */
  35920. _this.environmentIntensity = 1.0;
  35921. /**
  35922. * This is a special control allowing the reduction of the specular highlights coming from the
  35923. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35924. */
  35925. _this.specularIntensity = 1.0;
  35926. /**
  35927. * Debug Control allowing disabling the bump map on this material.
  35928. */
  35929. _this.disableBumpMap = false;
  35930. /**
  35931. * AKA Occlusion Texture Intensity in other nomenclature.
  35932. */
  35933. _this.ambientTextureStrength = 1.0;
  35934. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35935. /**
  35936. * AKA Diffuse Color in other nomenclature.
  35937. */
  35938. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35939. /**
  35940. * AKA Specular Color in other nomenclature.
  35941. */
  35942. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35943. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  35944. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35945. /**
  35946. * AKA Glossiness in other nomenclature.
  35947. */
  35948. _this.microSurface = 1.0;
  35949. /**
  35950. * source material index of refraction (IOR)' / 'destination material IOR.
  35951. */
  35952. _this.indexOfRefraction = 0.66;
  35953. /**
  35954. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35955. */
  35956. _this.invertRefractionY = false;
  35957. /**
  35958. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35959. * Materials half opaque for instance using refraction could benefit from this control.
  35960. */
  35961. _this.linkRefractionWithTransparency = false;
  35962. _this.useLightmapAsShadowmap = false;
  35963. /**
  35964. * Specifies that the alpha is coming form the albedo channel alpha channel.
  35965. */
  35966. _this.useAlphaFromAlbedoTexture = false;
  35967. /**
  35968. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35969. */
  35970. _this.forceAlphaTest = false;
  35971. /**
  35972. * Defines the alpha limits in alpha test mode.
  35973. */
  35974. _this.alphaCutOff = 0.4;
  35975. /**
  35976. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35977. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35978. */
  35979. _this.useSpecularOverAlpha = true;
  35980. /**
  35981. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35982. */
  35983. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  35984. /**
  35985. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35986. */
  35987. _this.useRoughnessFromMetallicTextureAlpha = true;
  35988. /**
  35989. * Specifies if the metallic texture contains the roughness information in its green channel.
  35990. */
  35991. _this.useRoughnessFromMetallicTextureGreen = false;
  35992. /**
  35993. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35994. */
  35995. _this.useMetallnessFromMetallicTextureBlue = false;
  35996. /**
  35997. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35998. */
  35999. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36000. /**
  36001. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36002. */
  36003. _this.useAmbientInGrayScale = false;
  36004. /**
  36005. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36006. * The material will try to infer what glossiness each pixel should be.
  36007. */
  36008. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36009. /**
  36010. * BJS is using an harcoded light falloff based on a manually sets up range.
  36011. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36012. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36013. */
  36014. _this.usePhysicalLightFalloff = true;
  36015. /**
  36016. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36017. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36018. */
  36019. _this.useRadianceOverAlpha = true;
  36020. /**
  36021. * Allows using the bump map in parallax mode.
  36022. */
  36023. _this.useParallax = false;
  36024. /**
  36025. * Allows using the bump map in parallax occlusion mode.
  36026. */
  36027. _this.useParallaxOcclusion = false;
  36028. /**
  36029. * Controls the scale bias of the parallax mode.
  36030. */
  36031. _this.parallaxScaleBias = 0.05;
  36032. /**
  36033. * If sets to true, disables all the lights affecting the material.
  36034. */
  36035. _this.disableLighting = false;
  36036. /**
  36037. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36038. */
  36039. _this.forceIrradianceInFragment = false;
  36040. /**
  36041. * Number of Simultaneous lights allowed on the material.
  36042. */
  36043. _this.maxSimultaneousLights = 4;
  36044. /**
  36045. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36046. */
  36047. _this.invertNormalMapX = false;
  36048. /**
  36049. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36050. */
  36051. _this.invertNormalMapY = false;
  36052. /**
  36053. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36054. */
  36055. _this.twoSidedLighting = false;
  36056. /**
  36057. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36058. * And/Or occlude the blended part.
  36059. */
  36060. _this.useAlphaFresnel = false;
  36061. /**
  36062. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36063. * And/Or occlude the blended part.
  36064. */
  36065. _this.environmentBRDFTexture = null;
  36066. /**
  36067. * Force normal to face away from face.
  36068. * (Temporary internal fix to remove before 3.1)
  36069. */
  36070. _this.forceNormalForward = false;
  36071. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36072. return _this;
  36073. }
  36074. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36075. /**
  36076. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36077. */
  36078. get: function () {
  36079. return this._PBRMATERIAL_OPAQUE;
  36080. },
  36081. enumerable: true,
  36082. configurable: true
  36083. });
  36084. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36085. /**
  36086. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36087. */
  36088. get: function () {
  36089. return this._PBRMATERIAL_ALPHATEST;
  36090. },
  36091. enumerable: true,
  36092. configurable: true
  36093. });
  36094. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36095. /**
  36096. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36097. */
  36098. get: function () {
  36099. return this._PBRMATERIAL_ALPHABLEND;
  36100. },
  36101. enumerable: true,
  36102. configurable: true
  36103. });
  36104. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36105. /**
  36106. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36107. * They are also discarded below the alpha cutoff threshold to improve performances.
  36108. */
  36109. get: function () {
  36110. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36111. },
  36112. enumerable: true,
  36113. configurable: true
  36114. });
  36115. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36116. /**
  36117. * Gets the image processing configuration used either in this material.
  36118. */
  36119. get: function () {
  36120. return this._imageProcessingConfiguration;
  36121. },
  36122. /**
  36123. * Sets the Default image processing configuration used either in the this material.
  36124. *
  36125. * If sets to null, the scene one is in use.
  36126. */
  36127. set: function (value) {
  36128. this._attachImageProcessingConfiguration(value);
  36129. // Ensure the effect will be rebuilt.
  36130. this._markAllSubMeshesAsTexturesDirty();
  36131. },
  36132. enumerable: true,
  36133. configurable: true
  36134. });
  36135. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36136. /**
  36137. * Gets wether the color curves effect is enabled.
  36138. */
  36139. get: function () {
  36140. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36141. },
  36142. /**
  36143. * Sets wether the color curves effect is enabled.
  36144. */
  36145. set: function (value) {
  36146. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36147. },
  36148. enumerable: true,
  36149. configurable: true
  36150. });
  36151. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36152. /**
  36153. * Gets wether the color grading effect is enabled.
  36154. */
  36155. get: function () {
  36156. return this.imageProcessingConfiguration.colorGradingEnabled;
  36157. },
  36158. /**
  36159. * Gets wether the color grading effect is enabled.
  36160. */
  36161. set: function (value) {
  36162. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36163. },
  36164. enumerable: true,
  36165. configurable: true
  36166. });
  36167. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36168. /**
  36169. * Gets wether tonemapping is enabled or not.
  36170. */
  36171. get: function () {
  36172. return this._imageProcessingConfiguration.toneMappingEnabled;
  36173. },
  36174. /**
  36175. * Sets wether tonemapping is enabled or not
  36176. */
  36177. set: function (value) {
  36178. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36179. },
  36180. enumerable: true,
  36181. configurable: true
  36182. });
  36183. ;
  36184. ;
  36185. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36186. /**
  36187. * The camera exposure used on this material.
  36188. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36189. * This corresponds to a photographic exposure.
  36190. */
  36191. get: function () {
  36192. return this._imageProcessingConfiguration.exposure;
  36193. },
  36194. /**
  36195. * The camera exposure used on this material.
  36196. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36197. * This corresponds to a photographic exposure.
  36198. */
  36199. set: function (value) {
  36200. this._imageProcessingConfiguration.exposure = value;
  36201. },
  36202. enumerable: true,
  36203. configurable: true
  36204. });
  36205. ;
  36206. ;
  36207. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36208. /**
  36209. * Gets The camera contrast used on this material.
  36210. */
  36211. get: function () {
  36212. return this._imageProcessingConfiguration.contrast;
  36213. },
  36214. /**
  36215. * Sets The camera contrast used on this material.
  36216. */
  36217. set: function (value) {
  36218. this._imageProcessingConfiguration.contrast = value;
  36219. },
  36220. enumerable: true,
  36221. configurable: true
  36222. });
  36223. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36224. /**
  36225. * Gets the Color Grading 2D Lookup Texture.
  36226. */
  36227. get: function () {
  36228. return this._imageProcessingConfiguration.colorGradingTexture;
  36229. },
  36230. /**
  36231. * Sets the Color Grading 2D Lookup Texture.
  36232. */
  36233. set: function (value) {
  36234. this._imageProcessingConfiguration.colorGradingTexture = value;
  36235. },
  36236. enumerable: true,
  36237. configurable: true
  36238. });
  36239. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36240. /**
  36241. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36242. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36243. * 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;
  36244. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36245. */
  36246. get: function () {
  36247. return this._imageProcessingConfiguration.colorCurves;
  36248. },
  36249. /**
  36250. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36251. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36252. * 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;
  36253. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36254. */
  36255. set: function (value) {
  36256. this._imageProcessingConfiguration.colorCurves = value;
  36257. },
  36258. enumerable: true,
  36259. configurable: true
  36260. });
  36261. PBRMaterial.prototype.getClassName = function () {
  36262. return "PBRMaterial";
  36263. };
  36264. PBRMaterial.prototype.getActiveTextures = function () {
  36265. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36266. if (this._albedoTexture) {
  36267. activeTextures.push(this._albedoTexture);
  36268. }
  36269. if (this._ambientTexture) {
  36270. activeTextures.push(this._ambientTexture);
  36271. }
  36272. if (this._opacityTexture) {
  36273. activeTextures.push(this._opacityTexture);
  36274. }
  36275. if (this._reflectionTexture) {
  36276. activeTextures.push(this._reflectionTexture);
  36277. }
  36278. if (this._emissiveTexture) {
  36279. activeTextures.push(this._emissiveTexture);
  36280. }
  36281. if (this._reflectivityTexture) {
  36282. activeTextures.push(this._reflectivityTexture);
  36283. }
  36284. if (this._metallicTexture) {
  36285. activeTextures.push(this._metallicTexture);
  36286. }
  36287. if (this._microSurfaceTexture) {
  36288. activeTextures.push(this._microSurfaceTexture);
  36289. }
  36290. if (this._bumpTexture) {
  36291. activeTextures.push(this._bumpTexture);
  36292. }
  36293. if (this._lightmapTexture) {
  36294. activeTextures.push(this._lightmapTexture);
  36295. }
  36296. if (this._refractionTexture) {
  36297. activeTextures.push(this._refractionTexture);
  36298. }
  36299. return activeTextures;
  36300. };
  36301. PBRMaterial.prototype.hasTexture = function (texture) {
  36302. if (_super.prototype.hasTexture.call(this, texture)) {
  36303. return true;
  36304. }
  36305. if (this._albedoTexture === texture) {
  36306. return true;
  36307. }
  36308. if (this._ambientTexture === texture) {
  36309. return true;
  36310. }
  36311. if (this._opacityTexture === texture) {
  36312. return true;
  36313. }
  36314. if (this._reflectionTexture === texture) {
  36315. return true;
  36316. }
  36317. if (this._reflectivityTexture === texture) {
  36318. return true;
  36319. }
  36320. if (this._metallicTexture === texture) {
  36321. return true;
  36322. }
  36323. if (this._microSurfaceTexture === texture) {
  36324. return true;
  36325. }
  36326. if (this._bumpTexture === texture) {
  36327. return true;
  36328. }
  36329. if (this._lightmapTexture === texture) {
  36330. return true;
  36331. }
  36332. if (this._refractionTexture === texture) {
  36333. return true;
  36334. }
  36335. return false;
  36336. };
  36337. PBRMaterial.prototype.clone = function (name) {
  36338. var _this = this;
  36339. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36340. clone.id = name;
  36341. clone.name = name;
  36342. return clone;
  36343. };
  36344. PBRMaterial.prototype.serialize = function () {
  36345. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36346. serializationObject.customType = "BABYLON.PBRMaterial";
  36347. return serializationObject;
  36348. };
  36349. // Statics
  36350. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36351. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36352. };
  36353. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36354. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36355. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36356. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36357. __decorate([
  36358. BABYLON.serialize(),
  36359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36360. ], PBRMaterial.prototype, "directIntensity", void 0);
  36361. __decorate([
  36362. BABYLON.serialize(),
  36363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36364. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36365. __decorate([
  36366. BABYLON.serialize(),
  36367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36368. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36369. __decorate([
  36370. BABYLON.serialize(),
  36371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36372. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36373. __decorate([
  36374. BABYLON.serialize(),
  36375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36376. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36377. __decorate([
  36378. BABYLON.serializeAsTexture(),
  36379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36380. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36381. __decorate([
  36382. BABYLON.serializeAsTexture(),
  36383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36384. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36385. __decorate([
  36386. BABYLON.serialize(),
  36387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36388. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36389. __decorate([
  36390. BABYLON.serializeAsTexture(),
  36391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36392. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36393. __decorate([
  36394. BABYLON.serializeAsTexture(),
  36395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36396. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36397. __decorate([
  36398. BABYLON.serializeAsTexture(),
  36399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36400. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36401. __decorate([
  36402. BABYLON.serializeAsTexture(),
  36403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36404. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36405. __decorate([
  36406. BABYLON.serializeAsTexture(),
  36407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36408. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36409. __decorate([
  36410. BABYLON.serialize(),
  36411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36412. ], PBRMaterial.prototype, "metallic", void 0);
  36413. __decorate([
  36414. BABYLON.serialize(),
  36415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36416. ], PBRMaterial.prototype, "roughness", void 0);
  36417. __decorate([
  36418. BABYLON.serializeAsTexture(),
  36419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36420. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36421. __decorate([
  36422. BABYLON.serializeAsTexture(),
  36423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36424. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36425. __decorate([
  36426. BABYLON.serializeAsTexture(),
  36427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36428. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36429. __decorate([
  36430. BABYLON.serializeAsTexture(),
  36431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36432. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36433. __decorate([
  36434. BABYLON.serializeAsColor3("ambient"),
  36435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36436. ], PBRMaterial.prototype, "ambientColor", void 0);
  36437. __decorate([
  36438. BABYLON.serializeAsColor3("albedo"),
  36439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36440. ], PBRMaterial.prototype, "albedoColor", void 0);
  36441. __decorate([
  36442. BABYLON.serializeAsColor3("reflectivity"),
  36443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36444. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36445. __decorate([
  36446. BABYLON.serializeAsColor3("reflection"),
  36447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36448. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36449. __decorate([
  36450. BABYLON.serializeAsColor3("emissive"),
  36451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36452. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36453. __decorate([
  36454. BABYLON.serialize(),
  36455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36456. ], PBRMaterial.prototype, "microSurface", void 0);
  36457. __decorate([
  36458. BABYLON.serialize(),
  36459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36460. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36461. __decorate([
  36462. BABYLON.serialize(),
  36463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36464. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36465. __decorate([
  36466. BABYLON.serialize(),
  36467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36468. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36469. __decorate([
  36470. BABYLON.serialize(),
  36471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36472. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36473. __decorate([
  36474. BABYLON.serialize(),
  36475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36476. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36477. __decorate([
  36478. BABYLON.serialize(),
  36479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36480. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  36481. __decorate([
  36482. BABYLON.serialize(),
  36483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36484. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  36485. __decorate([
  36486. BABYLON.serialize(),
  36487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36488. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36489. __decorate([
  36490. BABYLON.serialize(),
  36491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36492. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36493. __decorate([
  36494. BABYLON.serialize(),
  36495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36496. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36497. __decorate([
  36498. BABYLON.serialize(),
  36499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36500. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36501. __decorate([
  36502. BABYLON.serialize(),
  36503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36504. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36505. __decorate([
  36506. BABYLON.serialize(),
  36507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36508. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36509. __decorate([
  36510. BABYLON.serialize(),
  36511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36512. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36513. __decorate([
  36514. BABYLON.serialize(),
  36515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36516. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36517. __decorate([
  36518. BABYLON.serialize(),
  36519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36520. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36521. __decorate([
  36522. BABYLON.serialize(),
  36523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36524. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36525. __decorate([
  36526. BABYLON.serialize(),
  36527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36528. ], PBRMaterial.prototype, "useParallax", void 0);
  36529. __decorate([
  36530. BABYLON.serialize(),
  36531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36532. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36533. __decorate([
  36534. BABYLON.serialize(),
  36535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36536. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36537. __decorate([
  36538. BABYLON.serialize(),
  36539. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36540. ], PBRMaterial.prototype, "disableLighting", void 0);
  36541. __decorate([
  36542. BABYLON.serialize(),
  36543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36544. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  36545. __decorate([
  36546. BABYLON.serialize(),
  36547. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36548. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36549. __decorate([
  36550. BABYLON.serialize(),
  36551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36552. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36553. __decorate([
  36554. BABYLON.serialize(),
  36555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36556. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36557. __decorate([
  36558. BABYLON.serialize(),
  36559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36560. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36561. __decorate([
  36562. BABYLON.serialize(),
  36563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36564. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36565. __decorate([
  36566. BABYLON.serializeAsTexture(),
  36567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36568. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36569. __decorate([
  36570. BABYLON.serialize(),
  36571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36572. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36573. return PBRMaterial;
  36574. }(BABYLON.PBRBaseMaterial));
  36575. BABYLON.PBRMaterial = PBRMaterial;
  36576. })(BABYLON || (BABYLON = {}));
  36577. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36578. var BABYLON;
  36579. (function (BABYLON) {
  36580. /**
  36581. * The PBR material of BJS following the metal roughness convention.
  36582. *
  36583. * This fits to the PBR convention in the GLTF definition:
  36584. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36585. */
  36586. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36587. __extends(PBRMetallicRoughnessMaterial, _super);
  36588. /**
  36589. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36590. *
  36591. * @param name The material name
  36592. * @param scene The scene the material will be use in.
  36593. */
  36594. function PBRMetallicRoughnessMaterial(name, scene) {
  36595. var _this = _super.call(this, name, scene) || this;
  36596. _this._useRoughnessFromMetallicTextureAlpha = false;
  36597. _this._useRoughnessFromMetallicTextureGreen = true;
  36598. _this._useMetallnessFromMetallicTextureBlue = true;
  36599. return _this;
  36600. }
  36601. /**
  36602. * Return the currrent class name of the material.
  36603. */
  36604. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36605. return "PBRMetallicRoughnessMaterial";
  36606. };
  36607. /**
  36608. * Return the active textures of the material.
  36609. */
  36610. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36611. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36612. if (this.baseTexture) {
  36613. activeTextures.push(this.baseTexture);
  36614. }
  36615. if (this.metallicRoughnessTexture) {
  36616. activeTextures.push(this.metallicRoughnessTexture);
  36617. }
  36618. return activeTextures;
  36619. };
  36620. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36621. if (_super.prototype.hasTexture.call(this, texture)) {
  36622. return true;
  36623. }
  36624. if (this.baseTexture === texture) {
  36625. return true;
  36626. }
  36627. if (this.metallicRoughnessTexture === texture) {
  36628. return true;
  36629. }
  36630. return false;
  36631. };
  36632. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36633. var _this = this;
  36634. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36635. clone.id = name;
  36636. clone.name = name;
  36637. return clone;
  36638. };
  36639. /**
  36640. * Serialize the material to a parsable JSON object.
  36641. */
  36642. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36643. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36644. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36645. return serializationObject;
  36646. };
  36647. /**
  36648. * Parses a JSON object correponding to the serialize function.
  36649. */
  36650. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36651. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36652. };
  36653. __decorate([
  36654. BABYLON.serializeAsColor3(),
  36655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36656. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36657. __decorate([
  36658. BABYLON.serializeAsTexture(),
  36659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36660. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36661. __decorate([
  36662. BABYLON.serialize(),
  36663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36664. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36665. __decorate([
  36666. BABYLON.serialize(),
  36667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36668. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36669. __decorate([
  36670. BABYLON.serializeAsTexture(),
  36671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36672. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36673. return PBRMetallicRoughnessMaterial;
  36674. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36675. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36676. })(BABYLON || (BABYLON = {}));
  36677. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36678. var BABYLON;
  36679. (function (BABYLON) {
  36680. /**
  36681. * The PBR material of BJS following the specular glossiness convention.
  36682. *
  36683. * This fits to the PBR convention in the GLTF definition:
  36684. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36685. */
  36686. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  36687. __extends(PBRSpecularGlossinessMaterial, _super);
  36688. /**
  36689. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36690. *
  36691. * @param name The material name
  36692. * @param scene The scene the material will be use in.
  36693. */
  36694. function PBRSpecularGlossinessMaterial(name, scene) {
  36695. var _this = _super.call(this, name, scene) || this;
  36696. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36697. return _this;
  36698. }
  36699. /**
  36700. * Return the currrent class name of the material.
  36701. */
  36702. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36703. return "PBRSpecularGlossinessMaterial";
  36704. };
  36705. /**
  36706. * Return the active textures of the material.
  36707. */
  36708. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36709. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36710. if (this.diffuseTexture) {
  36711. activeTextures.push(this.diffuseTexture);
  36712. }
  36713. if (this.specularGlossinessTexture) {
  36714. activeTextures.push(this.specularGlossinessTexture);
  36715. }
  36716. return activeTextures;
  36717. };
  36718. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  36719. if (_super.prototype.hasTexture.call(this, texture)) {
  36720. return true;
  36721. }
  36722. if (this.diffuseTexture === texture) {
  36723. return true;
  36724. }
  36725. if (this.specularGlossinessTexture === texture) {
  36726. return true;
  36727. }
  36728. return false;
  36729. };
  36730. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36731. var _this = this;
  36732. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36733. clone.id = name;
  36734. clone.name = name;
  36735. return clone;
  36736. };
  36737. /**
  36738. * Serialize the material to a parsable JSON object.
  36739. */
  36740. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36741. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36742. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36743. return serializationObject;
  36744. };
  36745. /**
  36746. * Parses a JSON object correponding to the serialize function.
  36747. */
  36748. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36749. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36750. };
  36751. __decorate([
  36752. BABYLON.serializeAsColor3("diffuse"),
  36753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36754. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36755. __decorate([
  36756. BABYLON.serializeAsTexture(),
  36757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36758. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36759. __decorate([
  36760. BABYLON.serializeAsColor3("specular"),
  36761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36762. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36763. __decorate([
  36764. BABYLON.serialize(),
  36765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36766. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36767. __decorate([
  36768. BABYLON.serializeAsTexture(),
  36769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36770. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36771. return PBRSpecularGlossinessMaterial;
  36772. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36773. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36774. })(BABYLON || (BABYLON = {}));
  36775. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36776. var BABYLON;
  36777. (function (BABYLON) {
  36778. BABYLON.CameraInputTypes = {};
  36779. var CameraInputsManager = /** @class */ (function () {
  36780. function CameraInputsManager(camera) {
  36781. this.attached = {};
  36782. this.camera = camera;
  36783. this.checkInputs = function () { };
  36784. }
  36785. CameraInputsManager.prototype.add = function (input) {
  36786. var type = input.getSimpleName();
  36787. if (this.attached[type]) {
  36788. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  36789. return;
  36790. }
  36791. this.attached[type] = input;
  36792. input.camera = this.camera;
  36793. //for checkInputs, we are dynamically creating a function
  36794. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  36795. if (input.checkInputs) {
  36796. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36797. }
  36798. if (this.attachedElement) {
  36799. input.attachControl(this.attachedElement);
  36800. }
  36801. };
  36802. CameraInputsManager.prototype.remove = function (inputToRemove) {
  36803. for (var cam in this.attached) {
  36804. var input = this.attached[cam];
  36805. if (input === inputToRemove) {
  36806. input.detachControl(this.attachedElement);
  36807. input.camera = null;
  36808. delete this.attached[cam];
  36809. this.rebuildInputCheck();
  36810. }
  36811. }
  36812. };
  36813. CameraInputsManager.prototype.removeByType = function (inputType) {
  36814. for (var cam in this.attached) {
  36815. var input = this.attached[cam];
  36816. if (input.getClassName() === inputType) {
  36817. input.detachControl(this.attachedElement);
  36818. input.camera = null;
  36819. delete this.attached[cam];
  36820. this.rebuildInputCheck();
  36821. }
  36822. }
  36823. };
  36824. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  36825. var current = this.checkInputs;
  36826. return function () {
  36827. current();
  36828. fn();
  36829. };
  36830. };
  36831. CameraInputsManager.prototype.attachInput = function (input) {
  36832. if (this.attachedElement) {
  36833. input.attachControl(this.attachedElement, this.noPreventDefault);
  36834. }
  36835. };
  36836. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  36837. if (noPreventDefault === void 0) { noPreventDefault = false; }
  36838. if (this.attachedElement) {
  36839. return;
  36840. }
  36841. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  36842. this.attachedElement = element;
  36843. this.noPreventDefault = noPreventDefault;
  36844. for (var cam in this.attached) {
  36845. this.attached[cam].attachControl(element, noPreventDefault);
  36846. }
  36847. };
  36848. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  36849. if (disconnect === void 0) { disconnect = false; }
  36850. if (this.attachedElement !== element) {
  36851. return;
  36852. }
  36853. for (var cam in this.attached) {
  36854. this.attached[cam].detachControl(element);
  36855. if (disconnect) {
  36856. this.attached[cam].camera = null;
  36857. }
  36858. }
  36859. this.attachedElement = null;
  36860. };
  36861. CameraInputsManager.prototype.rebuildInputCheck = function () {
  36862. this.checkInputs = function () { };
  36863. for (var cam in this.attached) {
  36864. var input = this.attached[cam];
  36865. if (input.checkInputs) {
  36866. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36867. }
  36868. }
  36869. };
  36870. CameraInputsManager.prototype.clear = function () {
  36871. if (this.attachedElement) {
  36872. this.detachElement(this.attachedElement, true);
  36873. }
  36874. this.attached = {};
  36875. this.attachedElement = null;
  36876. this.checkInputs = function () { };
  36877. };
  36878. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  36879. var inputs = {};
  36880. for (var cam in this.attached) {
  36881. var input = this.attached[cam];
  36882. var res = BABYLON.SerializationHelper.Serialize(input);
  36883. inputs[input.getClassName()] = res;
  36884. }
  36885. serializedCamera.inputsmgr = inputs;
  36886. };
  36887. CameraInputsManager.prototype.parse = function (parsedCamera) {
  36888. var parsedInputs = parsedCamera.inputsmgr;
  36889. if (parsedInputs) {
  36890. this.clear();
  36891. for (var n in parsedInputs) {
  36892. var construct = BABYLON.CameraInputTypes[n];
  36893. if (construct) {
  36894. var parsedinput = parsedInputs[n];
  36895. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  36896. this.add(input);
  36897. }
  36898. }
  36899. }
  36900. else {
  36901. //2016-03-08 this part is for managing backward compatibility
  36902. for (var n in this.attached) {
  36903. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  36904. if (construct) {
  36905. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  36906. this.remove(this.attached[n]);
  36907. this.add(input);
  36908. }
  36909. }
  36910. }
  36911. };
  36912. return CameraInputsManager;
  36913. }());
  36914. BABYLON.CameraInputsManager = CameraInputsManager;
  36915. })(BABYLON || (BABYLON = {}));
  36916. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  36917. var BABYLON;
  36918. (function (BABYLON) {
  36919. var FreeCameraMouseInput = /** @class */ (function () {
  36920. function FreeCameraMouseInput(touchEnabled) {
  36921. if (touchEnabled === void 0) { touchEnabled = true; }
  36922. this.touchEnabled = touchEnabled;
  36923. this.buttons = [0, 1, 2];
  36924. this.angularSensibility = 2000.0;
  36925. this.previousPosition = null;
  36926. }
  36927. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  36928. var _this = this;
  36929. var engine = this.camera.getEngine();
  36930. if (!this._pointerInput) {
  36931. this._pointerInput = function (p, s) {
  36932. var evt = p.event;
  36933. if (engine.isInVRExclusivePointerMode) {
  36934. return;
  36935. }
  36936. if (!_this.touchEnabled && evt.pointerType === "touch") {
  36937. return;
  36938. }
  36939. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  36940. return;
  36941. }
  36942. var srcElement = (evt.srcElement || evt.target);
  36943. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  36944. try {
  36945. srcElement.setPointerCapture(evt.pointerId);
  36946. }
  36947. catch (e) {
  36948. //Nothing to do with the error. Execution will continue.
  36949. }
  36950. _this.previousPosition = {
  36951. x: evt.clientX,
  36952. y: evt.clientY
  36953. };
  36954. if (!noPreventDefault) {
  36955. evt.preventDefault();
  36956. element.focus();
  36957. }
  36958. }
  36959. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  36960. try {
  36961. srcElement.releasePointerCapture(evt.pointerId);
  36962. }
  36963. catch (e) {
  36964. //Nothing to do with the error.
  36965. }
  36966. _this.previousPosition = null;
  36967. if (!noPreventDefault) {
  36968. evt.preventDefault();
  36969. }
  36970. }
  36971. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  36972. if (!_this.previousPosition || engine.isPointerLock) {
  36973. return;
  36974. }
  36975. var offsetX = evt.clientX - _this.previousPosition.x;
  36976. var offsetY = evt.clientY - _this.previousPosition.y;
  36977. if (_this.camera.getScene().useRightHandedSystem) {
  36978. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  36979. }
  36980. else {
  36981. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  36982. }
  36983. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  36984. _this.previousPosition = {
  36985. x: evt.clientX,
  36986. y: evt.clientY
  36987. };
  36988. if (!noPreventDefault) {
  36989. evt.preventDefault();
  36990. }
  36991. }
  36992. };
  36993. }
  36994. this._onMouseMove = function (evt) {
  36995. if (!engine.isPointerLock) {
  36996. return;
  36997. }
  36998. if (engine.isInVRExclusivePointerMode) {
  36999. return;
  37000. }
  37001. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37002. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37003. if (_this.camera.getScene().useRightHandedSystem) {
  37004. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37005. }
  37006. else {
  37007. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37008. }
  37009. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37010. _this.previousPosition = null;
  37011. if (!noPreventDefault) {
  37012. evt.preventDefault();
  37013. }
  37014. };
  37015. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37016. element.addEventListener("mousemove", this._onMouseMove, false);
  37017. };
  37018. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37019. if (this._observer && element) {
  37020. this.camera.getScene().onPointerObservable.remove(this._observer);
  37021. if (this._onMouseMove) {
  37022. element.removeEventListener("mousemove", this._onMouseMove);
  37023. }
  37024. this._observer = null;
  37025. this._onMouseMove = null;
  37026. this.previousPosition = null;
  37027. }
  37028. };
  37029. FreeCameraMouseInput.prototype.getClassName = function () {
  37030. return "FreeCameraMouseInput";
  37031. };
  37032. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37033. return "mouse";
  37034. };
  37035. __decorate([
  37036. BABYLON.serialize()
  37037. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37038. __decorate([
  37039. BABYLON.serialize()
  37040. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37041. return FreeCameraMouseInput;
  37042. }());
  37043. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37044. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37045. })(BABYLON || (BABYLON = {}));
  37046. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37047. var BABYLON;
  37048. (function (BABYLON) {
  37049. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37050. function FreeCameraKeyboardMoveInput() {
  37051. this._keys = new Array();
  37052. this.keysUp = [38];
  37053. this.keysDown = [40];
  37054. this.keysLeft = [37];
  37055. this.keysRight = [39];
  37056. }
  37057. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37058. var _this = this;
  37059. if (this._onCanvasBlurObserver) {
  37060. return;
  37061. }
  37062. this._scene = this.camera.getScene();
  37063. this._engine = this._scene.getEngine();
  37064. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37065. _this._keys = [];
  37066. });
  37067. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37068. var evt = info.event;
  37069. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37070. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37071. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37072. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37073. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37074. var index = _this._keys.indexOf(evt.keyCode);
  37075. if (index === -1) {
  37076. _this._keys.push(evt.keyCode);
  37077. }
  37078. if (!noPreventDefault) {
  37079. evt.preventDefault();
  37080. }
  37081. }
  37082. }
  37083. else {
  37084. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37085. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37086. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37087. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37088. var index = _this._keys.indexOf(evt.keyCode);
  37089. if (index >= 0) {
  37090. _this._keys.splice(index, 1);
  37091. }
  37092. if (!noPreventDefault) {
  37093. evt.preventDefault();
  37094. }
  37095. }
  37096. }
  37097. });
  37098. };
  37099. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37100. if (this._scene) {
  37101. if (this._onKeyboardObserver) {
  37102. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37103. }
  37104. if (this._onCanvasBlurObserver) {
  37105. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37106. }
  37107. this._onKeyboardObserver = null;
  37108. this._onCanvasBlurObserver = null;
  37109. }
  37110. this._keys = [];
  37111. };
  37112. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37113. if (this._onKeyboardObserver) {
  37114. var camera = this.camera;
  37115. // Keyboard
  37116. for (var index = 0; index < this._keys.length; index++) {
  37117. var keyCode = this._keys[index];
  37118. var speed = camera._computeLocalCameraSpeed();
  37119. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37120. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37121. }
  37122. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37123. camera._localDirection.copyFromFloats(0, 0, speed);
  37124. }
  37125. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37126. camera._localDirection.copyFromFloats(speed, 0, 0);
  37127. }
  37128. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37129. camera._localDirection.copyFromFloats(0, 0, -speed);
  37130. }
  37131. if (camera.getScene().useRightHandedSystem) {
  37132. camera._localDirection.z *= -1;
  37133. }
  37134. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37135. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37136. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37137. }
  37138. }
  37139. };
  37140. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37141. return "FreeCameraKeyboardMoveInput";
  37142. };
  37143. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37144. this._keys = [];
  37145. };
  37146. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37147. return "keyboard";
  37148. };
  37149. __decorate([
  37150. BABYLON.serialize()
  37151. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37152. __decorate([
  37153. BABYLON.serialize()
  37154. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37155. __decorate([
  37156. BABYLON.serialize()
  37157. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37158. __decorate([
  37159. BABYLON.serialize()
  37160. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37161. return FreeCameraKeyboardMoveInput;
  37162. }());
  37163. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37164. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37165. })(BABYLON || (BABYLON = {}));
  37166. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37167. var BABYLON;
  37168. (function (BABYLON) {
  37169. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37170. __extends(FreeCameraInputsManager, _super);
  37171. function FreeCameraInputsManager(camera) {
  37172. return _super.call(this, camera) || this;
  37173. }
  37174. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37175. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37176. return this;
  37177. };
  37178. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37179. if (touchEnabled === void 0) { touchEnabled = true; }
  37180. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37181. return this;
  37182. };
  37183. FreeCameraInputsManager.prototype.addGamepad = function () {
  37184. this.add(new BABYLON.FreeCameraGamepadInput());
  37185. return this;
  37186. };
  37187. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37188. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37189. return this;
  37190. };
  37191. FreeCameraInputsManager.prototype.addTouch = function () {
  37192. this.add(new BABYLON.FreeCameraTouchInput());
  37193. return this;
  37194. };
  37195. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37196. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37197. return this;
  37198. };
  37199. return FreeCameraInputsManager;
  37200. }(BABYLON.CameraInputsManager));
  37201. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37202. })(BABYLON || (BABYLON = {}));
  37203. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37204. var BABYLON;
  37205. (function (BABYLON) {
  37206. var TargetCamera = /** @class */ (function (_super) {
  37207. __extends(TargetCamera, _super);
  37208. function TargetCamera(name, position, scene) {
  37209. var _this = _super.call(this, name, position, scene) || this;
  37210. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37211. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37212. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37213. _this.speed = 2.0;
  37214. _this.noRotationConstraint = false;
  37215. _this.lockedTarget = null;
  37216. _this._currentTarget = BABYLON.Vector3.Zero();
  37217. _this._viewMatrix = BABYLON.Matrix.Zero();
  37218. _this._camMatrix = BABYLON.Matrix.Zero();
  37219. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37220. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37221. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37222. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37223. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37224. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37225. _this._tempMatrix = BABYLON.Matrix.Zero();
  37226. return _this;
  37227. }
  37228. TargetCamera.prototype.getFrontPosition = function (distance) {
  37229. var direction = this.getTarget().subtract(this.position);
  37230. direction.normalize();
  37231. direction.scaleInPlace(distance);
  37232. return this.globalPosition.add(direction);
  37233. };
  37234. TargetCamera.prototype._getLockedTargetPosition = function () {
  37235. if (!this.lockedTarget) {
  37236. return null;
  37237. }
  37238. if (this.lockedTarget.absolutePosition) {
  37239. this.lockedTarget.computeWorldMatrix();
  37240. }
  37241. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37242. };
  37243. TargetCamera.prototype.storeState = function () {
  37244. this._storedPosition = this.position.clone();
  37245. this._storedRotation = this.rotation.clone();
  37246. if (this.rotationQuaternion) {
  37247. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37248. }
  37249. return _super.prototype.storeState.call(this);
  37250. };
  37251. /**
  37252. * Restored camera state. You must call storeState() first
  37253. */
  37254. TargetCamera.prototype._restoreStateValues = function () {
  37255. if (!_super.prototype._restoreStateValues.call(this)) {
  37256. return false;
  37257. }
  37258. this.position = this._storedPosition.clone();
  37259. this.rotation = this._storedRotation.clone();
  37260. if (this.rotationQuaternion) {
  37261. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37262. }
  37263. this.cameraDirection.copyFromFloats(0, 0, 0);
  37264. this.cameraRotation.copyFromFloats(0, 0);
  37265. return true;
  37266. };
  37267. // Cache
  37268. TargetCamera.prototype._initCache = function () {
  37269. _super.prototype._initCache.call(this);
  37270. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37271. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37272. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37273. };
  37274. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37275. if (!ignoreParentClass) {
  37276. _super.prototype._updateCache.call(this);
  37277. }
  37278. var lockedTargetPosition = this._getLockedTargetPosition();
  37279. if (!lockedTargetPosition) {
  37280. this._cache.lockedTarget = null;
  37281. }
  37282. else {
  37283. if (!this._cache.lockedTarget) {
  37284. this._cache.lockedTarget = lockedTargetPosition.clone();
  37285. }
  37286. else {
  37287. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37288. }
  37289. }
  37290. this._cache.rotation.copyFrom(this.rotation);
  37291. if (this.rotationQuaternion)
  37292. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37293. };
  37294. // Synchronized
  37295. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37296. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37297. return false;
  37298. }
  37299. var lockedTargetPosition = this._getLockedTargetPosition();
  37300. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37301. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37302. };
  37303. // Methods
  37304. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37305. var engine = this.getEngine();
  37306. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37307. };
  37308. // Target
  37309. TargetCamera.prototype.setTarget = function (target) {
  37310. this.upVector.normalize();
  37311. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37312. this._camMatrix.invert();
  37313. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37314. var vDir = target.subtract(this.position);
  37315. if (vDir.x >= 0.0) {
  37316. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37317. }
  37318. else {
  37319. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37320. }
  37321. this.rotation.z = 0;
  37322. if (isNaN(this.rotation.x)) {
  37323. this.rotation.x = 0;
  37324. }
  37325. if (isNaN(this.rotation.y)) {
  37326. this.rotation.y = 0;
  37327. }
  37328. if (isNaN(this.rotation.z)) {
  37329. this.rotation.z = 0;
  37330. }
  37331. if (this.rotationQuaternion) {
  37332. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37333. }
  37334. };
  37335. /**
  37336. * Return the current target position of the camera. This value is expressed in local space.
  37337. */
  37338. TargetCamera.prototype.getTarget = function () {
  37339. return this._currentTarget;
  37340. };
  37341. TargetCamera.prototype._decideIfNeedsToMove = function () {
  37342. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37343. };
  37344. TargetCamera.prototype._updatePosition = function () {
  37345. if (this.parent) {
  37346. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  37347. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  37348. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  37349. return;
  37350. }
  37351. this.position.addInPlace(this.cameraDirection);
  37352. };
  37353. TargetCamera.prototype._checkInputs = function () {
  37354. var needToMove = this._decideIfNeedsToMove();
  37355. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  37356. // Move
  37357. if (needToMove) {
  37358. this._updatePosition();
  37359. }
  37360. // Rotate
  37361. if (needToRotate) {
  37362. this.rotation.x += this.cameraRotation.x;
  37363. this.rotation.y += this.cameraRotation.y;
  37364. //rotate, if quaternion is set and rotation was used
  37365. if (this.rotationQuaternion) {
  37366. var len = this.rotation.lengthSquared();
  37367. if (len) {
  37368. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37369. }
  37370. }
  37371. if (!this.noRotationConstraint) {
  37372. var limit = (Math.PI / 2) * 0.95;
  37373. if (this.rotation.x > limit)
  37374. this.rotation.x = limit;
  37375. if (this.rotation.x < -limit)
  37376. this.rotation.x = -limit;
  37377. }
  37378. }
  37379. // Inertia
  37380. if (needToMove) {
  37381. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  37382. this.cameraDirection.x = 0;
  37383. }
  37384. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  37385. this.cameraDirection.y = 0;
  37386. }
  37387. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  37388. this.cameraDirection.z = 0;
  37389. }
  37390. this.cameraDirection.scaleInPlace(this.inertia);
  37391. }
  37392. if (needToRotate) {
  37393. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  37394. this.cameraRotation.x = 0;
  37395. }
  37396. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  37397. this.cameraRotation.y = 0;
  37398. }
  37399. this.cameraRotation.scaleInPlace(this.inertia);
  37400. }
  37401. _super.prototype._checkInputs.call(this);
  37402. };
  37403. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  37404. if (this.rotationQuaternion) {
  37405. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  37406. }
  37407. else {
  37408. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  37409. }
  37410. //update the up vector!
  37411. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  37412. };
  37413. TargetCamera.prototype._getViewMatrix = function () {
  37414. if (!this.lockedTarget) {
  37415. // Compute
  37416. this._updateCameraRotationMatrix();
  37417. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  37418. // Computing target and final matrix
  37419. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  37420. }
  37421. else {
  37422. var targetPosition = this._getLockedTargetPosition();
  37423. if (targetPosition) {
  37424. this._currentTarget.copyFrom(targetPosition);
  37425. }
  37426. }
  37427. if (this.getScene().useRightHandedSystem) {
  37428. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37429. }
  37430. else {
  37431. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37432. }
  37433. return this._viewMatrix;
  37434. };
  37435. /**
  37436. * @override
  37437. * Override Camera.createRigCamera
  37438. */
  37439. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37440. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  37441. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  37442. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  37443. if (!this.rotationQuaternion) {
  37444. this.rotationQuaternion = new BABYLON.Quaternion();
  37445. }
  37446. rigCamera._cameraRigParams = {};
  37447. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  37448. }
  37449. return rigCamera;
  37450. }
  37451. return null;
  37452. };
  37453. /**
  37454. * @override
  37455. * Override Camera._updateRigCameras
  37456. */
  37457. TargetCamera.prototype._updateRigCameras = function () {
  37458. var camLeft = this._rigCameras[0];
  37459. var camRight = this._rigCameras[1];
  37460. switch (this.cameraRigMode) {
  37461. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37462. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37463. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37464. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37465. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  37466. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  37467. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  37468. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  37469. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  37470. camLeft.setTarget(this.getTarget());
  37471. camRight.setTarget(this.getTarget());
  37472. break;
  37473. case BABYLON.Camera.RIG_MODE_VR:
  37474. if (camLeft.rotationQuaternion) {
  37475. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37476. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37477. }
  37478. else {
  37479. camLeft.rotation.copyFrom(this.rotation);
  37480. camRight.rotation.copyFrom(this.rotation);
  37481. }
  37482. camLeft.position.copyFrom(this.position);
  37483. camRight.position.copyFrom(this.position);
  37484. break;
  37485. }
  37486. _super.prototype._updateRigCameras.call(this);
  37487. };
  37488. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  37489. if (!this._rigCamTransformMatrix) {
  37490. this._rigCamTransformMatrix = new BABYLON.Matrix();
  37491. }
  37492. var target = this.getTarget();
  37493. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  37494. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  37495. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  37496. };
  37497. TargetCamera.prototype.getClassName = function () {
  37498. return "TargetCamera";
  37499. };
  37500. __decorate([
  37501. BABYLON.serializeAsVector3()
  37502. ], TargetCamera.prototype, "rotation", void 0);
  37503. __decorate([
  37504. BABYLON.serialize()
  37505. ], TargetCamera.prototype, "speed", void 0);
  37506. __decorate([
  37507. BABYLON.serializeAsMeshReference("lockedTargetId")
  37508. ], TargetCamera.prototype, "lockedTarget", void 0);
  37509. return TargetCamera;
  37510. }(BABYLON.Camera));
  37511. BABYLON.TargetCamera = TargetCamera;
  37512. })(BABYLON || (BABYLON = {}));
  37513. //# sourceMappingURL=babylon.targetCamera.js.map
  37514. var BABYLON;
  37515. (function (BABYLON) {
  37516. var FreeCamera = /** @class */ (function (_super) {
  37517. __extends(FreeCamera, _super);
  37518. function FreeCamera(name, position, scene) {
  37519. var _this = _super.call(this, name, position, scene) || this;
  37520. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  37521. _this.checkCollisions = false;
  37522. _this.applyGravity = false;
  37523. _this._needMoveForGravity = false;
  37524. _this._oldPosition = BABYLON.Vector3.Zero();
  37525. _this._diffPosition = BABYLON.Vector3.Zero();
  37526. _this._newPosition = BABYLON.Vector3.Zero();
  37527. // Collisions
  37528. _this._collisionMask = -1;
  37529. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37530. if (collidedMesh === void 0) { collidedMesh = null; }
  37531. //TODO move this to the collision coordinator!
  37532. if (_this.getScene().workerCollisions)
  37533. newPosition.multiplyInPlace(_this._collider.radius);
  37534. var updatePosition = function (newPos) {
  37535. _this._newPosition.copyFrom(newPos);
  37536. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  37537. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  37538. _this.position.addInPlace(_this._diffPosition);
  37539. if (_this.onCollide && collidedMesh) {
  37540. _this.onCollide(collidedMesh);
  37541. }
  37542. }
  37543. };
  37544. updatePosition(newPosition);
  37545. };
  37546. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  37547. _this.inputs.addKeyboard().addMouse();
  37548. return _this;
  37549. }
  37550. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  37551. //-- begin properties for backward compatibility for inputs
  37552. get: function () {
  37553. var mouse = this.inputs.attached["mouse"];
  37554. if (mouse)
  37555. return mouse.angularSensibility;
  37556. return 0;
  37557. },
  37558. set: function (value) {
  37559. var mouse = this.inputs.attached["mouse"];
  37560. if (mouse)
  37561. mouse.angularSensibility = value;
  37562. },
  37563. enumerable: true,
  37564. configurable: true
  37565. });
  37566. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37567. get: function () {
  37568. var keyboard = this.inputs.attached["keyboard"];
  37569. if (keyboard)
  37570. return keyboard.keysUp;
  37571. return [];
  37572. },
  37573. set: function (value) {
  37574. var keyboard = this.inputs.attached["keyboard"];
  37575. if (keyboard)
  37576. keyboard.keysUp = value;
  37577. },
  37578. enumerable: true,
  37579. configurable: true
  37580. });
  37581. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37582. get: function () {
  37583. var keyboard = this.inputs.attached["keyboard"];
  37584. if (keyboard)
  37585. return keyboard.keysDown;
  37586. return [];
  37587. },
  37588. set: function (value) {
  37589. var keyboard = this.inputs.attached["keyboard"];
  37590. if (keyboard)
  37591. keyboard.keysDown = value;
  37592. },
  37593. enumerable: true,
  37594. configurable: true
  37595. });
  37596. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37597. get: function () {
  37598. var keyboard = this.inputs.attached["keyboard"];
  37599. if (keyboard)
  37600. return keyboard.keysLeft;
  37601. return [];
  37602. },
  37603. set: function (value) {
  37604. var keyboard = this.inputs.attached["keyboard"];
  37605. if (keyboard)
  37606. keyboard.keysLeft = value;
  37607. },
  37608. enumerable: true,
  37609. configurable: true
  37610. });
  37611. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37612. get: function () {
  37613. var keyboard = this.inputs.attached["keyboard"];
  37614. if (keyboard)
  37615. return keyboard.keysRight;
  37616. return [];
  37617. },
  37618. set: function (value) {
  37619. var keyboard = this.inputs.attached["keyboard"];
  37620. if (keyboard)
  37621. keyboard.keysRight = value;
  37622. },
  37623. enumerable: true,
  37624. configurable: true
  37625. });
  37626. // Controls
  37627. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37628. this.inputs.attachElement(element, noPreventDefault);
  37629. };
  37630. FreeCamera.prototype.detachControl = function (element) {
  37631. this.inputs.detachElement(element);
  37632. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37633. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37634. };
  37635. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37636. get: function () {
  37637. return this._collisionMask;
  37638. },
  37639. set: function (mask) {
  37640. this._collisionMask = !isNaN(mask) ? mask : -1;
  37641. },
  37642. enumerable: true,
  37643. configurable: true
  37644. });
  37645. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37646. var globalPosition;
  37647. if (this.parent) {
  37648. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37649. }
  37650. else {
  37651. globalPosition = this.position;
  37652. }
  37653. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37654. if (!this._collider) {
  37655. this._collider = new BABYLON.Collider();
  37656. }
  37657. this._collider.radius = this.ellipsoid;
  37658. this._collider.collisionMask = this._collisionMask;
  37659. //no need for clone, as long as gravity is not on.
  37660. var actualDisplacement = displacement;
  37661. //add gravity to the direction to prevent the dual-collision checking
  37662. if (this.applyGravity) {
  37663. //this prevents mending with cameraDirection, a global variable of the free camera class.
  37664. actualDisplacement = displacement.add(this.getScene().gravity);
  37665. }
  37666. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37667. };
  37668. FreeCamera.prototype._checkInputs = function () {
  37669. if (!this._localDirection) {
  37670. this._localDirection = BABYLON.Vector3.Zero();
  37671. this._transformedDirection = BABYLON.Vector3.Zero();
  37672. }
  37673. this.inputs.checkInputs();
  37674. _super.prototype._checkInputs.call(this);
  37675. };
  37676. FreeCamera.prototype._decideIfNeedsToMove = function () {
  37677. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37678. };
  37679. FreeCamera.prototype._updatePosition = function () {
  37680. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  37681. this._collideWithWorld(this.cameraDirection);
  37682. }
  37683. else {
  37684. _super.prototype._updatePosition.call(this);
  37685. }
  37686. };
  37687. FreeCamera.prototype.dispose = function () {
  37688. this.inputs.clear();
  37689. _super.prototype.dispose.call(this);
  37690. };
  37691. FreeCamera.prototype.getClassName = function () {
  37692. return "FreeCamera";
  37693. };
  37694. __decorate([
  37695. BABYLON.serializeAsVector3()
  37696. ], FreeCamera.prototype, "ellipsoid", void 0);
  37697. __decorate([
  37698. BABYLON.serialize()
  37699. ], FreeCamera.prototype, "checkCollisions", void 0);
  37700. __decorate([
  37701. BABYLON.serialize()
  37702. ], FreeCamera.prototype, "applyGravity", void 0);
  37703. return FreeCamera;
  37704. }(BABYLON.TargetCamera));
  37705. BABYLON.FreeCamera = FreeCamera;
  37706. })(BABYLON || (BABYLON = {}));
  37707. //# sourceMappingURL=babylon.freeCamera.js.map
  37708. var BABYLON;
  37709. (function (BABYLON) {
  37710. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  37711. function ArcRotateCameraKeyboardMoveInput() {
  37712. this._keys = new Array();
  37713. this.keysUp = [38];
  37714. this.keysDown = [40];
  37715. this.keysLeft = [37];
  37716. this.keysRight = [39];
  37717. this.keysReset = [220];
  37718. this.panningSensibility = 50.0;
  37719. this.zoomingSensibility = 25.0;
  37720. this.useAltToZoom = true;
  37721. }
  37722. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37723. var _this = this;
  37724. if (this._onCanvasBlurObserver) {
  37725. return;
  37726. }
  37727. this._scene = this.camera.getScene();
  37728. this._engine = this._scene.getEngine();
  37729. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37730. _this._keys = [];
  37731. });
  37732. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37733. var evt = info.event;
  37734. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37735. _this._ctrlPressed = evt.ctrlKey;
  37736. _this._altPressed = evt.altKey;
  37737. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37738. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37739. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37740. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37741. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37742. var index = _this._keys.indexOf(evt.keyCode);
  37743. if (index === -1) {
  37744. _this._keys.push(evt.keyCode);
  37745. }
  37746. if (evt.preventDefault) {
  37747. if (!noPreventDefault) {
  37748. evt.preventDefault();
  37749. }
  37750. }
  37751. }
  37752. }
  37753. else {
  37754. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37755. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37756. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37757. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37758. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37759. var index = _this._keys.indexOf(evt.keyCode);
  37760. if (index >= 0) {
  37761. _this._keys.splice(index, 1);
  37762. }
  37763. if (evt.preventDefault) {
  37764. if (!noPreventDefault) {
  37765. evt.preventDefault();
  37766. }
  37767. }
  37768. }
  37769. }
  37770. });
  37771. };
  37772. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37773. if (this._scene) {
  37774. if (this._onKeyboardObserver) {
  37775. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37776. }
  37777. if (this._onCanvasBlurObserver) {
  37778. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37779. }
  37780. this._onKeyboardObserver = null;
  37781. this._onCanvasBlurObserver = null;
  37782. }
  37783. this._keys = [];
  37784. };
  37785. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37786. if (this._onKeyboardObserver) {
  37787. var camera = this.camera;
  37788. for (var index = 0; index < this._keys.length; index++) {
  37789. var keyCode = this._keys[index];
  37790. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37791. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37792. camera.inertialPanningX -= 1 / this.panningSensibility;
  37793. }
  37794. else {
  37795. camera.inertialAlphaOffset -= 0.01;
  37796. }
  37797. }
  37798. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37799. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37800. camera.inertialPanningY += 1 / this.panningSensibility;
  37801. }
  37802. else if (this._altPressed && this.useAltToZoom) {
  37803. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  37804. }
  37805. else {
  37806. camera.inertialBetaOffset -= 0.01;
  37807. }
  37808. }
  37809. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37810. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37811. camera.inertialPanningX += 1 / this.panningSensibility;
  37812. }
  37813. else {
  37814. camera.inertialAlphaOffset += 0.01;
  37815. }
  37816. }
  37817. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37818. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37819. camera.inertialPanningY -= 1 / this.panningSensibility;
  37820. }
  37821. else if (this._altPressed && this.useAltToZoom) {
  37822. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  37823. }
  37824. else {
  37825. camera.inertialBetaOffset += 0.01;
  37826. }
  37827. }
  37828. else if (this.keysReset.indexOf(keyCode) !== -1) {
  37829. camera.restoreState();
  37830. }
  37831. }
  37832. }
  37833. };
  37834. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  37835. return "ArcRotateCameraKeyboardMoveInput";
  37836. };
  37837. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37838. return "keyboard";
  37839. };
  37840. __decorate([
  37841. BABYLON.serialize()
  37842. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37843. __decorate([
  37844. BABYLON.serialize()
  37845. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37846. __decorate([
  37847. BABYLON.serialize()
  37848. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37849. __decorate([
  37850. BABYLON.serialize()
  37851. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37852. __decorate([
  37853. BABYLON.serialize()
  37854. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  37855. __decorate([
  37856. BABYLON.serialize()
  37857. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  37858. __decorate([
  37859. BABYLON.serialize()
  37860. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  37861. __decorate([
  37862. BABYLON.serialize()
  37863. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  37864. return ArcRotateCameraKeyboardMoveInput;
  37865. }());
  37866. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  37867. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  37868. })(BABYLON || (BABYLON = {}));
  37869. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  37870. var BABYLON;
  37871. (function (BABYLON) {
  37872. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  37873. function ArcRotateCameraMouseWheelInput() {
  37874. this.wheelPrecision = 3.0;
  37875. /**
  37876. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  37877. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  37878. */
  37879. this.wheelDeltaPercentage = 0;
  37880. }
  37881. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  37882. var _this = this;
  37883. this._wheel = function (p, s) {
  37884. //sanity check - this should be a PointerWheel event.
  37885. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  37886. return;
  37887. var event = p.event;
  37888. var delta = 0;
  37889. if (event.wheelDelta) {
  37890. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  37891. }
  37892. else if (event.detail) {
  37893. delta = -event.detail / _this.wheelPrecision;
  37894. }
  37895. if (delta)
  37896. _this.camera.inertialRadiusOffset += delta;
  37897. if (event.preventDefault) {
  37898. if (!noPreventDefault) {
  37899. event.preventDefault();
  37900. }
  37901. }
  37902. };
  37903. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  37904. };
  37905. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  37906. if (this._observer && element) {
  37907. this.camera.getScene().onPointerObservable.remove(this._observer);
  37908. this._observer = null;
  37909. this._wheel = null;
  37910. }
  37911. };
  37912. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  37913. return "ArcRotateCameraMouseWheelInput";
  37914. };
  37915. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  37916. return "mousewheel";
  37917. };
  37918. __decorate([
  37919. BABYLON.serialize()
  37920. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  37921. __decorate([
  37922. BABYLON.serialize()
  37923. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  37924. return ArcRotateCameraMouseWheelInput;
  37925. }());
  37926. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  37927. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  37928. })(BABYLON || (BABYLON = {}));
  37929. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  37930. var BABYLON;
  37931. (function (BABYLON) {
  37932. var ArcRotateCameraPointersInput = /** @class */ (function () {
  37933. function ArcRotateCameraPointersInput() {
  37934. this.buttons = [0, 1, 2];
  37935. this.angularSensibilityX = 1000.0;
  37936. this.angularSensibilityY = 1000.0;
  37937. this.pinchPrecision = 12.0;
  37938. /**
  37939. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  37940. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  37941. */
  37942. this.pinchDeltaPercentage = 0;
  37943. this.panningSensibility = 1000.0;
  37944. this.multiTouchPanning = true;
  37945. this.multiTouchPanAndZoom = true;
  37946. this._isPanClick = false;
  37947. this.pinchInwards = true;
  37948. }
  37949. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  37950. var _this = this;
  37951. var engine = this.camera.getEngine();
  37952. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  37953. var pointA = null;
  37954. var pointB = null;
  37955. var previousPinchSquaredDistance = 0;
  37956. var initialDistance = 0;
  37957. var twoFingerActivityCount = 0;
  37958. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  37959. this._pointerInput = function (p, s) {
  37960. var evt = p.event;
  37961. if (engine.isInVRExclusivePointerMode) {
  37962. return;
  37963. }
  37964. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37965. return;
  37966. }
  37967. var srcElement = (evt.srcElement || evt.target);
  37968. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37969. try {
  37970. srcElement.setPointerCapture(evt.pointerId);
  37971. }
  37972. catch (e) {
  37973. //Nothing to do with the error. Execution will continue.
  37974. }
  37975. // Manage panning with pan button click
  37976. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  37977. // manage pointers
  37978. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  37979. if (pointA === null) {
  37980. pointA = cacheSoloPointer;
  37981. }
  37982. else if (pointB === null) {
  37983. pointB = cacheSoloPointer;
  37984. }
  37985. if (!noPreventDefault) {
  37986. evt.preventDefault();
  37987. element.focus();
  37988. }
  37989. }
  37990. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  37991. _this.camera.restoreState();
  37992. }
  37993. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37994. try {
  37995. srcElement.releasePointerCapture(evt.pointerId);
  37996. }
  37997. catch (e) {
  37998. //Nothing to do with the error.
  37999. }
  38000. cacheSoloPointer = null;
  38001. previousPinchSquaredDistance = 0;
  38002. previousMultiTouchPanPosition.isPaning = false;
  38003. previousMultiTouchPanPosition.isPinching = false;
  38004. twoFingerActivityCount = 0;
  38005. initialDistance = 0;
  38006. if (p.event.pointerType !== "touch") {
  38007. pointB = null; // Mouse and pen are mono pointer
  38008. }
  38009. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38010. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38011. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38012. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38013. if (engine.badOS) {
  38014. pointA = pointB = null;
  38015. }
  38016. else {
  38017. //only remove the impacted pointer in case of multitouch allowing on most
  38018. //platforms switching from rotate to zoom and pan seamlessly.
  38019. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38020. pointA = pointB;
  38021. pointB = null;
  38022. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38023. }
  38024. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38025. pointB = null;
  38026. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38027. }
  38028. else {
  38029. pointA = pointB = null;
  38030. }
  38031. }
  38032. if (!noPreventDefault) {
  38033. evt.preventDefault();
  38034. }
  38035. }
  38036. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38037. if (!noPreventDefault) {
  38038. evt.preventDefault();
  38039. }
  38040. // One button down
  38041. if (pointA && pointB === null && cacheSoloPointer) {
  38042. if (_this.panningSensibility !== 0 &&
  38043. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38044. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38045. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38046. }
  38047. else {
  38048. var offsetX = evt.clientX - cacheSoloPointer.x;
  38049. var offsetY = evt.clientY - cacheSoloPointer.y;
  38050. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38051. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38052. }
  38053. cacheSoloPointer.x = evt.clientX;
  38054. cacheSoloPointer.y = evt.clientY;
  38055. }
  38056. else if (pointA && pointB) {
  38057. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38058. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38059. ed.x = evt.clientX;
  38060. ed.y = evt.clientY;
  38061. var direction = _this.pinchInwards ? 1 : -1;
  38062. var distX = pointA.x - pointB.x;
  38063. var distY = pointA.y - pointB.y;
  38064. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38065. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38066. if (previousPinchSquaredDistance === 0) {
  38067. initialDistance = pinchDistance;
  38068. previousPinchSquaredDistance = pinchSquaredDistance;
  38069. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38070. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38071. return;
  38072. }
  38073. if (_this.multiTouchPanAndZoom) {
  38074. if (_this.pinchDeltaPercentage) {
  38075. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38076. }
  38077. else {
  38078. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38079. (_this.pinchPrecision *
  38080. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38081. direction);
  38082. }
  38083. if (_this.panningSensibility !== 0) {
  38084. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38085. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38086. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38087. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38088. previousMultiTouchPanPosition.x = pointersCenterX;
  38089. previousMultiTouchPanPosition.y = pointersCenterY;
  38090. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38091. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38092. }
  38093. }
  38094. else {
  38095. twoFingerActivityCount++;
  38096. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38097. if (_this.pinchDeltaPercentage) {
  38098. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38099. }
  38100. else {
  38101. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38102. (_this.pinchPrecision *
  38103. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38104. direction);
  38105. }
  38106. previousMultiTouchPanPosition.isPaning = false;
  38107. previousMultiTouchPanPosition.isPinching = true;
  38108. }
  38109. else {
  38110. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38111. if (!previousMultiTouchPanPosition.isPaning) {
  38112. previousMultiTouchPanPosition.isPaning = true;
  38113. previousMultiTouchPanPosition.isPinching = false;
  38114. previousMultiTouchPanPosition.x = ed.x;
  38115. previousMultiTouchPanPosition.y = ed.y;
  38116. return;
  38117. }
  38118. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38119. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38120. }
  38121. }
  38122. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38123. previousMultiTouchPanPosition.x = ed.x;
  38124. previousMultiTouchPanPosition.y = ed.y;
  38125. }
  38126. }
  38127. previousPinchSquaredDistance = pinchSquaredDistance;
  38128. }
  38129. }
  38130. };
  38131. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38132. this._onContextMenu = function (evt) {
  38133. evt.preventDefault();
  38134. };
  38135. if (!this.camera._useCtrlForPanning) {
  38136. element.addEventListener("contextmenu", this._onContextMenu, false);
  38137. }
  38138. this._onLostFocus = function () {
  38139. //this._keys = [];
  38140. pointA = pointB = null;
  38141. previousPinchSquaredDistance = 0;
  38142. previousMultiTouchPanPosition.isPaning = false;
  38143. previousMultiTouchPanPosition.isPinching = false;
  38144. twoFingerActivityCount = 0;
  38145. cacheSoloPointer = null;
  38146. initialDistance = 0;
  38147. };
  38148. this._onMouseMove = function (evt) {
  38149. if (!engine.isPointerLock) {
  38150. return;
  38151. }
  38152. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38153. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38154. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38155. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38156. if (!noPreventDefault) {
  38157. evt.preventDefault();
  38158. }
  38159. };
  38160. this._onGestureStart = function (e) {
  38161. if (window.MSGesture === undefined) {
  38162. return;
  38163. }
  38164. if (!_this._MSGestureHandler) {
  38165. _this._MSGestureHandler = new MSGesture();
  38166. _this._MSGestureHandler.target = element;
  38167. }
  38168. _this._MSGestureHandler.addPointer(e.pointerId);
  38169. };
  38170. this._onGesture = function (e) {
  38171. _this.camera.radius *= e.scale;
  38172. if (e.preventDefault) {
  38173. if (!noPreventDefault) {
  38174. e.stopPropagation();
  38175. e.preventDefault();
  38176. }
  38177. }
  38178. };
  38179. element.addEventListener("mousemove", this._onMouseMove, false);
  38180. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38181. element.addEventListener("MSGestureChange", this._onGesture, false);
  38182. BABYLON.Tools.RegisterTopRootEvents([
  38183. { name: "blur", handler: this._onLostFocus }
  38184. ]);
  38185. };
  38186. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38187. if (this._onLostFocus) {
  38188. BABYLON.Tools.UnregisterTopRootEvents([
  38189. { name: "blur", handler: this._onLostFocus }
  38190. ]);
  38191. }
  38192. if (element && this._observer) {
  38193. this.camera.getScene().onPointerObservable.remove(this._observer);
  38194. this._observer = null;
  38195. if (this._onContextMenu) {
  38196. element.removeEventListener("contextmenu", this._onContextMenu);
  38197. }
  38198. if (this._onMouseMove) {
  38199. element.removeEventListener("mousemove", this._onMouseMove);
  38200. }
  38201. if (this._onGestureStart) {
  38202. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38203. }
  38204. if (this._onGesture) {
  38205. element.removeEventListener("MSGestureChange", this._onGesture);
  38206. }
  38207. this._isPanClick = false;
  38208. this.pinchInwards = true;
  38209. this._onMouseMove = null;
  38210. this._onGestureStart = null;
  38211. this._onGesture = null;
  38212. this._MSGestureHandler = null;
  38213. this._onLostFocus = null;
  38214. this._onContextMenu = null;
  38215. }
  38216. };
  38217. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38218. return "ArcRotateCameraPointersInput";
  38219. };
  38220. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38221. return "pointers";
  38222. };
  38223. __decorate([
  38224. BABYLON.serialize()
  38225. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38226. __decorate([
  38227. BABYLON.serialize()
  38228. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38229. __decorate([
  38230. BABYLON.serialize()
  38231. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38232. __decorate([
  38233. BABYLON.serialize()
  38234. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38235. __decorate([
  38236. BABYLON.serialize()
  38237. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38238. __decorate([
  38239. BABYLON.serialize()
  38240. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38241. __decorate([
  38242. BABYLON.serialize()
  38243. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38244. __decorate([
  38245. BABYLON.serialize()
  38246. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38247. return ArcRotateCameraPointersInput;
  38248. }());
  38249. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38250. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38251. })(BABYLON || (BABYLON = {}));
  38252. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38253. var BABYLON;
  38254. (function (BABYLON) {
  38255. var ArcRotateCamera = /** @class */ (function (_super) {
  38256. __extends(ArcRotateCamera, _super);
  38257. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38258. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38259. _this.inertialAlphaOffset = 0;
  38260. _this.inertialBetaOffset = 0;
  38261. _this.inertialRadiusOffset = 0;
  38262. _this.lowerAlphaLimit = null;
  38263. _this.upperAlphaLimit = null;
  38264. _this.lowerBetaLimit = 0.01;
  38265. _this.upperBetaLimit = Math.PI;
  38266. _this.lowerRadiusLimit = null;
  38267. _this.upperRadiusLimit = null;
  38268. _this.inertialPanningX = 0;
  38269. _this.inertialPanningY = 0;
  38270. _this.pinchToPanMaxDistance = 20;
  38271. _this.panningDistanceLimit = null;
  38272. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38273. _this.panningInertia = 0.9;
  38274. //-- end properties for backward compatibility for inputs
  38275. _this.zoomOnFactor = 1;
  38276. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38277. _this.allowUpsideDown = true;
  38278. _this._viewMatrix = new BABYLON.Matrix();
  38279. // Panning
  38280. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38281. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38282. _this.checkCollisions = false;
  38283. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38284. _this._previousPosition = BABYLON.Vector3.Zero();
  38285. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38286. _this._newPosition = BABYLON.Vector3.Zero();
  38287. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38288. if (collidedMesh === void 0) { collidedMesh = null; }
  38289. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38290. newPosition.multiplyInPlace(_this._collider.radius);
  38291. }
  38292. if (!collidedMesh) {
  38293. _this._previousPosition.copyFrom(_this.position);
  38294. }
  38295. else {
  38296. _this.setPosition(newPosition);
  38297. if (_this.onCollide) {
  38298. _this.onCollide(collidedMesh);
  38299. }
  38300. }
  38301. // Recompute because of constraints
  38302. var cosa = Math.cos(_this.alpha);
  38303. var sina = Math.sin(_this.alpha);
  38304. var cosb = Math.cos(_this.beta);
  38305. var sinb = Math.sin(_this.beta);
  38306. if (sinb === 0) {
  38307. sinb = 0.0001;
  38308. }
  38309. var target = _this._getTargetPosition();
  38310. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38311. _this.position.copyFrom(_this._newPosition);
  38312. var up = _this.upVector;
  38313. if (_this.allowUpsideDown && _this.beta < 0) {
  38314. up = up.clone();
  38315. up = up.negate();
  38316. }
  38317. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38318. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38319. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38320. _this._collisionTriggered = false;
  38321. };
  38322. _this._target = BABYLON.Vector3.Zero();
  38323. if (target) {
  38324. _this.setTarget(target);
  38325. }
  38326. _this.alpha = alpha;
  38327. _this.beta = beta;
  38328. _this.radius = radius;
  38329. _this.getViewMatrix();
  38330. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  38331. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  38332. return _this;
  38333. }
  38334. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  38335. get: function () {
  38336. return this._target;
  38337. },
  38338. set: function (value) {
  38339. this.setTarget(value);
  38340. },
  38341. enumerable: true,
  38342. configurable: true
  38343. });
  38344. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  38345. //-- begin properties for backward compatibility for inputs
  38346. get: function () {
  38347. var pointers = this.inputs.attached["pointers"];
  38348. if (pointers)
  38349. return pointers.angularSensibilityX;
  38350. return 0;
  38351. },
  38352. set: function (value) {
  38353. var pointers = this.inputs.attached["pointers"];
  38354. if (pointers) {
  38355. pointers.angularSensibilityX = value;
  38356. }
  38357. },
  38358. enumerable: true,
  38359. configurable: true
  38360. });
  38361. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  38362. get: function () {
  38363. var pointers = this.inputs.attached["pointers"];
  38364. if (pointers)
  38365. return pointers.angularSensibilityY;
  38366. return 0;
  38367. },
  38368. set: function (value) {
  38369. var pointers = this.inputs.attached["pointers"];
  38370. if (pointers) {
  38371. pointers.angularSensibilityY = value;
  38372. }
  38373. },
  38374. enumerable: true,
  38375. configurable: true
  38376. });
  38377. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  38378. get: function () {
  38379. var pointers = this.inputs.attached["pointers"];
  38380. if (pointers)
  38381. return pointers.pinchPrecision;
  38382. return 0;
  38383. },
  38384. set: function (value) {
  38385. var pointers = this.inputs.attached["pointers"];
  38386. if (pointers) {
  38387. pointers.pinchPrecision = value;
  38388. }
  38389. },
  38390. enumerable: true,
  38391. configurable: true
  38392. });
  38393. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  38394. get: function () {
  38395. var pointers = this.inputs.attached["pointers"];
  38396. if (pointers)
  38397. return pointers.pinchDeltaPercentage;
  38398. return 0;
  38399. },
  38400. set: function (value) {
  38401. var pointers = this.inputs.attached["pointers"];
  38402. if (pointers) {
  38403. pointers.pinchDeltaPercentage = value;
  38404. }
  38405. },
  38406. enumerable: true,
  38407. configurable: true
  38408. });
  38409. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  38410. get: function () {
  38411. var pointers = this.inputs.attached["pointers"];
  38412. if (pointers)
  38413. return pointers.panningSensibility;
  38414. return 0;
  38415. },
  38416. set: function (value) {
  38417. var pointers = this.inputs.attached["pointers"];
  38418. if (pointers) {
  38419. pointers.panningSensibility = value;
  38420. }
  38421. },
  38422. enumerable: true,
  38423. configurable: true
  38424. });
  38425. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  38426. get: function () {
  38427. var keyboard = this.inputs.attached["keyboard"];
  38428. if (keyboard)
  38429. return keyboard.keysUp;
  38430. return [];
  38431. },
  38432. set: function (value) {
  38433. var keyboard = this.inputs.attached["keyboard"];
  38434. if (keyboard)
  38435. keyboard.keysUp = value;
  38436. },
  38437. enumerable: true,
  38438. configurable: true
  38439. });
  38440. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  38441. get: function () {
  38442. var keyboard = this.inputs.attached["keyboard"];
  38443. if (keyboard)
  38444. return keyboard.keysDown;
  38445. return [];
  38446. },
  38447. set: function (value) {
  38448. var keyboard = this.inputs.attached["keyboard"];
  38449. if (keyboard)
  38450. keyboard.keysDown = value;
  38451. },
  38452. enumerable: true,
  38453. configurable: true
  38454. });
  38455. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  38456. get: function () {
  38457. var keyboard = this.inputs.attached["keyboard"];
  38458. if (keyboard)
  38459. return keyboard.keysLeft;
  38460. return [];
  38461. },
  38462. set: function (value) {
  38463. var keyboard = this.inputs.attached["keyboard"];
  38464. if (keyboard)
  38465. keyboard.keysLeft = value;
  38466. },
  38467. enumerable: true,
  38468. configurable: true
  38469. });
  38470. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  38471. get: function () {
  38472. var keyboard = this.inputs.attached["keyboard"];
  38473. if (keyboard)
  38474. return keyboard.keysRight;
  38475. return [];
  38476. },
  38477. set: function (value) {
  38478. var keyboard = this.inputs.attached["keyboard"];
  38479. if (keyboard)
  38480. keyboard.keysRight = value;
  38481. },
  38482. enumerable: true,
  38483. configurable: true
  38484. });
  38485. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  38486. get: function () {
  38487. var mousewheel = this.inputs.attached["mousewheel"];
  38488. if (mousewheel)
  38489. return mousewheel.wheelPrecision;
  38490. return 0;
  38491. },
  38492. set: function (value) {
  38493. var mousewheel = this.inputs.attached["mousewheel"];
  38494. if (mousewheel)
  38495. mousewheel.wheelPrecision = value;
  38496. },
  38497. enumerable: true,
  38498. configurable: true
  38499. });
  38500. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  38501. get: function () {
  38502. var mousewheel = this.inputs.attached["mousewheel"];
  38503. if (mousewheel)
  38504. return mousewheel.wheelDeltaPercentage;
  38505. return 0;
  38506. },
  38507. set: function (value) {
  38508. var mousewheel = this.inputs.attached["mousewheel"];
  38509. if (mousewheel)
  38510. mousewheel.wheelDeltaPercentage = value;
  38511. },
  38512. enumerable: true,
  38513. configurable: true
  38514. });
  38515. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  38516. get: function () {
  38517. return this._bouncingBehavior;
  38518. },
  38519. enumerable: true,
  38520. configurable: true
  38521. });
  38522. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  38523. get: function () {
  38524. return this._bouncingBehavior != null;
  38525. },
  38526. set: function (value) {
  38527. if (value === this.useBouncingBehavior) {
  38528. return;
  38529. }
  38530. if (value) {
  38531. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  38532. this.addBehavior(this._bouncingBehavior);
  38533. }
  38534. else if (this._bouncingBehavior) {
  38535. this.removeBehavior(this._bouncingBehavior);
  38536. this._bouncingBehavior = null;
  38537. }
  38538. },
  38539. enumerable: true,
  38540. configurable: true
  38541. });
  38542. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  38543. get: function () {
  38544. return this._framingBehavior;
  38545. },
  38546. enumerable: true,
  38547. configurable: true
  38548. });
  38549. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  38550. get: function () {
  38551. return this._framingBehavior != null;
  38552. },
  38553. set: function (value) {
  38554. if (value === this.useFramingBehavior) {
  38555. return;
  38556. }
  38557. if (value) {
  38558. this._framingBehavior = new BABYLON.FramingBehavior();
  38559. this.addBehavior(this._framingBehavior);
  38560. }
  38561. else if (this._framingBehavior) {
  38562. this.removeBehavior(this._framingBehavior);
  38563. this._framingBehavior = null;
  38564. }
  38565. },
  38566. enumerable: true,
  38567. configurable: true
  38568. });
  38569. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38570. get: function () {
  38571. return this._autoRotationBehavior;
  38572. },
  38573. enumerable: true,
  38574. configurable: true
  38575. });
  38576. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38577. get: function () {
  38578. return this._autoRotationBehavior != null;
  38579. },
  38580. set: function (value) {
  38581. if (value === this.useAutoRotationBehavior) {
  38582. return;
  38583. }
  38584. if (value) {
  38585. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38586. this.addBehavior(this._autoRotationBehavior);
  38587. }
  38588. else if (this._autoRotationBehavior) {
  38589. this.removeBehavior(this._autoRotationBehavior);
  38590. this._autoRotationBehavior = null;
  38591. }
  38592. },
  38593. enumerable: true,
  38594. configurable: true
  38595. });
  38596. // Cache
  38597. ArcRotateCamera.prototype._initCache = function () {
  38598. _super.prototype._initCache.call(this);
  38599. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38600. this._cache.alpha = undefined;
  38601. this._cache.beta = undefined;
  38602. this._cache.radius = undefined;
  38603. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38604. };
  38605. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38606. if (!ignoreParentClass) {
  38607. _super.prototype._updateCache.call(this);
  38608. }
  38609. this._cache._target.copyFrom(this._getTargetPosition());
  38610. this._cache.alpha = this.alpha;
  38611. this._cache.beta = this.beta;
  38612. this._cache.radius = this.radius;
  38613. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38614. };
  38615. ArcRotateCamera.prototype._getTargetPosition = function () {
  38616. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38617. var pos = this._targetHost.getAbsolutePosition();
  38618. if (this._targetBoundingCenter) {
  38619. pos.addToRef(this._targetBoundingCenter, this._target);
  38620. }
  38621. else {
  38622. this._target.copyFrom(pos);
  38623. }
  38624. }
  38625. var lockedTargetPosition = this._getLockedTargetPosition();
  38626. if (lockedTargetPosition) {
  38627. return lockedTargetPosition;
  38628. }
  38629. return this._target;
  38630. };
  38631. ArcRotateCamera.prototype.storeState = function () {
  38632. this._storedAlpha = this.alpha;
  38633. this._storedBeta = this.beta;
  38634. this._storedRadius = this.radius;
  38635. this._storedTarget = this._getTargetPosition().clone();
  38636. return _super.prototype.storeState.call(this);
  38637. };
  38638. /**
  38639. * Restored camera state. You must call storeState() first
  38640. */
  38641. ArcRotateCamera.prototype._restoreStateValues = function () {
  38642. if (!_super.prototype._restoreStateValues.call(this)) {
  38643. return false;
  38644. }
  38645. this.alpha = this._storedAlpha;
  38646. this.beta = this._storedBeta;
  38647. this.radius = this._storedRadius;
  38648. this.setTarget(this._storedTarget.clone());
  38649. this.inertialAlphaOffset = 0;
  38650. this.inertialBetaOffset = 0;
  38651. this.inertialRadiusOffset = 0;
  38652. this.inertialPanningX = 0;
  38653. this.inertialPanningY = 0;
  38654. return true;
  38655. };
  38656. // Synchronized
  38657. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38658. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38659. return false;
  38660. return this._cache._target.equals(this._getTargetPosition())
  38661. && this._cache.alpha === this.alpha
  38662. && this._cache.beta === this.beta
  38663. && this._cache.radius === this.radius
  38664. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  38665. };
  38666. // Methods
  38667. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  38668. var _this = this;
  38669. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  38670. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  38671. this._useCtrlForPanning = useCtrlForPanning;
  38672. this._panningMouseButton = panningMouseButton;
  38673. this.inputs.attachElement(element, noPreventDefault);
  38674. this._reset = function () {
  38675. _this.inertialAlphaOffset = 0;
  38676. _this.inertialBetaOffset = 0;
  38677. _this.inertialRadiusOffset = 0;
  38678. _this.inertialPanningX = 0;
  38679. _this.inertialPanningY = 0;
  38680. };
  38681. };
  38682. ArcRotateCamera.prototype.detachControl = function (element) {
  38683. this.inputs.detachElement(element);
  38684. if (this._reset) {
  38685. this._reset();
  38686. }
  38687. };
  38688. ArcRotateCamera.prototype._checkInputs = function () {
  38689. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  38690. if (this._collisionTriggered) {
  38691. return;
  38692. }
  38693. this.inputs.checkInputs();
  38694. // Inertia
  38695. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  38696. if (this.getScene().useRightHandedSystem) {
  38697. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38698. }
  38699. else {
  38700. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38701. }
  38702. this.beta += this.inertialBetaOffset;
  38703. this.radius -= this.inertialRadiusOffset;
  38704. this.inertialAlphaOffset *= this.inertia;
  38705. this.inertialBetaOffset *= this.inertia;
  38706. this.inertialRadiusOffset *= this.inertia;
  38707. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  38708. this.inertialAlphaOffset = 0;
  38709. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  38710. this.inertialBetaOffset = 0;
  38711. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  38712. this.inertialRadiusOffset = 0;
  38713. }
  38714. // Panning inertia
  38715. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  38716. if (!this._localDirection) {
  38717. this._localDirection = BABYLON.Vector3.Zero();
  38718. this._transformedDirection = BABYLON.Vector3.Zero();
  38719. }
  38720. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  38721. this._localDirection.multiplyInPlace(this.panningAxis);
  38722. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  38723. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  38724. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  38725. if (!this.panningAxis.y) {
  38726. this._transformedDirection.y = 0;
  38727. }
  38728. if (!this._targetHost) {
  38729. if (this.panningDistanceLimit) {
  38730. this._transformedDirection.addInPlace(this._target);
  38731. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  38732. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  38733. this._target.copyFrom(this._transformedDirection);
  38734. }
  38735. }
  38736. else {
  38737. this._target.addInPlace(this._transformedDirection);
  38738. }
  38739. }
  38740. this.inertialPanningX *= this.panningInertia;
  38741. this.inertialPanningY *= this.panningInertia;
  38742. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  38743. this.inertialPanningX = 0;
  38744. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  38745. this.inertialPanningY = 0;
  38746. }
  38747. // Limits
  38748. this._checkLimits();
  38749. _super.prototype._checkInputs.call(this);
  38750. };
  38751. ArcRotateCamera.prototype._checkLimits = function () {
  38752. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  38753. if (this.allowUpsideDown && this.beta > Math.PI) {
  38754. this.beta = this.beta - (2 * Math.PI);
  38755. }
  38756. }
  38757. else {
  38758. if (this.beta < this.lowerBetaLimit) {
  38759. this.beta = this.lowerBetaLimit;
  38760. }
  38761. }
  38762. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  38763. if (this.allowUpsideDown && this.beta < -Math.PI) {
  38764. this.beta = this.beta + (2 * Math.PI);
  38765. }
  38766. }
  38767. else {
  38768. if (this.beta > this.upperBetaLimit) {
  38769. this.beta = this.upperBetaLimit;
  38770. }
  38771. }
  38772. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  38773. this.alpha = this.lowerAlphaLimit;
  38774. }
  38775. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  38776. this.alpha = this.upperAlphaLimit;
  38777. }
  38778. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  38779. this.radius = this.lowerRadiusLimit;
  38780. }
  38781. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  38782. this.radius = this.upperRadiusLimit;
  38783. }
  38784. };
  38785. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  38786. var radiusv3 = this.position.subtract(this._getTargetPosition());
  38787. this.radius = radiusv3.length();
  38788. if (this.radius === 0) {
  38789. this.radius = 0.0001; // Just to avoid division by zero
  38790. }
  38791. // Alpha
  38792. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  38793. if (radiusv3.z < 0) {
  38794. this.alpha = 2 * Math.PI - this.alpha;
  38795. }
  38796. // Beta
  38797. this.beta = Math.acos(radiusv3.y / this.radius);
  38798. this._checkLimits();
  38799. };
  38800. ArcRotateCamera.prototype.setPosition = function (position) {
  38801. if (this.position.equals(position)) {
  38802. return;
  38803. }
  38804. this.position.copyFrom(position);
  38805. this.rebuildAnglesAndRadius();
  38806. };
  38807. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  38808. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  38809. if (allowSamePosition === void 0) { allowSamePosition = false; }
  38810. if (target.getBoundingInfo) {
  38811. if (toBoundingCenter) {
  38812. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  38813. }
  38814. else {
  38815. this._targetBoundingCenter = null;
  38816. }
  38817. this._targetHost = target;
  38818. this._target = this._getTargetPosition();
  38819. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  38820. }
  38821. else {
  38822. var newTarget = target;
  38823. var currentTarget = this._getTargetPosition();
  38824. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  38825. return;
  38826. }
  38827. this._targetHost = null;
  38828. this._target = newTarget;
  38829. this._targetBoundingCenter = null;
  38830. this.onMeshTargetChangedObservable.notifyObservers(null);
  38831. }
  38832. this.rebuildAnglesAndRadius();
  38833. };
  38834. ArcRotateCamera.prototype._getViewMatrix = function () {
  38835. // Compute
  38836. var cosa = Math.cos(this.alpha);
  38837. var sina = Math.sin(this.alpha);
  38838. var cosb = Math.cos(this.beta);
  38839. var sinb = Math.sin(this.beta);
  38840. if (sinb === 0) {
  38841. sinb = 0.0001;
  38842. }
  38843. var target = this._getTargetPosition();
  38844. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  38845. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  38846. if (!this._collider) {
  38847. this._collider = new BABYLON.Collider();
  38848. }
  38849. this._collider.radius = this.collisionRadius;
  38850. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  38851. this._collisionTriggered = true;
  38852. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38853. }
  38854. else {
  38855. this.position.copyFrom(this._newPosition);
  38856. var up = this.upVector;
  38857. if (this.allowUpsideDown && sinb < 0) {
  38858. up = up.clone();
  38859. up = up.negate();
  38860. }
  38861. if (this.getScene().useRightHandedSystem) {
  38862. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  38863. }
  38864. else {
  38865. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  38866. }
  38867. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  38868. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  38869. }
  38870. this._currentTarget = target;
  38871. return this._viewMatrix;
  38872. };
  38873. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  38874. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  38875. meshes = meshes || this.getScene().meshes;
  38876. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  38877. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  38878. this.radius = distance * this.zoomOnFactor;
  38879. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  38880. };
  38881. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  38882. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  38883. var meshesOrMinMaxVector;
  38884. var distance;
  38885. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  38886. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  38887. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  38888. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  38889. }
  38890. else {
  38891. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  38892. meshesOrMinMaxVector = minMaxVectorAndDistance;
  38893. distance = minMaxVectorAndDistance.distance;
  38894. }
  38895. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  38896. if (!doNotUpdateMaxZ) {
  38897. this.maxZ = distance * 2;
  38898. }
  38899. };
  38900. /**
  38901. * @override
  38902. * Override Camera.createRigCamera
  38903. */
  38904. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38905. var alphaShift = 0;
  38906. switch (this.cameraRigMode) {
  38907. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38908. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38909. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38910. case BABYLON.Camera.RIG_MODE_VR:
  38911. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  38912. break;
  38913. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38914. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  38915. break;
  38916. }
  38917. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  38918. rigCam._cameraRigParams = {};
  38919. return rigCam;
  38920. };
  38921. /**
  38922. * @override
  38923. * Override Camera._updateRigCameras
  38924. */
  38925. ArcRotateCamera.prototype._updateRigCameras = function () {
  38926. var camLeft = this._rigCameras[0];
  38927. var camRight = this._rigCameras[1];
  38928. camLeft.beta = camRight.beta = this.beta;
  38929. camLeft.radius = camRight.radius = this.radius;
  38930. switch (this.cameraRigMode) {
  38931. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38932. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38933. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38934. case BABYLON.Camera.RIG_MODE_VR:
  38935. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  38936. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  38937. break;
  38938. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38939. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  38940. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  38941. break;
  38942. }
  38943. _super.prototype._updateRigCameras.call(this);
  38944. };
  38945. ArcRotateCamera.prototype.dispose = function () {
  38946. this.inputs.clear();
  38947. _super.prototype.dispose.call(this);
  38948. };
  38949. ArcRotateCamera.prototype.getClassName = function () {
  38950. return "ArcRotateCamera";
  38951. };
  38952. __decorate([
  38953. BABYLON.serialize()
  38954. ], ArcRotateCamera.prototype, "alpha", void 0);
  38955. __decorate([
  38956. BABYLON.serialize()
  38957. ], ArcRotateCamera.prototype, "beta", void 0);
  38958. __decorate([
  38959. BABYLON.serialize()
  38960. ], ArcRotateCamera.prototype, "radius", void 0);
  38961. __decorate([
  38962. BABYLON.serializeAsVector3("target")
  38963. ], ArcRotateCamera.prototype, "_target", void 0);
  38964. __decorate([
  38965. BABYLON.serialize()
  38966. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  38967. __decorate([
  38968. BABYLON.serialize()
  38969. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  38970. __decorate([
  38971. BABYLON.serialize()
  38972. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  38973. __decorate([
  38974. BABYLON.serialize()
  38975. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  38976. __decorate([
  38977. BABYLON.serialize()
  38978. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  38979. __decorate([
  38980. BABYLON.serialize()
  38981. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  38982. __decorate([
  38983. BABYLON.serialize()
  38984. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  38985. __decorate([
  38986. BABYLON.serialize()
  38987. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  38988. __decorate([
  38989. BABYLON.serialize()
  38990. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  38991. __decorate([
  38992. BABYLON.serialize()
  38993. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  38994. __decorate([
  38995. BABYLON.serialize()
  38996. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  38997. __decorate([
  38998. BABYLON.serialize()
  38999. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39000. __decorate([
  39001. BABYLON.serialize()
  39002. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39003. __decorate([
  39004. BABYLON.serializeAsVector3()
  39005. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39006. __decorate([
  39007. BABYLON.serialize()
  39008. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39009. __decorate([
  39010. BABYLON.serialize()
  39011. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39012. __decorate([
  39013. BABYLON.serialize()
  39014. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39015. return ArcRotateCamera;
  39016. }(BABYLON.TargetCamera));
  39017. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39018. })(BABYLON || (BABYLON = {}));
  39019. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39020. var BABYLON;
  39021. (function (BABYLON) {
  39022. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39023. __extends(ArcRotateCameraInputsManager, _super);
  39024. function ArcRotateCameraInputsManager(camera) {
  39025. return _super.call(this, camera) || this;
  39026. }
  39027. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39028. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39029. return this;
  39030. };
  39031. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39032. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39033. return this;
  39034. };
  39035. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39036. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39037. return this;
  39038. };
  39039. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39040. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39041. return this;
  39042. };
  39043. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39044. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39045. return this;
  39046. };
  39047. return ArcRotateCameraInputsManager;
  39048. }(BABYLON.CameraInputsManager));
  39049. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39050. })(BABYLON || (BABYLON = {}));
  39051. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39052. var BABYLON;
  39053. (function (BABYLON) {
  39054. var HemisphericLight = /** @class */ (function (_super) {
  39055. __extends(HemisphericLight, _super);
  39056. /**
  39057. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39058. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39059. * The HemisphericLight can't cast shadows.
  39060. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39061. */
  39062. function HemisphericLight(name, direction, scene) {
  39063. var _this = _super.call(this, name, scene) || this;
  39064. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39065. _this.direction = direction || BABYLON.Vector3.Up();
  39066. return _this;
  39067. }
  39068. HemisphericLight.prototype._buildUniformLayout = function () {
  39069. this._uniformBuffer.addUniform("vLightData", 4);
  39070. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39071. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39072. this._uniformBuffer.addUniform("vLightGround", 3);
  39073. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39074. this._uniformBuffer.addUniform("depthValues", 2);
  39075. this._uniformBuffer.create();
  39076. };
  39077. /**
  39078. * Returns the string "HemisphericLight".
  39079. */
  39080. HemisphericLight.prototype.getClassName = function () {
  39081. return "HemisphericLight";
  39082. };
  39083. /**
  39084. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39085. * Returns the updated direction.
  39086. */
  39087. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39088. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39089. return this.direction;
  39090. };
  39091. HemisphericLight.prototype.getShadowGenerator = function () {
  39092. return null;
  39093. };
  39094. /**
  39095. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39096. * Returns the HemisphericLight.
  39097. */
  39098. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39099. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39100. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39101. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39102. return this;
  39103. };
  39104. HemisphericLight.prototype._getWorldMatrix = function () {
  39105. if (!this._worldMatrix) {
  39106. this._worldMatrix = BABYLON.Matrix.Identity();
  39107. }
  39108. return this._worldMatrix;
  39109. };
  39110. /**
  39111. * Returns the integer 3.
  39112. */
  39113. HemisphericLight.prototype.getTypeID = function () {
  39114. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39115. };
  39116. __decorate([
  39117. BABYLON.serializeAsColor3()
  39118. ], HemisphericLight.prototype, "groundColor", void 0);
  39119. __decorate([
  39120. BABYLON.serializeAsVector3()
  39121. ], HemisphericLight.prototype, "direction", void 0);
  39122. return HemisphericLight;
  39123. }(BABYLON.Light));
  39124. BABYLON.HemisphericLight = HemisphericLight;
  39125. })(BABYLON || (BABYLON = {}));
  39126. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39127. var BABYLON;
  39128. (function (BABYLON) {
  39129. var ShadowLight = /** @class */ (function (_super) {
  39130. __extends(ShadowLight, _super);
  39131. function ShadowLight() {
  39132. var _this = _super !== null && _super.apply(this, arguments) || this;
  39133. _this._needProjectionMatrixCompute = true;
  39134. return _this;
  39135. }
  39136. Object.defineProperty(ShadowLight.prototype, "direction", {
  39137. get: function () {
  39138. return this._direction;
  39139. },
  39140. set: function (value) {
  39141. this._direction = value;
  39142. },
  39143. enumerable: true,
  39144. configurable: true
  39145. });
  39146. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39147. get: function () {
  39148. return this._shadowMinZ;
  39149. },
  39150. set: function (value) {
  39151. this._shadowMinZ = value;
  39152. this.forceProjectionMatrixCompute();
  39153. },
  39154. enumerable: true,
  39155. configurable: true
  39156. });
  39157. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39158. get: function () {
  39159. return this._shadowMaxZ;
  39160. },
  39161. set: function (value) {
  39162. this._shadowMaxZ = value;
  39163. this.forceProjectionMatrixCompute();
  39164. },
  39165. enumerable: true,
  39166. configurable: true
  39167. });
  39168. /**
  39169. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39170. */
  39171. ShadowLight.prototype.computeTransformedInformation = function () {
  39172. if (this.parent && this.parent.getWorldMatrix) {
  39173. if (!this.transformedPosition) {
  39174. this.transformedPosition = BABYLON.Vector3.Zero();
  39175. }
  39176. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39177. // In case the direction is present.
  39178. if (this.direction) {
  39179. if (!this.transformedDirection) {
  39180. this.transformedDirection = BABYLON.Vector3.Zero();
  39181. }
  39182. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39183. }
  39184. return true;
  39185. }
  39186. return false;
  39187. };
  39188. /**
  39189. * Return the depth scale used for the shadow map.
  39190. */
  39191. ShadowLight.prototype.getDepthScale = function () {
  39192. return 50.0;
  39193. };
  39194. /**
  39195. * Returns the light direction (Vector3) for any passed face index.
  39196. */
  39197. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39198. return this.transformedDirection ? this.transformedDirection : this.direction;
  39199. };
  39200. /**
  39201. * Returns the DirectionalLight absolute position in the World.
  39202. */
  39203. ShadowLight.prototype.getAbsolutePosition = function () {
  39204. return this.transformedPosition ? this.transformedPosition : this.position;
  39205. };
  39206. /**
  39207. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39208. * Returns the updated DirectionalLight direction (Vector3).
  39209. */
  39210. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39211. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39212. return this.direction;
  39213. };
  39214. /**
  39215. * Returns the light rotation (Vector3).
  39216. */
  39217. ShadowLight.prototype.getRotation = function () {
  39218. this.direction.normalize();
  39219. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39220. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39221. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39222. };
  39223. /**
  39224. * Boolean : false by default.
  39225. */
  39226. ShadowLight.prototype.needCube = function () {
  39227. return false;
  39228. };
  39229. /**
  39230. * Specifies wether or not the projection matrix should be recomputed this frame.
  39231. */
  39232. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39233. return this._needProjectionMatrixCompute;
  39234. };
  39235. /**
  39236. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39237. */
  39238. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39239. this._needProjectionMatrixCompute = true;
  39240. };
  39241. /**
  39242. * Get the world matrix of the sahdow lights.
  39243. */
  39244. ShadowLight.prototype._getWorldMatrix = function () {
  39245. if (!this._worldMatrix) {
  39246. this._worldMatrix = BABYLON.Matrix.Identity();
  39247. }
  39248. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39249. return this._worldMatrix;
  39250. };
  39251. /**
  39252. * Gets the minZ used for shadow according to both the scene and the light.
  39253. * @param activeCamera
  39254. */
  39255. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39256. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39257. };
  39258. /**
  39259. * Gets the maxZ used for shadow according to both the scene and the light.
  39260. * @param activeCamera
  39261. */
  39262. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39263. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39264. };
  39265. /**
  39266. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39267. * Returns the light.
  39268. */
  39269. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39270. if (this.customProjectionMatrixBuilder) {
  39271. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39272. }
  39273. else {
  39274. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39275. }
  39276. return this;
  39277. };
  39278. __decorate([
  39279. BABYLON.serializeAsVector3()
  39280. ], ShadowLight.prototype, "position", void 0);
  39281. __decorate([
  39282. BABYLON.serializeAsVector3()
  39283. ], ShadowLight.prototype, "direction", null);
  39284. __decorate([
  39285. BABYLON.serialize()
  39286. ], ShadowLight.prototype, "shadowMinZ", null);
  39287. __decorate([
  39288. BABYLON.serialize()
  39289. ], ShadowLight.prototype, "shadowMaxZ", null);
  39290. return ShadowLight;
  39291. }(BABYLON.Light));
  39292. BABYLON.ShadowLight = ShadowLight;
  39293. })(BABYLON || (BABYLON = {}));
  39294. //# sourceMappingURL=babylon.shadowLight.js.map
  39295. var BABYLON;
  39296. (function (BABYLON) {
  39297. var PointLight = /** @class */ (function (_super) {
  39298. __extends(PointLight, _super);
  39299. /**
  39300. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39301. * A PointLight emits the light in every direction.
  39302. * It can cast shadows.
  39303. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39304. * ```javascript
  39305. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39306. * ```
  39307. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39308. */
  39309. function PointLight(name, position, scene) {
  39310. var _this = _super.call(this, name, scene) || this;
  39311. _this._shadowAngle = Math.PI / 2;
  39312. _this.position = position;
  39313. return _this;
  39314. }
  39315. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39316. /**
  39317. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39318. * This specifies what angle the shadow will use to be created.
  39319. *
  39320. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39321. */
  39322. get: function () {
  39323. return this._shadowAngle;
  39324. },
  39325. /**
  39326. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39327. * This specifies what angle the shadow will use to be created.
  39328. *
  39329. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39330. */
  39331. set: function (value) {
  39332. this._shadowAngle = value;
  39333. this.forceProjectionMatrixCompute();
  39334. },
  39335. enumerable: true,
  39336. configurable: true
  39337. });
  39338. Object.defineProperty(PointLight.prototype, "direction", {
  39339. get: function () {
  39340. return this._direction;
  39341. },
  39342. /**
  39343. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39344. */
  39345. set: function (value) {
  39346. var previousNeedCube = this.needCube();
  39347. this._direction = value;
  39348. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  39349. this._shadowGenerator.recreateShadowMap();
  39350. }
  39351. },
  39352. enumerable: true,
  39353. configurable: true
  39354. });
  39355. /**
  39356. * Returns the string "PointLight"
  39357. */
  39358. PointLight.prototype.getClassName = function () {
  39359. return "PointLight";
  39360. };
  39361. /**
  39362. * Returns the integer 0.
  39363. */
  39364. PointLight.prototype.getTypeID = function () {
  39365. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  39366. };
  39367. /**
  39368. * Specifies wether or not the shadowmap should be a cube texture.
  39369. */
  39370. PointLight.prototype.needCube = function () {
  39371. return !this.direction;
  39372. };
  39373. /**
  39374. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  39375. */
  39376. PointLight.prototype.getShadowDirection = function (faceIndex) {
  39377. if (this.direction) {
  39378. return _super.prototype.getShadowDirection.call(this, faceIndex);
  39379. }
  39380. else {
  39381. switch (faceIndex) {
  39382. case 0:
  39383. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  39384. case 1:
  39385. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  39386. case 2:
  39387. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  39388. case 3:
  39389. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  39390. case 4:
  39391. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  39392. case 5:
  39393. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  39394. }
  39395. }
  39396. return BABYLON.Vector3.Zero();
  39397. };
  39398. /**
  39399. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  39400. * - fov = PI / 2
  39401. * - aspect ratio : 1.0
  39402. * - z-near and far equal to the active camera minZ and maxZ.
  39403. * Returns the PointLight.
  39404. */
  39405. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39406. var activeCamera = this.getScene().activeCamera;
  39407. if (!activeCamera) {
  39408. return;
  39409. }
  39410. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39411. };
  39412. PointLight.prototype._buildUniformLayout = function () {
  39413. this._uniformBuffer.addUniform("vLightData", 4);
  39414. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39415. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39416. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39417. this._uniformBuffer.addUniform("depthValues", 2);
  39418. this._uniformBuffer.create();
  39419. };
  39420. /**
  39421. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  39422. * Returns the PointLight.
  39423. */
  39424. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  39425. if (this.computeTransformedInformation()) {
  39426. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  39427. return this;
  39428. }
  39429. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  39430. return this;
  39431. };
  39432. __decorate([
  39433. BABYLON.serialize()
  39434. ], PointLight.prototype, "shadowAngle", null);
  39435. return PointLight;
  39436. }(BABYLON.ShadowLight));
  39437. BABYLON.PointLight = PointLight;
  39438. })(BABYLON || (BABYLON = {}));
  39439. //# sourceMappingURL=babylon.pointLight.js.map
  39440. var BABYLON;
  39441. (function (BABYLON) {
  39442. var DirectionalLight = /** @class */ (function (_super) {
  39443. __extends(DirectionalLight, _super);
  39444. /**
  39445. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  39446. * The directional light is emitted from everywhere in the given direction.
  39447. * It can cast shawdows.
  39448. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39449. */
  39450. function DirectionalLight(name, direction, scene) {
  39451. var _this = _super.call(this, name, scene) || this;
  39452. _this._shadowFrustumSize = 0;
  39453. _this._shadowOrthoScale = 0.5;
  39454. _this.autoUpdateExtends = true;
  39455. // Cache
  39456. _this._orthoLeft = Number.MAX_VALUE;
  39457. _this._orthoRight = Number.MIN_VALUE;
  39458. _this._orthoTop = Number.MIN_VALUE;
  39459. _this._orthoBottom = Number.MAX_VALUE;
  39460. _this.position = direction.scale(-1.0);
  39461. _this.direction = direction;
  39462. return _this;
  39463. }
  39464. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  39465. /**
  39466. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  39467. */
  39468. get: function () {
  39469. return this._shadowFrustumSize;
  39470. },
  39471. /**
  39472. * Specifies a fix frustum size for the shadow generation.
  39473. */
  39474. set: function (value) {
  39475. this._shadowFrustumSize = value;
  39476. this.forceProjectionMatrixCompute();
  39477. },
  39478. enumerable: true,
  39479. configurable: true
  39480. });
  39481. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  39482. get: function () {
  39483. return this._shadowOrthoScale;
  39484. },
  39485. set: function (value) {
  39486. this._shadowOrthoScale = value;
  39487. this.forceProjectionMatrixCompute();
  39488. },
  39489. enumerable: true,
  39490. configurable: true
  39491. });
  39492. /**
  39493. * Returns the string "DirectionalLight".
  39494. */
  39495. DirectionalLight.prototype.getClassName = function () {
  39496. return "DirectionalLight";
  39497. };
  39498. /**
  39499. * Returns the integer 1.
  39500. */
  39501. DirectionalLight.prototype.getTypeID = function () {
  39502. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  39503. };
  39504. /**
  39505. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  39506. * Returns the DirectionalLight Shadow projection matrix.
  39507. */
  39508. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39509. if (this.shadowFrustumSize > 0) {
  39510. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  39511. }
  39512. else {
  39513. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39514. }
  39515. };
  39516. /**
  39517. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  39518. * Returns the DirectionalLight Shadow projection matrix.
  39519. */
  39520. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  39521. var activeCamera = this.getScene().activeCamera;
  39522. if (!activeCamera) {
  39523. return;
  39524. }
  39525. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39526. };
  39527. /**
  39528. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  39529. * Returns the DirectionalLight Shadow projection matrix.
  39530. */
  39531. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39532. var activeCamera = this.getScene().activeCamera;
  39533. if (!activeCamera) {
  39534. return;
  39535. }
  39536. // Check extends
  39537. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  39538. var tempVector3 = BABYLON.Vector3.Zero();
  39539. this._orthoLeft = Number.MAX_VALUE;
  39540. this._orthoRight = Number.MIN_VALUE;
  39541. this._orthoTop = Number.MIN_VALUE;
  39542. this._orthoBottom = Number.MAX_VALUE;
  39543. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  39544. var mesh = renderList[meshIndex];
  39545. if (!mesh) {
  39546. continue;
  39547. }
  39548. var boundingInfo = mesh.getBoundingInfo();
  39549. if (!boundingInfo) {
  39550. continue;
  39551. }
  39552. var boundingBox = boundingInfo.boundingBox;
  39553. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  39554. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  39555. if (tempVector3.x < this._orthoLeft)
  39556. this._orthoLeft = tempVector3.x;
  39557. if (tempVector3.y < this._orthoBottom)
  39558. this._orthoBottom = tempVector3.y;
  39559. if (tempVector3.x > this._orthoRight)
  39560. this._orthoRight = tempVector3.x;
  39561. if (tempVector3.y > this._orthoTop)
  39562. this._orthoTop = tempVector3.y;
  39563. }
  39564. }
  39565. }
  39566. var xOffset = this._orthoRight - this._orthoLeft;
  39567. var yOffset = this._orthoTop - this._orthoBottom;
  39568. 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);
  39569. };
  39570. DirectionalLight.prototype._buildUniformLayout = function () {
  39571. this._uniformBuffer.addUniform("vLightData", 4);
  39572. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39573. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39574. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39575. this._uniformBuffer.addUniform("depthValues", 2);
  39576. this._uniformBuffer.create();
  39577. };
  39578. /**
  39579. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39580. * Returns the DirectionalLight.
  39581. */
  39582. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39583. if (this.computeTransformedInformation()) {
  39584. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39585. return this;
  39586. }
  39587. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39588. return this;
  39589. };
  39590. /**
  39591. * Gets the minZ used for shadow according to both the scene and the light.
  39592. *
  39593. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39594. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39595. * @param activeCamera
  39596. */
  39597. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39598. return 1;
  39599. };
  39600. /**
  39601. * Gets the maxZ used for shadow according to both the scene and the light.
  39602. *
  39603. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39604. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39605. * @param activeCamera
  39606. */
  39607. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39608. return 1;
  39609. };
  39610. __decorate([
  39611. BABYLON.serialize()
  39612. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39613. __decorate([
  39614. BABYLON.serialize()
  39615. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39616. __decorate([
  39617. BABYLON.serialize()
  39618. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39619. return DirectionalLight;
  39620. }(BABYLON.ShadowLight));
  39621. BABYLON.DirectionalLight = DirectionalLight;
  39622. })(BABYLON || (BABYLON = {}));
  39623. //# sourceMappingURL=babylon.directionalLight.js.map
  39624. var BABYLON;
  39625. (function (BABYLON) {
  39626. var SpotLight = /** @class */ (function (_super) {
  39627. __extends(SpotLight, _super);
  39628. /**
  39629. * Creates a SpotLight object in the scene with the passed parameters :
  39630. * - `position` (Vector3) is the initial SpotLight position,
  39631. * - `direction` (Vector3) is the initial SpotLight direction,
  39632. * - `angle` (float, in radians) is the spot light cone angle,
  39633. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39634. * A spot light is a simply light oriented cone.
  39635. * It can cast shadows.
  39636. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39637. */
  39638. function SpotLight(name, position, direction, angle, exponent, scene) {
  39639. var _this = _super.call(this, name, scene) || this;
  39640. _this.position = position;
  39641. _this.direction = direction;
  39642. _this.angle = angle;
  39643. _this.exponent = exponent;
  39644. return _this;
  39645. }
  39646. Object.defineProperty(SpotLight.prototype, "angle", {
  39647. get: function () {
  39648. return this._angle;
  39649. },
  39650. set: function (value) {
  39651. this._angle = value;
  39652. this.forceProjectionMatrixCompute();
  39653. },
  39654. enumerable: true,
  39655. configurable: true
  39656. });
  39657. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39658. get: function () {
  39659. return this._shadowAngleScale;
  39660. },
  39661. /**
  39662. * Allows scaling the angle of the light for shadow generation only.
  39663. */
  39664. set: function (value) {
  39665. this._shadowAngleScale = value;
  39666. this.forceProjectionMatrixCompute();
  39667. },
  39668. enumerable: true,
  39669. configurable: true
  39670. });
  39671. /**
  39672. * Returns the string "SpotLight".
  39673. */
  39674. SpotLight.prototype.getClassName = function () {
  39675. return "SpotLight";
  39676. };
  39677. /**
  39678. * Returns the integer 2.
  39679. */
  39680. SpotLight.prototype.getTypeID = function () {
  39681. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  39682. };
  39683. /**
  39684. * 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.
  39685. * Returns the SpotLight.
  39686. */
  39687. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39688. var activeCamera = this.getScene().activeCamera;
  39689. if (!activeCamera) {
  39690. return;
  39691. }
  39692. this._shadowAngleScale = this._shadowAngleScale || 1;
  39693. var angle = this._shadowAngleScale * this._angle;
  39694. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39695. };
  39696. SpotLight.prototype._buildUniformLayout = function () {
  39697. this._uniformBuffer.addUniform("vLightData", 4);
  39698. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39699. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39700. this._uniformBuffer.addUniform("vLightDirection", 3);
  39701. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39702. this._uniformBuffer.addUniform("depthValues", 2);
  39703. this._uniformBuffer.create();
  39704. };
  39705. /**
  39706. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  39707. * Return the SpotLight.
  39708. */
  39709. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  39710. var normalizeDirection;
  39711. if (this.computeTransformedInformation()) {
  39712. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  39713. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  39714. }
  39715. else {
  39716. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  39717. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39718. }
  39719. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  39720. return this;
  39721. };
  39722. __decorate([
  39723. BABYLON.serialize()
  39724. ], SpotLight.prototype, "angle", null);
  39725. __decorate([
  39726. BABYLON.serialize()
  39727. /**
  39728. * Allows scaling the angle of the light for shadow generation only.
  39729. */
  39730. ], SpotLight.prototype, "shadowAngleScale", null);
  39731. __decorate([
  39732. BABYLON.serialize()
  39733. ], SpotLight.prototype, "exponent", void 0);
  39734. return SpotLight;
  39735. }(BABYLON.ShadowLight));
  39736. BABYLON.SpotLight = SpotLight;
  39737. })(BABYLON || (BABYLON = {}));
  39738. //# sourceMappingURL=babylon.spotLight.js.map
  39739. var BABYLON;
  39740. (function (BABYLON) {
  39741. var AnimationRange = /** @class */ (function () {
  39742. function AnimationRange(name, from, to) {
  39743. this.name = name;
  39744. this.from = from;
  39745. this.to = to;
  39746. }
  39747. AnimationRange.prototype.clone = function () {
  39748. return new AnimationRange(this.name, this.from, this.to);
  39749. };
  39750. return AnimationRange;
  39751. }());
  39752. BABYLON.AnimationRange = AnimationRange;
  39753. /**
  39754. * Composed of a frame, and an action function
  39755. */
  39756. var AnimationEvent = /** @class */ (function () {
  39757. function AnimationEvent(frame, action, onlyOnce) {
  39758. this.frame = frame;
  39759. this.action = action;
  39760. this.onlyOnce = onlyOnce;
  39761. this.isDone = false;
  39762. }
  39763. return AnimationEvent;
  39764. }());
  39765. BABYLON.AnimationEvent = AnimationEvent;
  39766. var PathCursor = /** @class */ (function () {
  39767. function PathCursor(path) {
  39768. this.path = path;
  39769. this._onchange = new Array();
  39770. this.value = 0;
  39771. this.animations = new Array();
  39772. }
  39773. PathCursor.prototype.getPoint = function () {
  39774. var point = this.path.getPointAtLengthPosition(this.value);
  39775. return new BABYLON.Vector3(point.x, 0, point.y);
  39776. };
  39777. PathCursor.prototype.moveAhead = function (step) {
  39778. if (step === void 0) { step = 0.002; }
  39779. this.move(step);
  39780. return this;
  39781. };
  39782. PathCursor.prototype.moveBack = function (step) {
  39783. if (step === void 0) { step = 0.002; }
  39784. this.move(-step);
  39785. return this;
  39786. };
  39787. PathCursor.prototype.move = function (step) {
  39788. if (Math.abs(step) > 1) {
  39789. throw "step size should be less than 1.";
  39790. }
  39791. this.value += step;
  39792. this.ensureLimits();
  39793. this.raiseOnChange();
  39794. return this;
  39795. };
  39796. PathCursor.prototype.ensureLimits = function () {
  39797. while (this.value > 1) {
  39798. this.value -= 1;
  39799. }
  39800. while (this.value < 0) {
  39801. this.value += 1;
  39802. }
  39803. return this;
  39804. };
  39805. // used by animation engine
  39806. PathCursor.prototype.raiseOnChange = function () {
  39807. var _this = this;
  39808. this._onchange.forEach(function (f) { return f(_this); });
  39809. return this;
  39810. };
  39811. PathCursor.prototype.onchange = function (f) {
  39812. this._onchange.push(f);
  39813. return this;
  39814. };
  39815. return PathCursor;
  39816. }());
  39817. BABYLON.PathCursor = PathCursor;
  39818. var Animation = /** @class */ (function () {
  39819. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  39820. this.name = name;
  39821. this.targetProperty = targetProperty;
  39822. this.framePerSecond = framePerSecond;
  39823. this.dataType = dataType;
  39824. this.loopMode = loopMode;
  39825. this.enableBlending = enableBlending;
  39826. this._runtimeAnimations = new Array();
  39827. // The set of event that will be linked to this animation
  39828. this._events = new Array();
  39829. this.blendingSpeed = 0.01;
  39830. this._ranges = {};
  39831. this.targetPropertyPath = targetProperty.split(".");
  39832. this.dataType = dataType;
  39833. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  39834. }
  39835. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  39836. var dataType = undefined;
  39837. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  39838. dataType = Animation.ANIMATIONTYPE_FLOAT;
  39839. }
  39840. else if (from instanceof BABYLON.Quaternion) {
  39841. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  39842. }
  39843. else if (from instanceof BABYLON.Vector3) {
  39844. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  39845. }
  39846. else if (from instanceof BABYLON.Vector2) {
  39847. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  39848. }
  39849. else if (from instanceof BABYLON.Color3) {
  39850. dataType = Animation.ANIMATIONTYPE_COLOR3;
  39851. }
  39852. else if (from instanceof BABYLON.Size) {
  39853. dataType = Animation.ANIMATIONTYPE_SIZE;
  39854. }
  39855. if (dataType == undefined) {
  39856. return null;
  39857. }
  39858. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  39859. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  39860. animation.setKeys(keys);
  39861. if (easingFunction !== undefined) {
  39862. animation.setEasingFunction(easingFunction);
  39863. }
  39864. return animation;
  39865. };
  39866. /**
  39867. * Sets up an animation.
  39868. * @param property the property to animate
  39869. * @param animationType the animation type to apply
  39870. * @param easingFunction the easing function used in the animation
  39871. * @returns The created animation
  39872. */
  39873. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  39874. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39875. animation.setEasingFunction(easingFunction);
  39876. return animation;
  39877. };
  39878. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  39879. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  39880. if (!animation) {
  39881. return null;
  39882. }
  39883. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  39884. };
  39885. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  39886. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  39887. if (!animation) {
  39888. return null;
  39889. }
  39890. node.animations.push(animation);
  39891. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  39892. };
  39893. /**
  39894. * Transition property of the Camera to the target Value.
  39895. * @param property The property to transition
  39896. * @param targetValue The target Value of the property
  39897. * @param host The object where the property to animate belongs
  39898. * @param scene Scene used to run the animation
  39899. * @param frameRate Framerate (in frame/s) to use
  39900. * @param transition The transition type we want to use
  39901. * @param duration The duration of the animation, in milliseconds
  39902. * @param onAnimationEnd Call back trigger at the end of the animation.
  39903. */
  39904. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  39905. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  39906. if (duration <= 0) {
  39907. host[property] = targetValue;
  39908. if (onAnimationEnd) {
  39909. onAnimationEnd();
  39910. }
  39911. return null;
  39912. }
  39913. var endFrame = frameRate * (duration / 1000);
  39914. transition.setKeys([{
  39915. frame: 0,
  39916. value: host[property].clone ? host[property].clone() : host[property]
  39917. },
  39918. {
  39919. frame: endFrame,
  39920. value: targetValue
  39921. }]);
  39922. if (!host.animations) {
  39923. host.animations = [];
  39924. }
  39925. host.animations.push(transition);
  39926. var animation = scene.beginAnimation(host, 0, endFrame, false);
  39927. animation.onAnimationEnd = onAnimationEnd;
  39928. return animation;
  39929. };
  39930. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  39931. /**
  39932. * Return the array of runtime animations currently using this animation
  39933. */
  39934. get: function () {
  39935. return this._runtimeAnimations;
  39936. },
  39937. enumerable: true,
  39938. configurable: true
  39939. });
  39940. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  39941. get: function () {
  39942. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  39943. var runtimeAnimation = _a[_i];
  39944. if (!runtimeAnimation.isStopped) {
  39945. return true;
  39946. }
  39947. }
  39948. return false;
  39949. },
  39950. enumerable: true,
  39951. configurable: true
  39952. });
  39953. // Methods
  39954. /**
  39955. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  39956. */
  39957. Animation.prototype.toString = function (fullDetails) {
  39958. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  39959. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  39960. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  39961. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  39962. if (fullDetails) {
  39963. ret += ", Ranges: {";
  39964. var first = true;
  39965. for (var name in this._ranges) {
  39966. if (first) {
  39967. ret += ", ";
  39968. first = false;
  39969. }
  39970. ret += name;
  39971. }
  39972. ret += "}";
  39973. }
  39974. return ret;
  39975. };
  39976. /**
  39977. * Add an event to this animation.
  39978. */
  39979. Animation.prototype.addEvent = function (event) {
  39980. this._events.push(event);
  39981. };
  39982. /**
  39983. * Remove all events found at the given frame
  39984. * @param frame
  39985. */
  39986. Animation.prototype.removeEvents = function (frame) {
  39987. for (var index = 0; index < this._events.length; index++) {
  39988. if (this._events[index].frame === frame) {
  39989. this._events.splice(index, 1);
  39990. index--;
  39991. }
  39992. }
  39993. };
  39994. Animation.prototype.getEvents = function () {
  39995. return this._events;
  39996. };
  39997. Animation.prototype.createRange = function (name, from, to) {
  39998. // check name not already in use; could happen for bones after serialized
  39999. if (!this._ranges[name]) {
  40000. this._ranges[name] = new AnimationRange(name, from, to);
  40001. }
  40002. };
  40003. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40004. if (deleteFrames === void 0) { deleteFrames = true; }
  40005. var range = this._ranges[name];
  40006. if (!range) {
  40007. return;
  40008. }
  40009. if (deleteFrames) {
  40010. var from = range.from;
  40011. var to = range.to;
  40012. // this loop MUST go high to low for multiple splices to work
  40013. for (var key = this._keys.length - 1; key >= 0; key--) {
  40014. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40015. this._keys.splice(key, 1);
  40016. }
  40017. }
  40018. }
  40019. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40020. };
  40021. Animation.prototype.getRange = function (name) {
  40022. return this._ranges[name];
  40023. };
  40024. Animation.prototype.getKeys = function () {
  40025. return this._keys;
  40026. };
  40027. Animation.prototype.getHighestFrame = function () {
  40028. var ret = 0;
  40029. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40030. if (ret < this._keys[key].frame) {
  40031. ret = this._keys[key].frame;
  40032. }
  40033. }
  40034. return ret;
  40035. };
  40036. Animation.prototype.getEasingFunction = function () {
  40037. return this._easingFunction;
  40038. };
  40039. Animation.prototype.setEasingFunction = function (easingFunction) {
  40040. this._easingFunction = easingFunction;
  40041. };
  40042. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40043. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40044. };
  40045. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40046. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40047. };
  40048. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40049. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40050. };
  40051. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40052. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40053. };
  40054. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40055. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40056. };
  40057. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40058. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40059. };
  40060. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40061. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40062. };
  40063. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40064. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40065. };
  40066. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40067. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40068. };
  40069. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40070. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40071. };
  40072. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40073. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40074. };
  40075. Animation.prototype.clone = function () {
  40076. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40077. clone.enableBlending = this.enableBlending;
  40078. clone.blendingSpeed = this.blendingSpeed;
  40079. if (this._keys) {
  40080. clone.setKeys(this._keys);
  40081. }
  40082. if (this._ranges) {
  40083. clone._ranges = {};
  40084. for (var name in this._ranges) {
  40085. var range = this._ranges[name];
  40086. if (!range) {
  40087. continue;
  40088. }
  40089. clone._ranges[name] = range.clone();
  40090. }
  40091. }
  40092. return clone;
  40093. };
  40094. Animation.prototype.setKeys = function (values) {
  40095. this._keys = values.slice(0);
  40096. };
  40097. Animation.prototype.serialize = function () {
  40098. var serializationObject = {};
  40099. serializationObject.name = this.name;
  40100. serializationObject.property = this.targetProperty;
  40101. serializationObject.framePerSecond = this.framePerSecond;
  40102. serializationObject.dataType = this.dataType;
  40103. serializationObject.loopBehavior = this.loopMode;
  40104. serializationObject.enableBlending = this.enableBlending;
  40105. serializationObject.blendingSpeed = this.blendingSpeed;
  40106. var dataType = this.dataType;
  40107. serializationObject.keys = [];
  40108. var keys = this.getKeys();
  40109. for (var index = 0; index < keys.length; index++) {
  40110. var animationKey = keys[index];
  40111. var key = {};
  40112. key.frame = animationKey.frame;
  40113. switch (dataType) {
  40114. case Animation.ANIMATIONTYPE_FLOAT:
  40115. key.values = [animationKey.value];
  40116. break;
  40117. case Animation.ANIMATIONTYPE_QUATERNION:
  40118. case Animation.ANIMATIONTYPE_MATRIX:
  40119. case Animation.ANIMATIONTYPE_VECTOR3:
  40120. case Animation.ANIMATIONTYPE_COLOR3:
  40121. key.values = animationKey.value.asArray();
  40122. break;
  40123. }
  40124. serializationObject.keys.push(key);
  40125. }
  40126. serializationObject.ranges = [];
  40127. for (var name in this._ranges) {
  40128. var source = this._ranges[name];
  40129. if (!source) {
  40130. continue;
  40131. }
  40132. var range = {};
  40133. range.name = name;
  40134. range.from = source.from;
  40135. range.to = source.to;
  40136. serializationObject.ranges.push(range);
  40137. }
  40138. return serializationObject;
  40139. };
  40140. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40141. get: function () {
  40142. return Animation._ANIMATIONTYPE_FLOAT;
  40143. },
  40144. enumerable: true,
  40145. configurable: true
  40146. });
  40147. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40148. get: function () {
  40149. return Animation._ANIMATIONTYPE_VECTOR3;
  40150. },
  40151. enumerable: true,
  40152. configurable: true
  40153. });
  40154. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40155. get: function () {
  40156. return Animation._ANIMATIONTYPE_VECTOR2;
  40157. },
  40158. enumerable: true,
  40159. configurable: true
  40160. });
  40161. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40162. get: function () {
  40163. return Animation._ANIMATIONTYPE_SIZE;
  40164. },
  40165. enumerable: true,
  40166. configurable: true
  40167. });
  40168. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40169. get: function () {
  40170. return Animation._ANIMATIONTYPE_QUATERNION;
  40171. },
  40172. enumerable: true,
  40173. configurable: true
  40174. });
  40175. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40176. get: function () {
  40177. return Animation._ANIMATIONTYPE_MATRIX;
  40178. },
  40179. enumerable: true,
  40180. configurable: true
  40181. });
  40182. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40183. get: function () {
  40184. return Animation._ANIMATIONTYPE_COLOR3;
  40185. },
  40186. enumerable: true,
  40187. configurable: true
  40188. });
  40189. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40190. get: function () {
  40191. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40192. },
  40193. enumerable: true,
  40194. configurable: true
  40195. });
  40196. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40197. get: function () {
  40198. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40199. },
  40200. enumerable: true,
  40201. configurable: true
  40202. });
  40203. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40204. get: function () {
  40205. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40206. },
  40207. enumerable: true,
  40208. configurable: true
  40209. });
  40210. Animation.Parse = function (parsedAnimation) {
  40211. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40212. var dataType = parsedAnimation.dataType;
  40213. var keys = [];
  40214. var data;
  40215. var index;
  40216. if (parsedAnimation.enableBlending) {
  40217. animation.enableBlending = parsedAnimation.enableBlending;
  40218. }
  40219. if (parsedAnimation.blendingSpeed) {
  40220. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40221. }
  40222. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40223. var key = parsedAnimation.keys[index];
  40224. var inTangent;
  40225. var outTangent;
  40226. switch (dataType) {
  40227. case Animation.ANIMATIONTYPE_FLOAT:
  40228. data = key.values[0];
  40229. if (key.values.length >= 1) {
  40230. inTangent = key.values[1];
  40231. }
  40232. if (key.values.length >= 2) {
  40233. outTangent = key.values[2];
  40234. }
  40235. break;
  40236. case Animation.ANIMATIONTYPE_QUATERNION:
  40237. data = BABYLON.Quaternion.FromArray(key.values);
  40238. if (key.values.length >= 8) {
  40239. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40240. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40241. inTangent = _inTangent;
  40242. }
  40243. }
  40244. if (key.values.length >= 12) {
  40245. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40246. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40247. outTangent = _outTangent;
  40248. }
  40249. }
  40250. break;
  40251. case Animation.ANIMATIONTYPE_MATRIX:
  40252. data = BABYLON.Matrix.FromArray(key.values);
  40253. break;
  40254. case Animation.ANIMATIONTYPE_COLOR3:
  40255. data = BABYLON.Color3.FromArray(key.values);
  40256. break;
  40257. case Animation.ANIMATIONTYPE_VECTOR3:
  40258. default:
  40259. data = BABYLON.Vector3.FromArray(key.values);
  40260. break;
  40261. }
  40262. var keyData = {};
  40263. keyData.frame = key.frame;
  40264. keyData.value = data;
  40265. if (inTangent != undefined) {
  40266. keyData.inTangent = inTangent;
  40267. }
  40268. if (outTangent != undefined) {
  40269. keyData.outTangent = outTangent;
  40270. }
  40271. keys.push(keyData);
  40272. }
  40273. animation.setKeys(keys);
  40274. if (parsedAnimation.ranges) {
  40275. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40276. data = parsedAnimation.ranges[index];
  40277. animation.createRange(data.name, data.from, data.to);
  40278. }
  40279. }
  40280. return animation;
  40281. };
  40282. Animation.AppendSerializedAnimations = function (source, destination) {
  40283. if (source.animations) {
  40284. destination.animations = [];
  40285. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40286. var animation = source.animations[animationIndex];
  40287. destination.animations.push(animation.serialize());
  40288. }
  40289. }
  40290. };
  40291. Animation.AllowMatricesInterpolation = false;
  40292. // Statics
  40293. Animation._ANIMATIONTYPE_FLOAT = 0;
  40294. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40295. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40296. Animation._ANIMATIONTYPE_MATRIX = 3;
  40297. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40298. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40299. Animation._ANIMATIONTYPE_SIZE = 6;
  40300. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40301. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40302. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40303. return Animation;
  40304. }());
  40305. BABYLON.Animation = Animation;
  40306. })(BABYLON || (BABYLON = {}));
  40307. //# sourceMappingURL=babylon.animation.js.map
  40308. var BABYLON;
  40309. (function (BABYLON) {
  40310. var RuntimeAnimation = /** @class */ (function () {
  40311. function RuntimeAnimation(target, animation) {
  40312. this._offsetsCache = {};
  40313. this._highLimitsCache = {};
  40314. this._stopped = false;
  40315. this._blendingFactor = 0;
  40316. this._ratioOffset = 0;
  40317. this._animation = animation;
  40318. this._target = target;
  40319. animation._runtimeAnimations.push(this);
  40320. }
  40321. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40322. get: function () {
  40323. return this._animation;
  40324. },
  40325. enumerable: true,
  40326. configurable: true
  40327. });
  40328. RuntimeAnimation.prototype.reset = function () {
  40329. this._offsetsCache = {};
  40330. this._highLimitsCache = {};
  40331. this.currentFrame = 0;
  40332. this._blendingFactor = 0;
  40333. this._originalBlendValue = null;
  40334. };
  40335. RuntimeAnimation.prototype.isStopped = function () {
  40336. return this._stopped;
  40337. };
  40338. RuntimeAnimation.prototype.dispose = function () {
  40339. var index = this._animation.runtimeAnimations.indexOf(this);
  40340. if (index > -1) {
  40341. this._animation.runtimeAnimations.splice(index, 1);
  40342. }
  40343. };
  40344. RuntimeAnimation.prototype._getKeyValue = function (value) {
  40345. if (typeof value === "function") {
  40346. return value();
  40347. }
  40348. return value;
  40349. };
  40350. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  40351. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  40352. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  40353. }
  40354. this.currentFrame = currentFrame;
  40355. var keys = this._animation.getKeys();
  40356. // Try to get a hash to find the right key
  40357. 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));
  40358. if (keys[startKeyIndex].frame >= currentFrame) {
  40359. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  40360. startKeyIndex--;
  40361. }
  40362. }
  40363. for (var key = startKeyIndex; key < keys.length; key++) {
  40364. var endKey = keys[key + 1];
  40365. if (endKey.frame >= currentFrame) {
  40366. var startKey = keys[key];
  40367. var startValue = this._getKeyValue(startKey.value);
  40368. var endValue = this._getKeyValue(endKey.value);
  40369. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  40370. var frameDelta = endKey.frame - startKey.frame;
  40371. // gradient : percent of currentFrame between the frame inf and the frame sup
  40372. var gradient = (currentFrame - startKey.frame) / frameDelta;
  40373. // check for easingFunction and correction of gradient
  40374. var easingFunction = this._animation.getEasingFunction();
  40375. if (easingFunction != null) {
  40376. gradient = easingFunction.ease(gradient);
  40377. }
  40378. switch (this._animation.dataType) {
  40379. // Float
  40380. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40381. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  40382. switch (loopMode) {
  40383. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40384. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40385. return floatValue;
  40386. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40387. return offsetValue * repeatCount + floatValue;
  40388. }
  40389. break;
  40390. // Quaternion
  40391. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40392. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  40393. switch (loopMode) {
  40394. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40395. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40396. return quatValue;
  40397. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40398. return quatValue.add(offsetValue.scale(repeatCount));
  40399. }
  40400. return quatValue;
  40401. // Vector3
  40402. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40403. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  40404. switch (loopMode) {
  40405. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40406. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40407. return vec3Value;
  40408. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40409. return vec3Value.add(offsetValue.scale(repeatCount));
  40410. }
  40411. // Vector2
  40412. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40413. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  40414. switch (loopMode) {
  40415. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40416. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40417. return vec2Value;
  40418. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40419. return vec2Value.add(offsetValue.scale(repeatCount));
  40420. }
  40421. // Size
  40422. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40423. switch (loopMode) {
  40424. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40425. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40426. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  40427. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40428. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40429. }
  40430. // Color3
  40431. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40432. switch (loopMode) {
  40433. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40434. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40435. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  40436. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40437. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40438. }
  40439. // Matrix
  40440. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  40441. switch (loopMode) {
  40442. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40443. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40444. if (BABYLON.Animation.AllowMatricesInterpolation) {
  40445. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  40446. }
  40447. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40448. return startValue;
  40449. }
  40450. default:
  40451. break;
  40452. }
  40453. break;
  40454. }
  40455. }
  40456. return this._getKeyValue(keys[keys.length - 1].value);
  40457. };
  40458. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  40459. if (blend === void 0) { blend = false; }
  40460. // Set value
  40461. var path;
  40462. var destination;
  40463. var targetPropertyPath = this._animation.targetPropertyPath;
  40464. if (targetPropertyPath.length > 1) {
  40465. var property = this._target[targetPropertyPath[0]];
  40466. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  40467. property = property[targetPropertyPath[index]];
  40468. }
  40469. path = targetPropertyPath[targetPropertyPath.length - 1];
  40470. destination = property;
  40471. }
  40472. else {
  40473. path = targetPropertyPath[0];
  40474. destination = this._target;
  40475. }
  40476. // Blending
  40477. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  40478. if (!this._originalBlendValue) {
  40479. if (destination[path].clone) {
  40480. this._originalBlendValue = destination[path].clone();
  40481. }
  40482. else {
  40483. this._originalBlendValue = destination[path];
  40484. }
  40485. }
  40486. if (this._originalBlendValue.prototype) {
  40487. if (this._originalBlendValue.prototype.Lerp) {
  40488. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  40489. }
  40490. else {
  40491. destination[path] = currentValue;
  40492. }
  40493. }
  40494. else if (this._originalBlendValue.m) {
  40495. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  40496. }
  40497. else {
  40498. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  40499. }
  40500. this._blendingFactor += this._animation.blendingSpeed;
  40501. }
  40502. else {
  40503. destination[path] = currentValue;
  40504. }
  40505. if (this._target.markAsDirty) {
  40506. this._target.markAsDirty(this._animation.targetProperty);
  40507. }
  40508. };
  40509. RuntimeAnimation.prototype.goToFrame = function (frame) {
  40510. var keys = this._animation.getKeys();
  40511. if (frame < keys[0].frame) {
  40512. frame = keys[0].frame;
  40513. }
  40514. else if (frame > keys[keys.length - 1].frame) {
  40515. frame = keys[keys.length - 1].frame;
  40516. }
  40517. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  40518. this.setValue(currentValue);
  40519. };
  40520. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  40521. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  40522. this._ratioOffset = this._previousRatio - newRatio;
  40523. };
  40524. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  40525. if (blend === void 0) { blend = false; }
  40526. var targetPropertyPath = this._animation.targetPropertyPath;
  40527. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  40528. this._stopped = true;
  40529. return false;
  40530. }
  40531. var returnValue = true;
  40532. var keys = this._animation.getKeys();
  40533. // Adding a start key at frame 0 if missing
  40534. if (keys[0].frame !== 0) {
  40535. var newKey = { frame: 0, value: keys[0].value };
  40536. keys.splice(0, 0, newKey);
  40537. }
  40538. // Check limits
  40539. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  40540. from = keys[0].frame;
  40541. }
  40542. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  40543. to = keys[keys.length - 1].frame;
  40544. }
  40545. //to and from cannot be the same key
  40546. if (from === to) {
  40547. if (from > keys[0].frame) {
  40548. from--;
  40549. }
  40550. else if (to < keys[keys.length - 1].frame) {
  40551. to++;
  40552. }
  40553. }
  40554. // Compute ratio
  40555. var range = to - from;
  40556. var offsetValue;
  40557. // ratio represents the frame delta between from and to
  40558. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40559. var highLimitValue = 0;
  40560. this._previousDelay = delay;
  40561. this._previousRatio = ratio;
  40562. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40563. returnValue = false;
  40564. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40565. }
  40566. else {
  40567. // Get max value if required
  40568. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40569. var keyOffset = to.toString() + from.toString();
  40570. if (!this._offsetsCache[keyOffset]) {
  40571. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40572. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40573. switch (this._animation.dataType) {
  40574. // Float
  40575. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40576. this._offsetsCache[keyOffset] = toValue - fromValue;
  40577. break;
  40578. // Quaternion
  40579. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40580. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40581. break;
  40582. // Vector3
  40583. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40584. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40585. // Vector2
  40586. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40587. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40588. // Size
  40589. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40590. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40591. // Color3
  40592. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40593. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40594. default:
  40595. break;
  40596. }
  40597. this._highLimitsCache[keyOffset] = toValue;
  40598. }
  40599. highLimitValue = this._highLimitsCache[keyOffset];
  40600. offsetValue = this._offsetsCache[keyOffset];
  40601. }
  40602. }
  40603. if (offsetValue === undefined) {
  40604. switch (this._animation.dataType) {
  40605. // Float
  40606. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40607. offsetValue = 0;
  40608. break;
  40609. // Quaternion
  40610. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40611. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40612. break;
  40613. // Vector3
  40614. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40615. offsetValue = BABYLON.Vector3.Zero();
  40616. break;
  40617. // Vector2
  40618. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40619. offsetValue = BABYLON.Vector2.Zero();
  40620. break;
  40621. // Size
  40622. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40623. offsetValue = BABYLON.Size.Zero();
  40624. break;
  40625. // Color3
  40626. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40627. offsetValue = BABYLON.Color3.Black();
  40628. }
  40629. }
  40630. // Compute value
  40631. var repeatCount = (ratio / range) >> 0;
  40632. var currentFrame = returnValue ? from + ratio % range : to;
  40633. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40634. // Set value
  40635. this.setValue(currentValue);
  40636. // Check events
  40637. var events = this._animation.getEvents();
  40638. for (var index = 0; index < events.length; index++) {
  40639. // Make sure current frame has passed event frame and that event frame is within the current range
  40640. // Also, handle both forward and reverse animations
  40641. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40642. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40643. var event = events[index];
  40644. if (!event.isDone) {
  40645. // If event should be done only once, remove it.
  40646. if (event.onlyOnce) {
  40647. events.splice(index, 1);
  40648. index--;
  40649. }
  40650. event.isDone = true;
  40651. event.action();
  40652. } // Don't do anything if the event has already be done.
  40653. }
  40654. else if (events[index].isDone && !events[index].onlyOnce) {
  40655. // reset event, the animation is looping
  40656. events[index].isDone = false;
  40657. }
  40658. }
  40659. if (!returnValue) {
  40660. this._stopped = true;
  40661. }
  40662. return returnValue;
  40663. };
  40664. return RuntimeAnimation;
  40665. }());
  40666. BABYLON.RuntimeAnimation = RuntimeAnimation;
  40667. })(BABYLON || (BABYLON = {}));
  40668. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  40669. var BABYLON;
  40670. (function (BABYLON) {
  40671. var Animatable = /** @class */ (function () {
  40672. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  40673. if (fromFrame === void 0) { fromFrame = 0; }
  40674. if (toFrame === void 0) { toFrame = 100; }
  40675. if (loopAnimation === void 0) { loopAnimation = false; }
  40676. if (speedRatio === void 0) { speedRatio = 1.0; }
  40677. this.target = target;
  40678. this.fromFrame = fromFrame;
  40679. this.toFrame = toFrame;
  40680. this.loopAnimation = loopAnimation;
  40681. this.onAnimationEnd = onAnimationEnd;
  40682. this._localDelayOffset = null;
  40683. this._pausedDelay = null;
  40684. this._runtimeAnimations = new Array();
  40685. this._paused = false;
  40686. this._speedRatio = 1;
  40687. this.animationStarted = false;
  40688. if (animations) {
  40689. this.appendAnimations(target, animations);
  40690. }
  40691. this._speedRatio = speedRatio;
  40692. this._scene = scene;
  40693. scene._activeAnimatables.push(this);
  40694. }
  40695. Object.defineProperty(Animatable.prototype, "speedRatio", {
  40696. get: function () {
  40697. return this._speedRatio;
  40698. },
  40699. set: function (value) {
  40700. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  40701. var animation = this._runtimeAnimations[index];
  40702. animation._prepareForSpeedRatioChange(value);
  40703. }
  40704. this._speedRatio = value;
  40705. },
  40706. enumerable: true,
  40707. configurable: true
  40708. });
  40709. // Methods
  40710. Animatable.prototype.getAnimations = function () {
  40711. return this._runtimeAnimations;
  40712. };
  40713. Animatable.prototype.appendAnimations = function (target, animations) {
  40714. for (var index = 0; index < animations.length; index++) {
  40715. var animation = animations[index];
  40716. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  40717. }
  40718. };
  40719. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  40720. var runtimeAnimations = this._runtimeAnimations;
  40721. for (var index = 0; index < runtimeAnimations.length; index++) {
  40722. if (runtimeAnimations[index].animation.targetProperty === property) {
  40723. return runtimeAnimations[index].animation;
  40724. }
  40725. }
  40726. return null;
  40727. };
  40728. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  40729. var runtimeAnimations = this._runtimeAnimations;
  40730. for (var index = 0; index < runtimeAnimations.length; index++) {
  40731. if (runtimeAnimations[index].animation.targetProperty === property) {
  40732. return runtimeAnimations[index];
  40733. }
  40734. }
  40735. return null;
  40736. };
  40737. Animatable.prototype.reset = function () {
  40738. var runtimeAnimations = this._runtimeAnimations;
  40739. for (var index = 0; index < runtimeAnimations.length; index++) {
  40740. runtimeAnimations[index].reset();
  40741. }
  40742. this._localDelayOffset = null;
  40743. this._pausedDelay = null;
  40744. };
  40745. Animatable.prototype.enableBlending = function (blendingSpeed) {
  40746. var runtimeAnimations = this._runtimeAnimations;
  40747. for (var index = 0; index < runtimeAnimations.length; index++) {
  40748. runtimeAnimations[index].animation.enableBlending = true;
  40749. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  40750. }
  40751. };
  40752. Animatable.prototype.disableBlending = function () {
  40753. var runtimeAnimations = this._runtimeAnimations;
  40754. for (var index = 0; index < runtimeAnimations.length; index++) {
  40755. runtimeAnimations[index].animation.enableBlending = false;
  40756. }
  40757. };
  40758. Animatable.prototype.goToFrame = function (frame) {
  40759. var runtimeAnimations = this._runtimeAnimations;
  40760. if (runtimeAnimations[0]) {
  40761. var fps = runtimeAnimations[0].animation.framePerSecond;
  40762. var currentFrame = runtimeAnimations[0].currentFrame;
  40763. var adjustTime = frame - currentFrame;
  40764. var delay = adjustTime * 1000 / fps;
  40765. if (this._localDelayOffset === null) {
  40766. this._localDelayOffset = 0;
  40767. }
  40768. this._localDelayOffset -= delay;
  40769. }
  40770. for (var index = 0; index < runtimeAnimations.length; index++) {
  40771. runtimeAnimations[index].goToFrame(frame);
  40772. }
  40773. };
  40774. Animatable.prototype.pause = function () {
  40775. if (this._paused) {
  40776. return;
  40777. }
  40778. this._paused = true;
  40779. };
  40780. Animatable.prototype.restart = function () {
  40781. this._paused = false;
  40782. };
  40783. Animatable.prototype.stop = function (animationName) {
  40784. if (animationName) {
  40785. var idx = this._scene._activeAnimatables.indexOf(this);
  40786. if (idx > -1) {
  40787. var runtimeAnimations = this._runtimeAnimations;
  40788. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  40789. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  40790. continue;
  40791. }
  40792. runtimeAnimations[index].dispose();
  40793. runtimeAnimations.splice(index, 1);
  40794. }
  40795. if (runtimeAnimations.length == 0) {
  40796. this._scene._activeAnimatables.splice(idx, 1);
  40797. if (this.onAnimationEnd) {
  40798. this.onAnimationEnd();
  40799. }
  40800. }
  40801. }
  40802. }
  40803. else {
  40804. var index = this._scene._activeAnimatables.indexOf(this);
  40805. if (index > -1) {
  40806. this._scene._activeAnimatables.splice(index, 1);
  40807. var runtimeAnimations = this._runtimeAnimations;
  40808. for (var index = 0; index < runtimeAnimations.length; index++) {
  40809. runtimeAnimations[index].dispose();
  40810. }
  40811. if (this.onAnimationEnd) {
  40812. this.onAnimationEnd();
  40813. }
  40814. }
  40815. }
  40816. };
  40817. Animatable.prototype._animate = function (delay) {
  40818. if (this._paused) {
  40819. this.animationStarted = false;
  40820. if (this._pausedDelay === null) {
  40821. this._pausedDelay = delay;
  40822. }
  40823. return true;
  40824. }
  40825. if (this._localDelayOffset === null) {
  40826. this._localDelayOffset = delay;
  40827. }
  40828. else if (this._pausedDelay !== null) {
  40829. this._localDelayOffset += delay - this._pausedDelay;
  40830. this._pausedDelay = null;
  40831. }
  40832. // Animating
  40833. var running = false;
  40834. var runtimeAnimations = this._runtimeAnimations;
  40835. var index;
  40836. for (index = 0; index < runtimeAnimations.length; index++) {
  40837. var animation = runtimeAnimations[index];
  40838. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  40839. running = running || isRunning;
  40840. }
  40841. this.animationStarted = running;
  40842. if (!running) {
  40843. // Remove from active animatables
  40844. index = this._scene._activeAnimatables.indexOf(this);
  40845. this._scene._activeAnimatables.splice(index, 1);
  40846. // Dispose all runtime animations
  40847. for (index = 0; index < runtimeAnimations.length; index++) {
  40848. runtimeAnimations[index].dispose();
  40849. }
  40850. }
  40851. if (!running && this.onAnimationEnd) {
  40852. this.onAnimationEnd();
  40853. this.onAnimationEnd = null;
  40854. }
  40855. return running;
  40856. };
  40857. return Animatable;
  40858. }());
  40859. BABYLON.Animatable = Animatable;
  40860. })(BABYLON || (BABYLON = {}));
  40861. //# sourceMappingURL=babylon.animatable.js.map
  40862. var BABYLON;
  40863. (function (BABYLON) {
  40864. var EasingFunction = /** @class */ (function () {
  40865. function EasingFunction() {
  40866. // Properties
  40867. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  40868. }
  40869. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  40870. get: function () {
  40871. return EasingFunction._EASINGMODE_EASEIN;
  40872. },
  40873. enumerable: true,
  40874. configurable: true
  40875. });
  40876. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  40877. get: function () {
  40878. return EasingFunction._EASINGMODE_EASEOUT;
  40879. },
  40880. enumerable: true,
  40881. configurable: true
  40882. });
  40883. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  40884. get: function () {
  40885. return EasingFunction._EASINGMODE_EASEINOUT;
  40886. },
  40887. enumerable: true,
  40888. configurable: true
  40889. });
  40890. EasingFunction.prototype.setEasingMode = function (easingMode) {
  40891. var n = Math.min(Math.max(easingMode, 0), 2);
  40892. this._easingMode = n;
  40893. };
  40894. EasingFunction.prototype.getEasingMode = function () {
  40895. return this._easingMode;
  40896. };
  40897. EasingFunction.prototype.easeInCore = function (gradient) {
  40898. throw new Error('You must implement this method');
  40899. };
  40900. EasingFunction.prototype.ease = function (gradient) {
  40901. switch (this._easingMode) {
  40902. case EasingFunction.EASINGMODE_EASEIN:
  40903. return this.easeInCore(gradient);
  40904. case EasingFunction.EASINGMODE_EASEOUT:
  40905. return (1 - this.easeInCore(1 - gradient));
  40906. }
  40907. if (gradient >= 0.5) {
  40908. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  40909. }
  40910. return (this.easeInCore(gradient * 2) * 0.5);
  40911. };
  40912. //Statics
  40913. EasingFunction._EASINGMODE_EASEIN = 0;
  40914. EasingFunction._EASINGMODE_EASEOUT = 1;
  40915. EasingFunction._EASINGMODE_EASEINOUT = 2;
  40916. return EasingFunction;
  40917. }());
  40918. BABYLON.EasingFunction = EasingFunction;
  40919. var CircleEase = /** @class */ (function (_super) {
  40920. __extends(CircleEase, _super);
  40921. function CircleEase() {
  40922. return _super !== null && _super.apply(this, arguments) || this;
  40923. }
  40924. CircleEase.prototype.easeInCore = function (gradient) {
  40925. gradient = Math.max(0, Math.min(1, gradient));
  40926. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  40927. };
  40928. return CircleEase;
  40929. }(EasingFunction));
  40930. BABYLON.CircleEase = CircleEase;
  40931. var BackEase = /** @class */ (function (_super) {
  40932. __extends(BackEase, _super);
  40933. function BackEase(amplitude) {
  40934. if (amplitude === void 0) { amplitude = 1; }
  40935. var _this = _super.call(this) || this;
  40936. _this.amplitude = amplitude;
  40937. return _this;
  40938. }
  40939. BackEase.prototype.easeInCore = function (gradient) {
  40940. var num = Math.max(0, this.amplitude);
  40941. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  40942. };
  40943. return BackEase;
  40944. }(EasingFunction));
  40945. BABYLON.BackEase = BackEase;
  40946. var BounceEase = /** @class */ (function (_super) {
  40947. __extends(BounceEase, _super);
  40948. function BounceEase(bounces, bounciness) {
  40949. if (bounces === void 0) { bounces = 3; }
  40950. if (bounciness === void 0) { bounciness = 2; }
  40951. var _this = _super.call(this) || this;
  40952. _this.bounces = bounces;
  40953. _this.bounciness = bounciness;
  40954. return _this;
  40955. }
  40956. BounceEase.prototype.easeInCore = function (gradient) {
  40957. var y = Math.max(0.0, this.bounces);
  40958. var bounciness = this.bounciness;
  40959. if (bounciness <= 1.0) {
  40960. bounciness = 1.001;
  40961. }
  40962. var num9 = Math.pow(bounciness, y);
  40963. var num5 = 1.0 - bounciness;
  40964. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  40965. var num15 = gradient * num4;
  40966. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  40967. var num3 = Math.floor(num65);
  40968. var num13 = num3 + 1.0;
  40969. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  40970. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  40971. var num7 = (num8 + num12) * 0.5;
  40972. var num6 = gradient - num7;
  40973. var num2 = num7 - num8;
  40974. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  40975. };
  40976. return BounceEase;
  40977. }(EasingFunction));
  40978. BABYLON.BounceEase = BounceEase;
  40979. var CubicEase = /** @class */ (function (_super) {
  40980. __extends(CubicEase, _super);
  40981. function CubicEase() {
  40982. return _super !== null && _super.apply(this, arguments) || this;
  40983. }
  40984. CubicEase.prototype.easeInCore = function (gradient) {
  40985. return (gradient * gradient * gradient);
  40986. };
  40987. return CubicEase;
  40988. }(EasingFunction));
  40989. BABYLON.CubicEase = CubicEase;
  40990. var ElasticEase = /** @class */ (function (_super) {
  40991. __extends(ElasticEase, _super);
  40992. function ElasticEase(oscillations, springiness) {
  40993. if (oscillations === void 0) { oscillations = 3; }
  40994. if (springiness === void 0) { springiness = 3; }
  40995. var _this = _super.call(this) || this;
  40996. _this.oscillations = oscillations;
  40997. _this.springiness = springiness;
  40998. return _this;
  40999. }
  41000. ElasticEase.prototype.easeInCore = function (gradient) {
  41001. var num2;
  41002. var num3 = Math.max(0.0, this.oscillations);
  41003. var num = Math.max(0.0, this.springiness);
  41004. if (num == 0) {
  41005. num2 = gradient;
  41006. }
  41007. else {
  41008. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41009. }
  41010. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41011. };
  41012. return ElasticEase;
  41013. }(EasingFunction));
  41014. BABYLON.ElasticEase = ElasticEase;
  41015. var ExponentialEase = /** @class */ (function (_super) {
  41016. __extends(ExponentialEase, _super);
  41017. function ExponentialEase(exponent) {
  41018. if (exponent === void 0) { exponent = 2; }
  41019. var _this = _super.call(this) || this;
  41020. _this.exponent = exponent;
  41021. return _this;
  41022. }
  41023. ExponentialEase.prototype.easeInCore = function (gradient) {
  41024. if (this.exponent <= 0) {
  41025. return gradient;
  41026. }
  41027. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41028. };
  41029. return ExponentialEase;
  41030. }(EasingFunction));
  41031. BABYLON.ExponentialEase = ExponentialEase;
  41032. var PowerEase = /** @class */ (function (_super) {
  41033. __extends(PowerEase, _super);
  41034. function PowerEase(power) {
  41035. if (power === void 0) { power = 2; }
  41036. var _this = _super.call(this) || this;
  41037. _this.power = power;
  41038. return _this;
  41039. }
  41040. PowerEase.prototype.easeInCore = function (gradient) {
  41041. var y = Math.max(0.0, this.power);
  41042. return Math.pow(gradient, y);
  41043. };
  41044. return PowerEase;
  41045. }(EasingFunction));
  41046. BABYLON.PowerEase = PowerEase;
  41047. var QuadraticEase = /** @class */ (function (_super) {
  41048. __extends(QuadraticEase, _super);
  41049. function QuadraticEase() {
  41050. return _super !== null && _super.apply(this, arguments) || this;
  41051. }
  41052. QuadraticEase.prototype.easeInCore = function (gradient) {
  41053. return (gradient * gradient);
  41054. };
  41055. return QuadraticEase;
  41056. }(EasingFunction));
  41057. BABYLON.QuadraticEase = QuadraticEase;
  41058. var QuarticEase = /** @class */ (function (_super) {
  41059. __extends(QuarticEase, _super);
  41060. function QuarticEase() {
  41061. return _super !== null && _super.apply(this, arguments) || this;
  41062. }
  41063. QuarticEase.prototype.easeInCore = function (gradient) {
  41064. return (gradient * gradient * gradient * gradient);
  41065. };
  41066. return QuarticEase;
  41067. }(EasingFunction));
  41068. BABYLON.QuarticEase = QuarticEase;
  41069. var QuinticEase = /** @class */ (function (_super) {
  41070. __extends(QuinticEase, _super);
  41071. function QuinticEase() {
  41072. return _super !== null && _super.apply(this, arguments) || this;
  41073. }
  41074. QuinticEase.prototype.easeInCore = function (gradient) {
  41075. return (gradient * gradient * gradient * gradient * gradient);
  41076. };
  41077. return QuinticEase;
  41078. }(EasingFunction));
  41079. BABYLON.QuinticEase = QuinticEase;
  41080. var SineEase = /** @class */ (function (_super) {
  41081. __extends(SineEase, _super);
  41082. function SineEase() {
  41083. return _super !== null && _super.apply(this, arguments) || this;
  41084. }
  41085. SineEase.prototype.easeInCore = function (gradient) {
  41086. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41087. };
  41088. return SineEase;
  41089. }(EasingFunction));
  41090. BABYLON.SineEase = SineEase;
  41091. var BezierCurveEase = /** @class */ (function (_super) {
  41092. __extends(BezierCurveEase, _super);
  41093. function BezierCurveEase(x1, y1, x2, y2) {
  41094. if (x1 === void 0) { x1 = 0; }
  41095. if (y1 === void 0) { y1 = 0; }
  41096. if (x2 === void 0) { x2 = 1; }
  41097. if (y2 === void 0) { y2 = 1; }
  41098. var _this = _super.call(this) || this;
  41099. _this.x1 = x1;
  41100. _this.y1 = y1;
  41101. _this.x2 = x2;
  41102. _this.y2 = y2;
  41103. return _this;
  41104. }
  41105. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41106. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41107. };
  41108. return BezierCurveEase;
  41109. }(EasingFunction));
  41110. BABYLON.BezierCurveEase = BezierCurveEase;
  41111. })(BABYLON || (BABYLON = {}));
  41112. //# sourceMappingURL=babylon.easing.js.map
  41113. var BABYLON;
  41114. (function (BABYLON) {
  41115. var Condition = /** @class */ (function () {
  41116. function Condition(actionManager) {
  41117. this._actionManager = actionManager;
  41118. }
  41119. Condition.prototype.isValid = function () {
  41120. return true;
  41121. };
  41122. Condition.prototype._getProperty = function (propertyPath) {
  41123. return this._actionManager._getProperty(propertyPath);
  41124. };
  41125. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41126. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41127. };
  41128. Condition.prototype.serialize = function () {
  41129. };
  41130. Condition.prototype._serialize = function (serializedCondition) {
  41131. return {
  41132. type: 2,
  41133. children: [],
  41134. name: serializedCondition.name,
  41135. properties: serializedCondition.properties
  41136. };
  41137. };
  41138. return Condition;
  41139. }());
  41140. BABYLON.Condition = Condition;
  41141. var ValueCondition = /** @class */ (function (_super) {
  41142. __extends(ValueCondition, _super);
  41143. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41144. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41145. var _this = _super.call(this, actionManager) || this;
  41146. _this.propertyPath = propertyPath;
  41147. _this.value = value;
  41148. _this.operator = operator;
  41149. _this._target = target;
  41150. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41151. _this._property = _this._getProperty(_this.propertyPath);
  41152. return _this;
  41153. }
  41154. Object.defineProperty(ValueCondition, "IsEqual", {
  41155. get: function () {
  41156. return ValueCondition._IsEqual;
  41157. },
  41158. enumerable: true,
  41159. configurable: true
  41160. });
  41161. Object.defineProperty(ValueCondition, "IsDifferent", {
  41162. get: function () {
  41163. return ValueCondition._IsDifferent;
  41164. },
  41165. enumerable: true,
  41166. configurable: true
  41167. });
  41168. Object.defineProperty(ValueCondition, "IsGreater", {
  41169. get: function () {
  41170. return ValueCondition._IsGreater;
  41171. },
  41172. enumerable: true,
  41173. configurable: true
  41174. });
  41175. Object.defineProperty(ValueCondition, "IsLesser", {
  41176. get: function () {
  41177. return ValueCondition._IsLesser;
  41178. },
  41179. enumerable: true,
  41180. configurable: true
  41181. });
  41182. // Methods
  41183. ValueCondition.prototype.isValid = function () {
  41184. switch (this.operator) {
  41185. case ValueCondition.IsGreater:
  41186. return this._effectiveTarget[this._property] > this.value;
  41187. case ValueCondition.IsLesser:
  41188. return this._effectiveTarget[this._property] < this.value;
  41189. case ValueCondition.IsEqual:
  41190. case ValueCondition.IsDifferent:
  41191. var check;
  41192. if (this.value.equals) {
  41193. check = this.value.equals(this._effectiveTarget[this._property]);
  41194. }
  41195. else {
  41196. check = this.value === this._effectiveTarget[this._property];
  41197. }
  41198. return this.operator === ValueCondition.IsEqual ? check : !check;
  41199. }
  41200. return false;
  41201. };
  41202. ValueCondition.prototype.serialize = function () {
  41203. return this._serialize({
  41204. name: "ValueCondition",
  41205. properties: [
  41206. BABYLON.Action._GetTargetProperty(this._target),
  41207. { name: "propertyPath", value: this.propertyPath },
  41208. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41209. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41210. ]
  41211. });
  41212. };
  41213. ValueCondition.GetOperatorName = function (operator) {
  41214. switch (operator) {
  41215. case ValueCondition._IsEqual: return "IsEqual";
  41216. case ValueCondition._IsDifferent: return "IsDifferent";
  41217. case ValueCondition._IsGreater: return "IsGreater";
  41218. case ValueCondition._IsLesser: return "IsLesser";
  41219. default: return "";
  41220. }
  41221. };
  41222. // Statics
  41223. ValueCondition._IsEqual = 0;
  41224. ValueCondition._IsDifferent = 1;
  41225. ValueCondition._IsGreater = 2;
  41226. ValueCondition._IsLesser = 3;
  41227. return ValueCondition;
  41228. }(Condition));
  41229. BABYLON.ValueCondition = ValueCondition;
  41230. var PredicateCondition = /** @class */ (function (_super) {
  41231. __extends(PredicateCondition, _super);
  41232. function PredicateCondition(actionManager, predicate) {
  41233. var _this = _super.call(this, actionManager) || this;
  41234. _this.predicate = predicate;
  41235. return _this;
  41236. }
  41237. PredicateCondition.prototype.isValid = function () {
  41238. return this.predicate();
  41239. };
  41240. return PredicateCondition;
  41241. }(Condition));
  41242. BABYLON.PredicateCondition = PredicateCondition;
  41243. var StateCondition = /** @class */ (function (_super) {
  41244. __extends(StateCondition, _super);
  41245. function StateCondition(actionManager, target, value) {
  41246. var _this = _super.call(this, actionManager) || this;
  41247. _this.value = value;
  41248. _this._target = target;
  41249. return _this;
  41250. }
  41251. // Methods
  41252. StateCondition.prototype.isValid = function () {
  41253. return this._target.state === this.value;
  41254. };
  41255. StateCondition.prototype.serialize = function () {
  41256. return this._serialize({
  41257. name: "StateCondition",
  41258. properties: [
  41259. BABYLON.Action._GetTargetProperty(this._target),
  41260. { name: "value", value: this.value }
  41261. ]
  41262. });
  41263. };
  41264. return StateCondition;
  41265. }(Condition));
  41266. BABYLON.StateCondition = StateCondition;
  41267. })(BABYLON || (BABYLON = {}));
  41268. //# sourceMappingURL=babylon.condition.js.map
  41269. var BABYLON;
  41270. (function (BABYLON) {
  41271. var Action = /** @class */ (function () {
  41272. function Action(triggerOptions, condition) {
  41273. this.triggerOptions = triggerOptions;
  41274. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41275. if (triggerOptions.parameter) {
  41276. this.trigger = triggerOptions.trigger;
  41277. this._triggerParameter = triggerOptions.parameter;
  41278. }
  41279. else {
  41280. this.trigger = triggerOptions;
  41281. }
  41282. this._nextActiveAction = this;
  41283. this._condition = condition;
  41284. }
  41285. // Methods
  41286. Action.prototype._prepare = function () {
  41287. };
  41288. Action.prototype.getTriggerParameter = function () {
  41289. return this._triggerParameter;
  41290. };
  41291. Action.prototype._executeCurrent = function (evt) {
  41292. if (this._nextActiveAction._condition) {
  41293. var condition = this._nextActiveAction._condition;
  41294. var currentRenderId = this._actionManager.getScene().getRenderId();
  41295. // We cache the current evaluation for the current frame
  41296. if (condition._evaluationId === currentRenderId) {
  41297. if (!condition._currentResult) {
  41298. return;
  41299. }
  41300. }
  41301. else {
  41302. condition._evaluationId = currentRenderId;
  41303. if (!condition.isValid()) {
  41304. condition._currentResult = false;
  41305. return;
  41306. }
  41307. condition._currentResult = true;
  41308. }
  41309. }
  41310. this.onBeforeExecuteObservable.notifyObservers(this);
  41311. this._nextActiveAction.execute(evt);
  41312. this.skipToNextActiveAction();
  41313. };
  41314. Action.prototype.execute = function (evt) {
  41315. };
  41316. Action.prototype.skipToNextActiveAction = function () {
  41317. if (this._nextActiveAction._child) {
  41318. if (!this._nextActiveAction._child._actionManager) {
  41319. this._nextActiveAction._child._actionManager = this._actionManager;
  41320. }
  41321. this._nextActiveAction = this._nextActiveAction._child;
  41322. }
  41323. else {
  41324. this._nextActiveAction = this;
  41325. }
  41326. };
  41327. Action.prototype.then = function (action) {
  41328. this._child = action;
  41329. action._actionManager = this._actionManager;
  41330. action._prepare();
  41331. return action;
  41332. };
  41333. Action.prototype._getProperty = function (propertyPath) {
  41334. return this._actionManager._getProperty(propertyPath);
  41335. };
  41336. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41337. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41338. };
  41339. Action.prototype.serialize = function (parent) {
  41340. };
  41341. // Called by BABYLON.Action objects in serialize(...). Internal use
  41342. Action.prototype._serialize = function (serializedAction, parent) {
  41343. var serializationObject = {
  41344. type: 1,
  41345. children: [],
  41346. name: serializedAction.name,
  41347. properties: serializedAction.properties || []
  41348. };
  41349. // Serialize child
  41350. if (this._child) {
  41351. this._child.serialize(serializationObject);
  41352. }
  41353. // Check if "this" has a condition
  41354. if (this._condition) {
  41355. var serializedCondition = this._condition.serialize();
  41356. serializedCondition.children.push(serializationObject);
  41357. if (parent) {
  41358. parent.children.push(serializedCondition);
  41359. }
  41360. return serializedCondition;
  41361. }
  41362. if (parent) {
  41363. parent.children.push(serializationObject);
  41364. }
  41365. return serializationObject;
  41366. };
  41367. Action._SerializeValueAsString = function (value) {
  41368. if (typeof value === "number") {
  41369. return value.toString();
  41370. }
  41371. if (typeof value === "boolean") {
  41372. return value ? "true" : "false";
  41373. }
  41374. if (value instanceof BABYLON.Vector2) {
  41375. return value.x + ", " + value.y;
  41376. }
  41377. if (value instanceof BABYLON.Vector3) {
  41378. return value.x + ", " + value.y + ", " + value.z;
  41379. }
  41380. if (value instanceof BABYLON.Color3) {
  41381. return value.r + ", " + value.g + ", " + value.b;
  41382. }
  41383. if (value instanceof BABYLON.Color4) {
  41384. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41385. }
  41386. return value; // string
  41387. };
  41388. Action._GetTargetProperty = function (target) {
  41389. return {
  41390. name: "target",
  41391. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41392. : target instanceof BABYLON.Light ? "LightProperties"
  41393. : target instanceof BABYLON.Camera ? "CameraProperties"
  41394. : "SceneProperties",
  41395. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41396. };
  41397. };
  41398. return Action;
  41399. }());
  41400. BABYLON.Action = Action;
  41401. })(BABYLON || (BABYLON = {}));
  41402. //# sourceMappingURL=babylon.action.js.map
  41403. var BABYLON;
  41404. (function (BABYLON) {
  41405. /**
  41406. * ActionEvent is the event beint sent when an action is triggered.
  41407. */
  41408. var ActionEvent = /** @class */ (function () {
  41409. /**
  41410. * @param source The mesh or sprite that triggered the action.
  41411. * @param pointerX The X mouse cursor position at the time of the event
  41412. * @param pointerY The Y mouse cursor position at the time of the event
  41413. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41414. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41415. */
  41416. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41417. this.source = source;
  41418. this.pointerX = pointerX;
  41419. this.pointerY = pointerY;
  41420. this.meshUnderPointer = meshUnderPointer;
  41421. this.sourceEvent = sourceEvent;
  41422. this.additionalData = additionalData;
  41423. }
  41424. /**
  41425. * Helper function to auto-create an ActionEvent from a source mesh.
  41426. * @param source The source mesh that triggered the event
  41427. * @param evt {Event} The original (browser) event
  41428. */
  41429. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41430. var scene = source.getScene();
  41431. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41432. };
  41433. /**
  41434. * Helper function to auto-create an ActionEvent from a source mesh.
  41435. * @param source The source sprite that triggered the event
  41436. * @param scene Scene associated with the sprite
  41437. * @param evt {Event} The original (browser) event
  41438. */
  41439. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41440. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41441. };
  41442. /**
  41443. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41444. * @param scene the scene where the event occurred
  41445. * @param evt {Event} The original (browser) event
  41446. */
  41447. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41448. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41449. };
  41450. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41451. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41452. };
  41453. return ActionEvent;
  41454. }());
  41455. BABYLON.ActionEvent = ActionEvent;
  41456. /**
  41457. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41458. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41459. */
  41460. var ActionManager = /** @class */ (function () {
  41461. function ActionManager(scene) {
  41462. // Members
  41463. this.actions = new Array();
  41464. this.hoverCursor = '';
  41465. this._scene = scene;
  41466. scene._actionManagers.push(this);
  41467. }
  41468. Object.defineProperty(ActionManager, "NothingTrigger", {
  41469. get: function () {
  41470. return ActionManager._NothingTrigger;
  41471. },
  41472. enumerable: true,
  41473. configurable: true
  41474. });
  41475. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41476. get: function () {
  41477. return ActionManager._OnPickTrigger;
  41478. },
  41479. enumerable: true,
  41480. configurable: true
  41481. });
  41482. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41483. get: function () {
  41484. return ActionManager._OnLeftPickTrigger;
  41485. },
  41486. enumerable: true,
  41487. configurable: true
  41488. });
  41489. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41490. get: function () {
  41491. return ActionManager._OnRightPickTrigger;
  41492. },
  41493. enumerable: true,
  41494. configurable: true
  41495. });
  41496. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41497. get: function () {
  41498. return ActionManager._OnCenterPickTrigger;
  41499. },
  41500. enumerable: true,
  41501. configurable: true
  41502. });
  41503. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41504. get: function () {
  41505. return ActionManager._OnPickDownTrigger;
  41506. },
  41507. enumerable: true,
  41508. configurable: true
  41509. });
  41510. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41511. get: function () {
  41512. return ActionManager._OnDoublePickTrigger;
  41513. },
  41514. enumerable: true,
  41515. configurable: true
  41516. });
  41517. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41518. get: function () {
  41519. return ActionManager._OnPickUpTrigger;
  41520. },
  41521. enumerable: true,
  41522. configurable: true
  41523. });
  41524. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41525. /// This trigger will only be raised if you also declared a OnPickDown
  41526. get: function () {
  41527. return ActionManager._OnPickOutTrigger;
  41528. },
  41529. enumerable: true,
  41530. configurable: true
  41531. });
  41532. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41533. get: function () {
  41534. return ActionManager._OnLongPressTrigger;
  41535. },
  41536. enumerable: true,
  41537. configurable: true
  41538. });
  41539. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41540. get: function () {
  41541. return ActionManager._OnPointerOverTrigger;
  41542. },
  41543. enumerable: true,
  41544. configurable: true
  41545. });
  41546. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41547. get: function () {
  41548. return ActionManager._OnPointerOutTrigger;
  41549. },
  41550. enumerable: true,
  41551. configurable: true
  41552. });
  41553. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41554. get: function () {
  41555. return ActionManager._OnEveryFrameTrigger;
  41556. },
  41557. enumerable: true,
  41558. configurable: true
  41559. });
  41560. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41561. get: function () {
  41562. return ActionManager._OnIntersectionEnterTrigger;
  41563. },
  41564. enumerable: true,
  41565. configurable: true
  41566. });
  41567. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41568. get: function () {
  41569. return ActionManager._OnIntersectionExitTrigger;
  41570. },
  41571. enumerable: true,
  41572. configurable: true
  41573. });
  41574. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41575. get: function () {
  41576. return ActionManager._OnKeyDownTrigger;
  41577. },
  41578. enumerable: true,
  41579. configurable: true
  41580. });
  41581. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41582. get: function () {
  41583. return ActionManager._OnKeyUpTrigger;
  41584. },
  41585. enumerable: true,
  41586. configurable: true
  41587. });
  41588. // Methods
  41589. ActionManager.prototype.dispose = function () {
  41590. var index = this._scene._actionManagers.indexOf(this);
  41591. for (var i = 0; i < this.actions.length; i++) {
  41592. var action = this.actions[i];
  41593. ActionManager.Triggers[action.trigger]--;
  41594. if (ActionManager.Triggers[action.trigger] === 0) {
  41595. delete ActionManager.Triggers[action.trigger];
  41596. }
  41597. }
  41598. if (index > -1) {
  41599. this._scene._actionManagers.splice(index, 1);
  41600. }
  41601. };
  41602. ActionManager.prototype.getScene = function () {
  41603. return this._scene;
  41604. };
  41605. /**
  41606. * Does this action manager handles actions of any of the given triggers
  41607. * @param {number[]} triggers - the triggers to be tested
  41608. * @return {boolean} whether one (or more) of the triggers is handeled
  41609. */
  41610. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41611. for (var index = 0; index < this.actions.length; index++) {
  41612. var action = this.actions[index];
  41613. if (triggers.indexOf(action.trigger) > -1) {
  41614. return true;
  41615. }
  41616. }
  41617. return false;
  41618. };
  41619. /**
  41620. * Does this action manager handles actions of a given trigger
  41621. * @param {number} trigger - the trigger to be tested
  41622. * @return {boolean} whether the trigger is handeled
  41623. */
  41624. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41625. for (var index = 0; index < this.actions.length; index++) {
  41626. var action = this.actions[index];
  41627. if (action.trigger === trigger) {
  41628. return true;
  41629. }
  41630. }
  41631. return false;
  41632. };
  41633. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41634. /**
  41635. * Does this action manager has pointer triggers
  41636. * @return {boolean} whether or not it has pointer triggers
  41637. */
  41638. get: function () {
  41639. for (var index = 0; index < this.actions.length; index++) {
  41640. var action = this.actions[index];
  41641. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41642. return true;
  41643. }
  41644. }
  41645. return false;
  41646. },
  41647. enumerable: true,
  41648. configurable: true
  41649. });
  41650. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41651. /**
  41652. * Does this action manager has pick triggers
  41653. * @return {boolean} whether or not it has pick triggers
  41654. */
  41655. get: function () {
  41656. for (var index = 0; index < this.actions.length; index++) {
  41657. var action = this.actions[index];
  41658. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41659. return true;
  41660. }
  41661. }
  41662. return false;
  41663. },
  41664. enumerable: true,
  41665. configurable: true
  41666. });
  41667. Object.defineProperty(ActionManager, "HasTriggers", {
  41668. /**
  41669. * Does exist one action manager with at least one trigger
  41670. * @return {boolean} whether or not it exists one action manager with one trigger
  41671. **/
  41672. get: function () {
  41673. for (var t in ActionManager.Triggers) {
  41674. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41675. return true;
  41676. }
  41677. }
  41678. return false;
  41679. },
  41680. enumerable: true,
  41681. configurable: true
  41682. });
  41683. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41684. /**
  41685. * Does exist one action manager with at least one pick trigger
  41686. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41687. **/
  41688. get: function () {
  41689. for (var t in ActionManager.Triggers) {
  41690. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41691. var t_int = parseInt(t);
  41692. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41693. return true;
  41694. }
  41695. }
  41696. }
  41697. return false;
  41698. },
  41699. enumerable: true,
  41700. configurable: true
  41701. });
  41702. /**
  41703. * Does exist one action manager that handles actions of a given trigger
  41704. * @param {number} trigger - the trigger to be tested
  41705. * @return {boolean} whether the trigger is handeled by at least one action manager
  41706. **/
  41707. ActionManager.HasSpecificTrigger = function (trigger) {
  41708. for (var t in ActionManager.Triggers) {
  41709. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41710. var t_int = parseInt(t);
  41711. if (t_int === trigger) {
  41712. return true;
  41713. }
  41714. }
  41715. }
  41716. return false;
  41717. };
  41718. /**
  41719. * Registers an action to this action manager
  41720. * @param {BABYLON.Action} action - the action to be registered
  41721. * @return {BABYLON.Action} the action amended (prepared) after registration
  41722. */
  41723. ActionManager.prototype.registerAction = function (action) {
  41724. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41725. if (this.getScene().actionManager !== this) {
  41726. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41727. return null;
  41728. }
  41729. }
  41730. this.actions.push(action);
  41731. if (ActionManager.Triggers[action.trigger]) {
  41732. ActionManager.Triggers[action.trigger]++;
  41733. }
  41734. else {
  41735. ActionManager.Triggers[action.trigger] = 1;
  41736. }
  41737. action._actionManager = this;
  41738. action._prepare();
  41739. return action;
  41740. };
  41741. /**
  41742. * Process a specific trigger
  41743. * @param {number} trigger - the trigger to process
  41744. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41745. */
  41746. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41747. for (var index = 0; index < this.actions.length; index++) {
  41748. var action = this.actions[index];
  41749. if (action.trigger === trigger) {
  41750. if (evt) {
  41751. if (trigger === ActionManager.OnKeyUpTrigger
  41752. || trigger === ActionManager.OnKeyDownTrigger) {
  41753. var parameter = action.getTriggerParameter();
  41754. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41755. if (!parameter.toLowerCase) {
  41756. continue;
  41757. }
  41758. var lowerCase = parameter.toLowerCase();
  41759. if (lowerCase !== evt.sourceEvent.key) {
  41760. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41761. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41762. if (actualkey !== lowerCase) {
  41763. continue;
  41764. }
  41765. }
  41766. }
  41767. }
  41768. }
  41769. action._executeCurrent(evt);
  41770. }
  41771. }
  41772. };
  41773. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41774. var properties = propertyPath.split(".");
  41775. for (var index = 0; index < properties.length - 1; index++) {
  41776. target = target[properties[index]];
  41777. }
  41778. return target;
  41779. };
  41780. ActionManager.prototype._getProperty = function (propertyPath) {
  41781. var properties = propertyPath.split(".");
  41782. return properties[properties.length - 1];
  41783. };
  41784. ActionManager.prototype.serialize = function (name) {
  41785. var root = {
  41786. children: new Array(),
  41787. name: name,
  41788. type: 3,
  41789. properties: new Array() // Empty for root but required
  41790. };
  41791. for (var i = 0; i < this.actions.length; i++) {
  41792. var triggerObject = {
  41793. type: 0,
  41794. children: new Array(),
  41795. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41796. properties: new Array()
  41797. };
  41798. var triggerOptions = this.actions[i].triggerOptions;
  41799. if (triggerOptions && typeof triggerOptions !== "number") {
  41800. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41801. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  41802. }
  41803. else {
  41804. var parameter = {};
  41805. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  41806. if (triggerOptions.parameter.mesh) {
  41807. parameter._meshId = triggerOptions.parameter.mesh.id;
  41808. }
  41809. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  41810. }
  41811. }
  41812. // Serialize child action, recursively
  41813. this.actions[i].serialize(triggerObject);
  41814. // Add serialized trigger
  41815. root.children.push(triggerObject);
  41816. }
  41817. return root;
  41818. };
  41819. ActionManager.Parse = function (parsedActions, object, scene) {
  41820. var actionManager = new BABYLON.ActionManager(scene);
  41821. if (object === null)
  41822. scene.actionManager = actionManager;
  41823. else
  41824. object.actionManager = actionManager;
  41825. // instanciate a new object
  41826. var instanciate = function (name, params) {
  41827. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  41828. newInstance.constructor.apply(newInstance, params);
  41829. return newInstance;
  41830. };
  41831. var parseParameter = function (name, value, target, propertyPath) {
  41832. if (propertyPath === null) {
  41833. // String, boolean or float
  41834. var floatValue = parseFloat(value);
  41835. if (value === "true" || value === "false")
  41836. return value === "true";
  41837. else
  41838. return isNaN(floatValue) ? value : floatValue;
  41839. }
  41840. var effectiveTarget = propertyPath.split(".");
  41841. var values = value.split(",");
  41842. // Get effective Target
  41843. for (var i = 0; i < effectiveTarget.length; i++) {
  41844. target = target[effectiveTarget[i]];
  41845. }
  41846. // Return appropriate value with its type
  41847. if (typeof (target) === "boolean")
  41848. return values[0] === "true";
  41849. if (typeof (target) === "string")
  41850. return values[0];
  41851. // Parameters with multiple values such as Vector3 etc.
  41852. var split = new Array();
  41853. for (var i = 0; i < values.length; i++)
  41854. split.push(parseFloat(values[i]));
  41855. if (target instanceof BABYLON.Vector3)
  41856. return BABYLON.Vector3.FromArray(split);
  41857. if (target instanceof BABYLON.Vector4)
  41858. return BABYLON.Vector4.FromArray(split);
  41859. if (target instanceof BABYLON.Color3)
  41860. return BABYLON.Color3.FromArray(split);
  41861. if (target instanceof BABYLON.Color4)
  41862. return BABYLON.Color4.FromArray(split);
  41863. return parseFloat(values[0]);
  41864. };
  41865. // traverse graph per trigger
  41866. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  41867. if (combineArray === void 0) { combineArray = null; }
  41868. if (parsedAction.detached)
  41869. return;
  41870. var parameters = new Array();
  41871. var target = null;
  41872. var propertyPath = null;
  41873. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  41874. // Parameters
  41875. if (parsedAction.type === 2)
  41876. parameters.push(actionManager);
  41877. else
  41878. parameters.push(trigger);
  41879. if (combine) {
  41880. var actions = new Array();
  41881. for (var j = 0; j < parsedAction.combine.length; j++) {
  41882. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  41883. }
  41884. parameters.push(actions);
  41885. }
  41886. else {
  41887. for (var i = 0; i < parsedAction.properties.length; i++) {
  41888. var value = parsedAction.properties[i].value;
  41889. var name = parsedAction.properties[i].name;
  41890. var targetType = parsedAction.properties[i].targetType;
  41891. if (name === "target")
  41892. if (targetType !== null && targetType === "SceneProperties")
  41893. value = target = scene;
  41894. else
  41895. value = target = scene.getNodeByName(value);
  41896. else if (name === "parent")
  41897. value = scene.getNodeByName(value);
  41898. else if (name === "sound")
  41899. value = scene.getSoundByName(value);
  41900. else if (name !== "propertyPath") {
  41901. if (parsedAction.type === 2 && name === "operator")
  41902. value = BABYLON.ValueCondition[value];
  41903. else
  41904. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  41905. }
  41906. else {
  41907. propertyPath = value;
  41908. }
  41909. parameters.push(value);
  41910. }
  41911. }
  41912. if (combineArray === null) {
  41913. parameters.push(condition);
  41914. }
  41915. else {
  41916. parameters.push(null);
  41917. }
  41918. // If interpolate value action
  41919. if (parsedAction.name === "InterpolateValueAction") {
  41920. var param = parameters[parameters.length - 2];
  41921. parameters[parameters.length - 1] = param;
  41922. parameters[parameters.length - 2] = condition;
  41923. }
  41924. // Action or condition(s) and not CombineAction
  41925. var newAction = instanciate(parsedAction.name, parameters);
  41926. if (newAction instanceof BABYLON.Condition && condition !== null) {
  41927. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  41928. if (action)
  41929. action.then(nothing);
  41930. else
  41931. actionManager.registerAction(nothing);
  41932. action = nothing;
  41933. }
  41934. if (combineArray === null) {
  41935. if (newAction instanceof BABYLON.Condition) {
  41936. condition = newAction;
  41937. newAction = action;
  41938. }
  41939. else {
  41940. condition = null;
  41941. if (action)
  41942. action.then(newAction);
  41943. else
  41944. actionManager.registerAction(newAction);
  41945. }
  41946. }
  41947. else {
  41948. combineArray.push(newAction);
  41949. }
  41950. for (var i = 0; i < parsedAction.children.length; i++)
  41951. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  41952. };
  41953. // triggers
  41954. for (var i = 0; i < parsedActions.children.length; i++) {
  41955. var triggerParams;
  41956. var trigger = parsedActions.children[i];
  41957. if (trigger.properties.length > 0) {
  41958. var param = trigger.properties[0].value;
  41959. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  41960. if (value._meshId) {
  41961. value.mesh = scene.getMeshByID(value._meshId);
  41962. }
  41963. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  41964. }
  41965. else
  41966. triggerParams = ActionManager[trigger.name];
  41967. for (var j = 0; j < trigger.children.length; j++) {
  41968. if (!trigger.detached)
  41969. traverse(trigger.children[j], triggerParams, null, null);
  41970. }
  41971. }
  41972. };
  41973. ActionManager.GetTriggerName = function (trigger) {
  41974. switch (trigger) {
  41975. case 0: return "NothingTrigger";
  41976. case 1: return "OnPickTrigger";
  41977. case 2: return "OnLeftPickTrigger";
  41978. case 3: return "OnRightPickTrigger";
  41979. case 4: return "OnCenterPickTrigger";
  41980. case 5: return "OnPickDownTrigger";
  41981. case 6: return "OnPickUpTrigger";
  41982. case 7: return "OnLongPressTrigger";
  41983. case 8: return "OnPointerOverTrigger";
  41984. case 9: return "OnPointerOutTrigger";
  41985. case 10: return "OnEveryFrameTrigger";
  41986. case 11: return "OnIntersectionEnterTrigger";
  41987. case 12: return "OnIntersectionExitTrigger";
  41988. case 13: return "OnKeyDownTrigger";
  41989. case 14: return "OnKeyUpTrigger";
  41990. case 15: return "OnPickOutTrigger";
  41991. default: return "";
  41992. }
  41993. };
  41994. // Statics
  41995. ActionManager._NothingTrigger = 0;
  41996. ActionManager._OnPickTrigger = 1;
  41997. ActionManager._OnLeftPickTrigger = 2;
  41998. ActionManager._OnRightPickTrigger = 3;
  41999. ActionManager._OnCenterPickTrigger = 4;
  42000. ActionManager._OnPickDownTrigger = 5;
  42001. ActionManager._OnDoublePickTrigger = 6;
  42002. ActionManager._OnPickUpTrigger = 7;
  42003. ActionManager._OnLongPressTrigger = 8;
  42004. ActionManager._OnPointerOverTrigger = 9;
  42005. ActionManager._OnPointerOutTrigger = 10;
  42006. ActionManager._OnEveryFrameTrigger = 11;
  42007. ActionManager._OnIntersectionEnterTrigger = 12;
  42008. ActionManager._OnIntersectionExitTrigger = 13;
  42009. ActionManager._OnKeyDownTrigger = 14;
  42010. ActionManager._OnKeyUpTrigger = 15;
  42011. ActionManager._OnPickOutTrigger = 16;
  42012. ActionManager.Triggers = {};
  42013. return ActionManager;
  42014. }());
  42015. BABYLON.ActionManager = ActionManager;
  42016. })(BABYLON || (BABYLON = {}));
  42017. //# sourceMappingURL=babylon.actionManager.js.map
  42018. var BABYLON;
  42019. (function (BABYLON) {
  42020. var InterpolateValueAction = /** @class */ (function (_super) {
  42021. __extends(InterpolateValueAction, _super);
  42022. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42023. if (duration === void 0) { duration = 1000; }
  42024. var _this = _super.call(this, triggerOptions, condition) || this;
  42025. _this.propertyPath = propertyPath;
  42026. _this.value = value;
  42027. _this.duration = duration;
  42028. _this.stopOtherAnimations = stopOtherAnimations;
  42029. _this.onInterpolationDone = onInterpolationDone;
  42030. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42031. _this._target = _this._effectiveTarget = target;
  42032. return _this;
  42033. }
  42034. InterpolateValueAction.prototype._prepare = function () {
  42035. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42036. this._property = this._getProperty(this.propertyPath);
  42037. };
  42038. InterpolateValueAction.prototype.execute = function () {
  42039. var _this = this;
  42040. var scene = this._actionManager.getScene();
  42041. var keys = [
  42042. {
  42043. frame: 0,
  42044. value: this._effectiveTarget[this._property]
  42045. }, {
  42046. frame: 100,
  42047. value: this.value
  42048. }
  42049. ];
  42050. var dataType;
  42051. if (typeof this.value === "number") {
  42052. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42053. }
  42054. else if (this.value instanceof BABYLON.Color3) {
  42055. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42056. }
  42057. else if (this.value instanceof BABYLON.Vector3) {
  42058. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42059. }
  42060. else if (this.value instanceof BABYLON.Matrix) {
  42061. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42062. }
  42063. else if (this.value instanceof BABYLON.Quaternion) {
  42064. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42065. }
  42066. else {
  42067. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42068. return;
  42069. }
  42070. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42071. animation.setKeys(keys);
  42072. if (this.stopOtherAnimations) {
  42073. scene.stopAnimation(this._effectiveTarget);
  42074. }
  42075. var wrapper = function () {
  42076. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42077. if (_this.onInterpolationDone) {
  42078. _this.onInterpolationDone();
  42079. }
  42080. };
  42081. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42082. };
  42083. InterpolateValueAction.prototype.serialize = function (parent) {
  42084. return _super.prototype._serialize.call(this, {
  42085. name: "InterpolateValueAction",
  42086. properties: [
  42087. BABYLON.Action._GetTargetProperty(this._target),
  42088. { name: "propertyPath", value: this.propertyPath },
  42089. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42090. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42091. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42092. ]
  42093. }, parent);
  42094. };
  42095. return InterpolateValueAction;
  42096. }(BABYLON.Action));
  42097. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42098. })(BABYLON || (BABYLON = {}));
  42099. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42100. var BABYLON;
  42101. (function (BABYLON) {
  42102. var SwitchBooleanAction = /** @class */ (function (_super) {
  42103. __extends(SwitchBooleanAction, _super);
  42104. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42105. var _this = _super.call(this, triggerOptions, condition) || this;
  42106. _this.propertyPath = propertyPath;
  42107. _this._target = _this._effectiveTarget = target;
  42108. return _this;
  42109. }
  42110. SwitchBooleanAction.prototype._prepare = function () {
  42111. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42112. this._property = this._getProperty(this.propertyPath);
  42113. };
  42114. SwitchBooleanAction.prototype.execute = function () {
  42115. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42116. };
  42117. SwitchBooleanAction.prototype.serialize = function (parent) {
  42118. return _super.prototype._serialize.call(this, {
  42119. name: "SwitchBooleanAction",
  42120. properties: [
  42121. BABYLON.Action._GetTargetProperty(this._target),
  42122. { name: "propertyPath", value: this.propertyPath }
  42123. ]
  42124. }, parent);
  42125. };
  42126. return SwitchBooleanAction;
  42127. }(BABYLON.Action));
  42128. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42129. var SetStateAction = /** @class */ (function (_super) {
  42130. __extends(SetStateAction, _super);
  42131. function SetStateAction(triggerOptions, target, value, condition) {
  42132. var _this = _super.call(this, triggerOptions, condition) || this;
  42133. _this.value = value;
  42134. _this._target = target;
  42135. return _this;
  42136. }
  42137. SetStateAction.prototype.execute = function () {
  42138. this._target.state = this.value;
  42139. };
  42140. SetStateAction.prototype.serialize = function (parent) {
  42141. return _super.prototype._serialize.call(this, {
  42142. name: "SetStateAction",
  42143. properties: [
  42144. BABYLON.Action._GetTargetProperty(this._target),
  42145. { name: "value", value: this.value }
  42146. ]
  42147. }, parent);
  42148. };
  42149. return SetStateAction;
  42150. }(BABYLON.Action));
  42151. BABYLON.SetStateAction = SetStateAction;
  42152. var SetValueAction = /** @class */ (function (_super) {
  42153. __extends(SetValueAction, _super);
  42154. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42155. var _this = _super.call(this, triggerOptions, condition) || this;
  42156. _this.propertyPath = propertyPath;
  42157. _this.value = value;
  42158. _this._target = _this._effectiveTarget = target;
  42159. return _this;
  42160. }
  42161. SetValueAction.prototype._prepare = function () {
  42162. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42163. this._property = this._getProperty(this.propertyPath);
  42164. };
  42165. SetValueAction.prototype.execute = function () {
  42166. this._effectiveTarget[this._property] = this.value;
  42167. if (this._target.markAsDirty) {
  42168. this._target.markAsDirty(this._property);
  42169. }
  42170. };
  42171. SetValueAction.prototype.serialize = function (parent) {
  42172. return _super.prototype._serialize.call(this, {
  42173. name: "SetValueAction",
  42174. properties: [
  42175. BABYLON.Action._GetTargetProperty(this._target),
  42176. { name: "propertyPath", value: this.propertyPath },
  42177. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42178. ]
  42179. }, parent);
  42180. };
  42181. return SetValueAction;
  42182. }(BABYLON.Action));
  42183. BABYLON.SetValueAction = SetValueAction;
  42184. var IncrementValueAction = /** @class */ (function (_super) {
  42185. __extends(IncrementValueAction, _super);
  42186. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42187. var _this = _super.call(this, triggerOptions, condition) || this;
  42188. _this.propertyPath = propertyPath;
  42189. _this.value = value;
  42190. _this._target = _this._effectiveTarget = target;
  42191. return _this;
  42192. }
  42193. IncrementValueAction.prototype._prepare = function () {
  42194. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42195. this._property = this._getProperty(this.propertyPath);
  42196. if (typeof this._effectiveTarget[this._property] !== "number") {
  42197. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42198. }
  42199. };
  42200. IncrementValueAction.prototype.execute = function () {
  42201. this._effectiveTarget[this._property] += this.value;
  42202. if (this._target.markAsDirty) {
  42203. this._target.markAsDirty(this._property);
  42204. }
  42205. };
  42206. IncrementValueAction.prototype.serialize = function (parent) {
  42207. return _super.prototype._serialize.call(this, {
  42208. name: "IncrementValueAction",
  42209. properties: [
  42210. BABYLON.Action._GetTargetProperty(this._target),
  42211. { name: "propertyPath", value: this.propertyPath },
  42212. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42213. ]
  42214. }, parent);
  42215. };
  42216. return IncrementValueAction;
  42217. }(BABYLON.Action));
  42218. BABYLON.IncrementValueAction = IncrementValueAction;
  42219. var PlayAnimationAction = /** @class */ (function (_super) {
  42220. __extends(PlayAnimationAction, _super);
  42221. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42222. var _this = _super.call(this, triggerOptions, condition) || this;
  42223. _this.from = from;
  42224. _this.to = to;
  42225. _this.loop = loop;
  42226. _this._target = target;
  42227. return _this;
  42228. }
  42229. PlayAnimationAction.prototype._prepare = function () {
  42230. };
  42231. PlayAnimationAction.prototype.execute = function () {
  42232. var scene = this._actionManager.getScene();
  42233. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42234. };
  42235. PlayAnimationAction.prototype.serialize = function (parent) {
  42236. return _super.prototype._serialize.call(this, {
  42237. name: "PlayAnimationAction",
  42238. properties: [
  42239. BABYLON.Action._GetTargetProperty(this._target),
  42240. { name: "from", value: String(this.from) },
  42241. { name: "to", value: String(this.to) },
  42242. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42243. ]
  42244. }, parent);
  42245. };
  42246. return PlayAnimationAction;
  42247. }(BABYLON.Action));
  42248. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42249. var StopAnimationAction = /** @class */ (function (_super) {
  42250. __extends(StopAnimationAction, _super);
  42251. function StopAnimationAction(triggerOptions, target, condition) {
  42252. var _this = _super.call(this, triggerOptions, condition) || this;
  42253. _this._target = target;
  42254. return _this;
  42255. }
  42256. StopAnimationAction.prototype._prepare = function () {
  42257. };
  42258. StopAnimationAction.prototype.execute = function () {
  42259. var scene = this._actionManager.getScene();
  42260. scene.stopAnimation(this._target);
  42261. };
  42262. StopAnimationAction.prototype.serialize = function (parent) {
  42263. return _super.prototype._serialize.call(this, {
  42264. name: "StopAnimationAction",
  42265. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42266. }, parent);
  42267. };
  42268. return StopAnimationAction;
  42269. }(BABYLON.Action));
  42270. BABYLON.StopAnimationAction = StopAnimationAction;
  42271. var DoNothingAction = /** @class */ (function (_super) {
  42272. __extends(DoNothingAction, _super);
  42273. function DoNothingAction(triggerOptions, condition) {
  42274. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42275. return _super.call(this, triggerOptions, condition) || this;
  42276. }
  42277. DoNothingAction.prototype.execute = function () {
  42278. };
  42279. DoNothingAction.prototype.serialize = function (parent) {
  42280. return _super.prototype._serialize.call(this, {
  42281. name: "DoNothingAction",
  42282. properties: []
  42283. }, parent);
  42284. };
  42285. return DoNothingAction;
  42286. }(BABYLON.Action));
  42287. BABYLON.DoNothingAction = DoNothingAction;
  42288. var CombineAction = /** @class */ (function (_super) {
  42289. __extends(CombineAction, _super);
  42290. function CombineAction(triggerOptions, children, condition) {
  42291. var _this = _super.call(this, triggerOptions, condition) || this;
  42292. _this.children = children;
  42293. return _this;
  42294. }
  42295. CombineAction.prototype._prepare = function () {
  42296. for (var index = 0; index < this.children.length; index++) {
  42297. this.children[index]._actionManager = this._actionManager;
  42298. this.children[index]._prepare();
  42299. }
  42300. };
  42301. CombineAction.prototype.execute = function (evt) {
  42302. for (var index = 0; index < this.children.length; index++) {
  42303. this.children[index].execute(evt);
  42304. }
  42305. };
  42306. CombineAction.prototype.serialize = function (parent) {
  42307. var serializationObject = _super.prototype._serialize.call(this, {
  42308. name: "CombineAction",
  42309. properties: [],
  42310. combine: []
  42311. }, parent);
  42312. for (var i = 0; i < this.children.length; i++) {
  42313. serializationObject.combine.push(this.children[i].serialize(null));
  42314. }
  42315. return serializationObject;
  42316. };
  42317. return CombineAction;
  42318. }(BABYLON.Action));
  42319. BABYLON.CombineAction = CombineAction;
  42320. var ExecuteCodeAction = /** @class */ (function (_super) {
  42321. __extends(ExecuteCodeAction, _super);
  42322. function ExecuteCodeAction(triggerOptions, func, condition) {
  42323. var _this = _super.call(this, triggerOptions, condition) || this;
  42324. _this.func = func;
  42325. return _this;
  42326. }
  42327. ExecuteCodeAction.prototype.execute = function (evt) {
  42328. this.func(evt);
  42329. };
  42330. return ExecuteCodeAction;
  42331. }(BABYLON.Action));
  42332. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42333. var SetParentAction = /** @class */ (function (_super) {
  42334. __extends(SetParentAction, _super);
  42335. function SetParentAction(triggerOptions, target, parent, condition) {
  42336. var _this = _super.call(this, triggerOptions, condition) || this;
  42337. _this._target = target;
  42338. _this._parent = parent;
  42339. return _this;
  42340. }
  42341. SetParentAction.prototype._prepare = function () {
  42342. };
  42343. SetParentAction.prototype.execute = function () {
  42344. if (this._target.parent === this._parent) {
  42345. return;
  42346. }
  42347. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42348. invertParentWorldMatrix.invert();
  42349. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42350. this._target.parent = this._parent;
  42351. };
  42352. SetParentAction.prototype.serialize = function (parent) {
  42353. return _super.prototype._serialize.call(this, {
  42354. name: "SetParentAction",
  42355. properties: [
  42356. BABYLON.Action._GetTargetProperty(this._target),
  42357. BABYLON.Action._GetTargetProperty(this._parent),
  42358. ]
  42359. }, parent);
  42360. };
  42361. return SetParentAction;
  42362. }(BABYLON.Action));
  42363. BABYLON.SetParentAction = SetParentAction;
  42364. var PlaySoundAction = /** @class */ (function (_super) {
  42365. __extends(PlaySoundAction, _super);
  42366. function PlaySoundAction(triggerOptions, sound, condition) {
  42367. var _this = _super.call(this, triggerOptions, condition) || this;
  42368. _this._sound = sound;
  42369. return _this;
  42370. }
  42371. PlaySoundAction.prototype._prepare = function () {
  42372. };
  42373. PlaySoundAction.prototype.execute = function () {
  42374. if (this._sound !== undefined)
  42375. this._sound.play();
  42376. };
  42377. PlaySoundAction.prototype.serialize = function (parent) {
  42378. return _super.prototype._serialize.call(this, {
  42379. name: "PlaySoundAction",
  42380. properties: [{ name: "sound", value: this._sound.name }]
  42381. }, parent);
  42382. };
  42383. return PlaySoundAction;
  42384. }(BABYLON.Action));
  42385. BABYLON.PlaySoundAction = PlaySoundAction;
  42386. var StopSoundAction = /** @class */ (function (_super) {
  42387. __extends(StopSoundAction, _super);
  42388. function StopSoundAction(triggerOptions, sound, condition) {
  42389. var _this = _super.call(this, triggerOptions, condition) || this;
  42390. _this._sound = sound;
  42391. return _this;
  42392. }
  42393. StopSoundAction.prototype._prepare = function () {
  42394. };
  42395. StopSoundAction.prototype.execute = function () {
  42396. if (this._sound !== undefined)
  42397. this._sound.stop();
  42398. };
  42399. StopSoundAction.prototype.serialize = function (parent) {
  42400. return _super.prototype._serialize.call(this, {
  42401. name: "StopSoundAction",
  42402. properties: [{ name: "sound", value: this._sound.name }]
  42403. }, parent);
  42404. };
  42405. return StopSoundAction;
  42406. }(BABYLON.Action));
  42407. BABYLON.StopSoundAction = StopSoundAction;
  42408. })(BABYLON || (BABYLON = {}));
  42409. //# sourceMappingURL=babylon.directActions.js.map
  42410. var BABYLON;
  42411. (function (BABYLON) {
  42412. var SpriteManager = /** @class */ (function () {
  42413. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  42414. if (epsilon === void 0) { epsilon = 0.01; }
  42415. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42416. this.name = name;
  42417. this.sprites = new Array();
  42418. this.renderingGroupId = 0;
  42419. this.layerMask = 0x0FFFFFFF;
  42420. this.fogEnabled = true;
  42421. this.isPickable = false;
  42422. /**
  42423. * An event triggered when the manager is disposed.
  42424. * @type {BABYLON.Observable}
  42425. */
  42426. this.onDisposeObservable = new BABYLON.Observable();
  42427. this._vertexBuffers = {};
  42428. this._capacity = capacity;
  42429. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  42430. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42431. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42432. if (cellSize.width && cellSize.height) {
  42433. this.cellWidth = cellSize.width;
  42434. this.cellHeight = cellSize.height;
  42435. }
  42436. else if (cellSize !== undefined) {
  42437. this.cellWidth = cellSize;
  42438. this.cellHeight = cellSize;
  42439. }
  42440. else {
  42441. return;
  42442. }
  42443. this._epsilon = epsilon;
  42444. this._scene = scene;
  42445. this._scene.spriteManagers.push(this);
  42446. var indices = [];
  42447. var index = 0;
  42448. for (var count = 0; count < capacity; count++) {
  42449. indices.push(index);
  42450. indices.push(index + 1);
  42451. indices.push(index + 2);
  42452. indices.push(index);
  42453. indices.push(index + 2);
  42454. indices.push(index + 3);
  42455. index += 4;
  42456. }
  42457. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  42458. // VBO
  42459. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  42460. this._vertexData = new Float32Array(capacity * 16 * 4);
  42461. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  42462. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  42463. var options = this._buffer.createVertexBuffer("options", 4, 4);
  42464. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  42465. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  42466. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42467. this._vertexBuffers["options"] = options;
  42468. this._vertexBuffers["cellInfo"] = cellInfo;
  42469. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42470. // Effects
  42471. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  42472. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  42473. }
  42474. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  42475. set: function (callback) {
  42476. if (this._onDisposeObserver) {
  42477. this.onDisposeObservable.remove(this._onDisposeObserver);
  42478. }
  42479. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42480. },
  42481. enumerable: true,
  42482. configurable: true
  42483. });
  42484. Object.defineProperty(SpriteManager.prototype, "texture", {
  42485. get: function () {
  42486. return this._spriteTexture;
  42487. },
  42488. set: function (value) {
  42489. this._spriteTexture = value;
  42490. },
  42491. enumerable: true,
  42492. configurable: true
  42493. });
  42494. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  42495. var arrayOffset = index * 16;
  42496. if (offsetX === 0)
  42497. offsetX = this._epsilon;
  42498. else if (offsetX === 1)
  42499. offsetX = 1 - this._epsilon;
  42500. if (offsetY === 0)
  42501. offsetY = this._epsilon;
  42502. else if (offsetY === 1)
  42503. offsetY = 1 - this._epsilon;
  42504. this._vertexData[arrayOffset] = sprite.position.x;
  42505. this._vertexData[arrayOffset + 1] = sprite.position.y;
  42506. this._vertexData[arrayOffset + 2] = sprite.position.z;
  42507. this._vertexData[arrayOffset + 3] = sprite.angle;
  42508. this._vertexData[arrayOffset + 4] = sprite.width;
  42509. this._vertexData[arrayOffset + 5] = sprite.height;
  42510. this._vertexData[arrayOffset + 6] = offsetX;
  42511. this._vertexData[arrayOffset + 7] = offsetY;
  42512. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  42513. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  42514. var offset = (sprite.cellIndex / rowSize) >> 0;
  42515. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  42516. this._vertexData[arrayOffset + 11] = offset;
  42517. // Color
  42518. this._vertexData[arrayOffset + 12] = sprite.color.r;
  42519. this._vertexData[arrayOffset + 13] = sprite.color.g;
  42520. this._vertexData[arrayOffset + 14] = sprite.color.b;
  42521. this._vertexData[arrayOffset + 15] = sprite.color.a;
  42522. };
  42523. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  42524. var count = Math.min(this._capacity, this.sprites.length);
  42525. var min = BABYLON.Vector3.Zero();
  42526. var max = BABYLON.Vector3.Zero();
  42527. var distance = Number.MAX_VALUE;
  42528. var currentSprite = null;
  42529. var cameraSpacePosition = BABYLON.Vector3.Zero();
  42530. var cameraView = camera.getViewMatrix();
  42531. for (var index = 0; index < count; index++) {
  42532. var sprite = this.sprites[index];
  42533. if (!sprite) {
  42534. continue;
  42535. }
  42536. if (predicate) {
  42537. if (!predicate(sprite)) {
  42538. continue;
  42539. }
  42540. }
  42541. else if (!sprite.isPickable) {
  42542. continue;
  42543. }
  42544. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  42545. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  42546. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  42547. if (ray.intersectsBoxMinMax(min, max)) {
  42548. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  42549. if (distance > currentDistance) {
  42550. distance = currentDistance;
  42551. currentSprite = sprite;
  42552. if (fastCheck) {
  42553. break;
  42554. }
  42555. }
  42556. }
  42557. }
  42558. if (currentSprite) {
  42559. var result = new BABYLON.PickingInfo();
  42560. result.hit = true;
  42561. result.pickedSprite = currentSprite;
  42562. result.distance = distance;
  42563. return result;
  42564. }
  42565. return null;
  42566. };
  42567. SpriteManager.prototype.render = function () {
  42568. // Check
  42569. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42570. return;
  42571. var engine = this._scene.getEngine();
  42572. var baseSize = this._spriteTexture.getBaseSize();
  42573. // Sprites
  42574. var deltaTime = engine.getDeltaTime();
  42575. var max = Math.min(this._capacity, this.sprites.length);
  42576. var rowSize = baseSize.width / this.cellWidth;
  42577. var offset = 0;
  42578. for (var index = 0; index < max; index++) {
  42579. var sprite = this.sprites[index];
  42580. if (!sprite) {
  42581. continue;
  42582. }
  42583. sprite._animate(deltaTime);
  42584. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42585. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42586. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42587. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42588. }
  42589. this._buffer.update(this._vertexData);
  42590. // Render
  42591. var effect = this._effectBase;
  42592. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42593. effect = this._effectFog;
  42594. }
  42595. engine.enableEffect(effect);
  42596. var viewMatrix = this._scene.getViewMatrix();
  42597. effect.setTexture("diffuseSampler", this._spriteTexture);
  42598. effect.setMatrix("view", viewMatrix);
  42599. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42600. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42601. // Fog
  42602. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42603. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42604. effect.setColor3("vFogColor", this._scene.fogColor);
  42605. }
  42606. // VBOs
  42607. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42608. // Draw order
  42609. engine.setDepthFunctionToLessOrEqual();
  42610. effect.setBool("alphaTest", true);
  42611. engine.setColorWrite(false);
  42612. engine.draw(true, 0, max * 6);
  42613. engine.setColorWrite(true);
  42614. effect.setBool("alphaTest", false);
  42615. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42616. engine.draw(true, 0, max * 6);
  42617. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42618. };
  42619. SpriteManager.prototype.dispose = function () {
  42620. if (this._buffer) {
  42621. this._buffer.dispose();
  42622. this._buffer = null;
  42623. }
  42624. if (this._indexBuffer) {
  42625. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42626. this._indexBuffer = null;
  42627. }
  42628. if (this._spriteTexture) {
  42629. this._spriteTexture.dispose();
  42630. this._spriteTexture = null;
  42631. }
  42632. // Remove from scene
  42633. var index = this._scene.spriteManagers.indexOf(this);
  42634. this._scene.spriteManagers.splice(index, 1);
  42635. // Callback
  42636. this.onDisposeObservable.notifyObservers(this);
  42637. this.onDisposeObservable.clear();
  42638. };
  42639. return SpriteManager;
  42640. }());
  42641. BABYLON.SpriteManager = SpriteManager;
  42642. })(BABYLON || (BABYLON = {}));
  42643. //# sourceMappingURL=babylon.spriteManager.js.map
  42644. var BABYLON;
  42645. (function (BABYLON) {
  42646. var Sprite = /** @class */ (function () {
  42647. function Sprite(name, manager) {
  42648. this.name = name;
  42649. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42650. this.width = 1.0;
  42651. this.height = 1.0;
  42652. this.angle = 0;
  42653. this.cellIndex = 0;
  42654. this.invertU = 0;
  42655. this.invertV = 0;
  42656. this.animations = new Array();
  42657. this.isPickable = false;
  42658. this._animationStarted = false;
  42659. this._loopAnimation = false;
  42660. this._fromIndex = 0;
  42661. this._toIndex = 0;
  42662. this._delay = 0;
  42663. this._direction = 1;
  42664. this._time = 0;
  42665. this._manager = manager;
  42666. this._manager.sprites.push(this);
  42667. this.position = BABYLON.Vector3.Zero();
  42668. }
  42669. Object.defineProperty(Sprite.prototype, "size", {
  42670. get: function () {
  42671. return this.width;
  42672. },
  42673. set: function (value) {
  42674. this.width = value;
  42675. this.height = value;
  42676. },
  42677. enumerable: true,
  42678. configurable: true
  42679. });
  42680. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  42681. this._fromIndex = from;
  42682. this._toIndex = to;
  42683. this._loopAnimation = loop;
  42684. this._delay = delay;
  42685. this._animationStarted = true;
  42686. this._direction = from < to ? 1 : -1;
  42687. this.cellIndex = from;
  42688. this._time = 0;
  42689. this._onAnimationEnd = onAnimationEnd;
  42690. };
  42691. Sprite.prototype.stopAnimation = function () {
  42692. this._animationStarted = false;
  42693. };
  42694. Sprite.prototype._animate = function (deltaTime) {
  42695. if (!this._animationStarted)
  42696. return;
  42697. this._time += deltaTime;
  42698. if (this._time > this._delay) {
  42699. this._time = this._time % this._delay;
  42700. this.cellIndex += this._direction;
  42701. if (this.cellIndex > this._toIndex) {
  42702. if (this._loopAnimation) {
  42703. this.cellIndex = this._fromIndex;
  42704. }
  42705. else {
  42706. this.cellIndex = this._toIndex;
  42707. this._animationStarted = false;
  42708. if (this._onAnimationEnd) {
  42709. this._onAnimationEnd();
  42710. }
  42711. if (this.disposeWhenFinishedAnimating) {
  42712. this.dispose();
  42713. }
  42714. }
  42715. }
  42716. }
  42717. };
  42718. Sprite.prototype.dispose = function () {
  42719. for (var i = 0; i < this._manager.sprites.length; i++) {
  42720. if (this._manager.sprites[i] == this) {
  42721. this._manager.sprites.splice(i, 1);
  42722. }
  42723. }
  42724. };
  42725. return Sprite;
  42726. }());
  42727. BABYLON.Sprite = Sprite;
  42728. })(BABYLON || (BABYLON = {}));
  42729. //# sourceMappingURL=babylon.sprite.js.map
  42730. var BABYLON;
  42731. (function (BABYLON) {
  42732. var IntersectionInfo = /** @class */ (function () {
  42733. function IntersectionInfo(bu, bv, distance) {
  42734. this.bu = bu;
  42735. this.bv = bv;
  42736. this.distance = distance;
  42737. this.faceId = 0;
  42738. this.subMeshId = 0;
  42739. }
  42740. return IntersectionInfo;
  42741. }());
  42742. BABYLON.IntersectionInfo = IntersectionInfo;
  42743. var PickingInfo = /** @class */ (function () {
  42744. function PickingInfo() {
  42745. this.hit = false;
  42746. this.distance = 0;
  42747. this.pickedPoint = null;
  42748. this.pickedMesh = null;
  42749. this.bu = 0;
  42750. this.bv = 0;
  42751. this.faceId = -1;
  42752. this.subMeshId = 0;
  42753. this.pickedSprite = null;
  42754. }
  42755. // Methods
  42756. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  42757. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  42758. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  42759. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42760. return null;
  42761. }
  42762. var indices = this.pickedMesh.getIndices();
  42763. if (!indices) {
  42764. return null;
  42765. }
  42766. var result;
  42767. if (useVerticesNormals) {
  42768. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42769. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  42770. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  42771. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  42772. normal0 = normal0.scale(this.bu);
  42773. normal1 = normal1.scale(this.bv);
  42774. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  42775. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  42776. }
  42777. else {
  42778. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42779. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  42780. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  42781. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  42782. var p1p2 = vertex1.subtract(vertex2);
  42783. var p3p2 = vertex3.subtract(vertex2);
  42784. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  42785. }
  42786. if (useWorldCoordinates) {
  42787. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  42788. }
  42789. return BABYLON.Vector3.Normalize(result);
  42790. };
  42791. PickingInfo.prototype.getTextureCoordinates = function () {
  42792. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42793. return null;
  42794. }
  42795. var indices = this.pickedMesh.getIndices();
  42796. if (!indices) {
  42797. return null;
  42798. }
  42799. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42800. if (!uvs) {
  42801. return null;
  42802. }
  42803. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  42804. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  42805. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  42806. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  42807. uv1 = uv1.scale(this.bu);
  42808. uv2 = uv2.scale(this.bv);
  42809. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  42810. };
  42811. return PickingInfo;
  42812. }());
  42813. BABYLON.PickingInfo = PickingInfo;
  42814. })(BABYLON || (BABYLON = {}));
  42815. //# sourceMappingURL=babylon.pickingInfo.js.map
  42816. var BABYLON;
  42817. (function (BABYLON) {
  42818. var Ray = /** @class */ (function () {
  42819. function Ray(origin, direction, length) {
  42820. if (length === void 0) { length = Number.MAX_VALUE; }
  42821. this.origin = origin;
  42822. this.direction = direction;
  42823. this.length = length;
  42824. }
  42825. // Methods
  42826. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  42827. var d = 0.0;
  42828. var maxValue = Number.MAX_VALUE;
  42829. var inv;
  42830. var min;
  42831. var max;
  42832. var temp;
  42833. if (Math.abs(this.direction.x) < 0.0000001) {
  42834. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  42835. return false;
  42836. }
  42837. }
  42838. else {
  42839. inv = 1.0 / this.direction.x;
  42840. min = (minimum.x - this.origin.x) * inv;
  42841. max = (maximum.x - this.origin.x) * inv;
  42842. if (max === -Infinity) {
  42843. max = Infinity;
  42844. }
  42845. if (min > max) {
  42846. temp = min;
  42847. min = max;
  42848. max = temp;
  42849. }
  42850. d = Math.max(min, d);
  42851. maxValue = Math.min(max, maxValue);
  42852. if (d > maxValue) {
  42853. return false;
  42854. }
  42855. }
  42856. if (Math.abs(this.direction.y) < 0.0000001) {
  42857. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  42858. return false;
  42859. }
  42860. }
  42861. else {
  42862. inv = 1.0 / this.direction.y;
  42863. min = (minimum.y - this.origin.y) * inv;
  42864. max = (maximum.y - this.origin.y) * inv;
  42865. if (max === -Infinity) {
  42866. max = Infinity;
  42867. }
  42868. if (min > max) {
  42869. temp = min;
  42870. min = max;
  42871. max = temp;
  42872. }
  42873. d = Math.max(min, d);
  42874. maxValue = Math.min(max, maxValue);
  42875. if (d > maxValue) {
  42876. return false;
  42877. }
  42878. }
  42879. if (Math.abs(this.direction.z) < 0.0000001) {
  42880. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  42881. return false;
  42882. }
  42883. }
  42884. else {
  42885. inv = 1.0 / this.direction.z;
  42886. min = (minimum.z - this.origin.z) * inv;
  42887. max = (maximum.z - this.origin.z) * inv;
  42888. if (max === -Infinity) {
  42889. max = Infinity;
  42890. }
  42891. if (min > max) {
  42892. temp = min;
  42893. min = max;
  42894. max = temp;
  42895. }
  42896. d = Math.max(min, d);
  42897. maxValue = Math.min(max, maxValue);
  42898. if (d > maxValue) {
  42899. return false;
  42900. }
  42901. }
  42902. return true;
  42903. };
  42904. Ray.prototype.intersectsBox = function (box) {
  42905. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  42906. };
  42907. Ray.prototype.intersectsSphere = function (sphere) {
  42908. var x = sphere.center.x - this.origin.x;
  42909. var y = sphere.center.y - this.origin.y;
  42910. var z = sphere.center.z - this.origin.z;
  42911. var pyth = (x * x) + (y * y) + (z * z);
  42912. var rr = sphere.radius * sphere.radius;
  42913. if (pyth <= rr) {
  42914. return true;
  42915. }
  42916. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  42917. if (dot < 0.0) {
  42918. return false;
  42919. }
  42920. var temp = pyth - (dot * dot);
  42921. return temp <= rr;
  42922. };
  42923. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  42924. if (!this._edge1) {
  42925. this._edge1 = BABYLON.Vector3.Zero();
  42926. this._edge2 = BABYLON.Vector3.Zero();
  42927. this._pvec = BABYLON.Vector3.Zero();
  42928. this._tvec = BABYLON.Vector3.Zero();
  42929. this._qvec = BABYLON.Vector3.Zero();
  42930. }
  42931. vertex1.subtractToRef(vertex0, this._edge1);
  42932. vertex2.subtractToRef(vertex0, this._edge2);
  42933. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  42934. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  42935. if (det === 0) {
  42936. return null;
  42937. }
  42938. var invdet = 1 / det;
  42939. this.origin.subtractToRef(vertex0, this._tvec);
  42940. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  42941. if (bu < 0 || bu > 1.0) {
  42942. return null;
  42943. }
  42944. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  42945. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  42946. if (bv < 0 || bu + bv > 1.0) {
  42947. return null;
  42948. }
  42949. //check if the distance is longer than the predefined length.
  42950. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  42951. if (distance > this.length) {
  42952. return null;
  42953. }
  42954. return new BABYLON.IntersectionInfo(bu, bv, distance);
  42955. };
  42956. Ray.prototype.intersectsPlane = function (plane) {
  42957. var distance;
  42958. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  42959. if (Math.abs(result1) < 9.99999997475243E-07) {
  42960. return null;
  42961. }
  42962. else {
  42963. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  42964. distance = (-plane.d - result2) / result1;
  42965. if (distance < 0.0) {
  42966. if (distance < -9.99999997475243E-07) {
  42967. return null;
  42968. }
  42969. else {
  42970. return 0;
  42971. }
  42972. }
  42973. return distance;
  42974. }
  42975. };
  42976. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  42977. var tm = BABYLON.Tmp.Matrix[0];
  42978. mesh.getWorldMatrix().invertToRef(tm);
  42979. if (this._tmpRay) {
  42980. Ray.TransformToRef(this, tm, this._tmpRay);
  42981. }
  42982. else {
  42983. this._tmpRay = Ray.Transform(this, tm);
  42984. }
  42985. return mesh.intersects(this._tmpRay, fastCheck);
  42986. };
  42987. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  42988. if (results) {
  42989. results.length = 0;
  42990. }
  42991. else {
  42992. results = [];
  42993. }
  42994. for (var i = 0; i < meshes.length; i++) {
  42995. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  42996. if (pickInfo.hit) {
  42997. results.push(pickInfo);
  42998. }
  42999. }
  43000. results.sort(this._comparePickingInfo);
  43001. return results;
  43002. };
  43003. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43004. if (pickingInfoA.distance < pickingInfoB.distance) {
  43005. return -1;
  43006. }
  43007. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43008. return 1;
  43009. }
  43010. else {
  43011. return 0;
  43012. }
  43013. };
  43014. /**
  43015. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43016. * @param sega the first point of the segment to test the intersection against
  43017. * @param segb the second point of the segment to test the intersection against
  43018. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43019. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43020. */
  43021. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43022. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43023. var u = segb.subtract(sega);
  43024. var v = rsegb.subtract(this.origin);
  43025. var w = sega.subtract(this.origin);
  43026. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43027. var b = BABYLON.Vector3.Dot(u, v);
  43028. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43029. var d = BABYLON.Vector3.Dot(u, w);
  43030. var e = BABYLON.Vector3.Dot(v, w);
  43031. var D = a * c - b * b; // always >= 0
  43032. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43033. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43034. // compute the line parameters of the two closest points
  43035. if (D < Ray.smallnum) {
  43036. sN = 0.0; // force using point P0 on segment S1
  43037. sD = 1.0; // to prevent possible division by 0.0 later
  43038. tN = e;
  43039. tD = c;
  43040. }
  43041. else {
  43042. sN = (b * e - c * d);
  43043. tN = (a * e - b * d);
  43044. if (sN < 0.0) {
  43045. sN = 0.0;
  43046. tN = e;
  43047. tD = c;
  43048. }
  43049. else if (sN > sD) {
  43050. sN = sD;
  43051. tN = e + b;
  43052. tD = c;
  43053. }
  43054. }
  43055. if (tN < 0.0) {
  43056. tN = 0.0;
  43057. // recompute sc for this edge
  43058. if (-d < 0.0) {
  43059. sN = 0.0;
  43060. }
  43061. else if (-d > a)
  43062. sN = sD;
  43063. else {
  43064. sN = -d;
  43065. sD = a;
  43066. }
  43067. }
  43068. else if (tN > tD) {
  43069. tN = tD;
  43070. // recompute sc for this edge
  43071. if ((-d + b) < 0.0) {
  43072. sN = 0;
  43073. }
  43074. else if ((-d + b) > a) {
  43075. sN = sD;
  43076. }
  43077. else {
  43078. sN = (-d + b);
  43079. sD = a;
  43080. }
  43081. }
  43082. // finally do the division to get sc and tc
  43083. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43084. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43085. // get the difference of the two closest points
  43086. var qtc = v.multiplyByFloats(tc, tc, tc);
  43087. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43088. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43089. if (isIntersected) {
  43090. return qtc.length();
  43091. }
  43092. return -1;
  43093. };
  43094. // Statics
  43095. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43096. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  43097. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  43098. var direction = end.subtract(start);
  43099. direction.normalize();
  43100. return new Ray(start, direction);
  43101. };
  43102. /**
  43103. * 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
  43104. * transformed to the given world matrix.
  43105. * @param origin The origin point
  43106. * @param end The end point
  43107. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43108. */
  43109. Ray.CreateNewFromTo = function (origin, end, world) {
  43110. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43111. var direction = end.subtract(origin);
  43112. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43113. direction.normalize();
  43114. return Ray.Transform(new Ray(origin, direction, length), world);
  43115. };
  43116. Ray.Transform = function (ray, matrix) {
  43117. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43118. Ray.TransformToRef(ray, matrix, result);
  43119. return result;
  43120. };
  43121. Ray.TransformToRef = function (ray, matrix, result) {
  43122. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43123. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43124. result.length = ray.length;
  43125. var dir = result.direction;
  43126. var len = dir.length();
  43127. if (!(len === 0 || len === 1)) {
  43128. var num = 1.0 / len;
  43129. dir.x *= num;
  43130. dir.y *= num;
  43131. dir.z *= num;
  43132. result.length *= len;
  43133. }
  43134. };
  43135. Ray.smallnum = 0.00000001;
  43136. Ray.rayl = 10e8;
  43137. return Ray;
  43138. }());
  43139. BABYLON.Ray = Ray;
  43140. })(BABYLON || (BABYLON = {}));
  43141. //# sourceMappingURL=babylon.ray.js.map
  43142. var BABYLON;
  43143. (function (BABYLON) {
  43144. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43145. if (boxMin.x > sphereCenter.x + sphereRadius)
  43146. return false;
  43147. if (sphereCenter.x - sphereRadius > boxMax.x)
  43148. return false;
  43149. if (boxMin.y > sphereCenter.y + sphereRadius)
  43150. return false;
  43151. if (sphereCenter.y - sphereRadius > boxMax.y)
  43152. return false;
  43153. if (boxMin.z > sphereCenter.z + sphereRadius)
  43154. return false;
  43155. if (sphereCenter.z - sphereRadius > boxMax.z)
  43156. return false;
  43157. return true;
  43158. };
  43159. var getLowestRoot = (function () {
  43160. var result = { root: 0, found: false };
  43161. return function (a, b, c, maxR) {
  43162. result.root = 0;
  43163. result.found = false;
  43164. var determinant = b * b - 4.0 * a * c;
  43165. if (determinant < 0)
  43166. return result;
  43167. var sqrtD = Math.sqrt(determinant);
  43168. var r1 = (-b - sqrtD) / (2.0 * a);
  43169. var r2 = (-b + sqrtD) / (2.0 * a);
  43170. if (r1 > r2) {
  43171. var temp = r2;
  43172. r2 = r1;
  43173. r1 = temp;
  43174. }
  43175. if (r1 > 0 && r1 < maxR) {
  43176. result.root = r1;
  43177. result.found = true;
  43178. return result;
  43179. }
  43180. if (r2 > 0 && r2 < maxR) {
  43181. result.root = r2;
  43182. result.found = true;
  43183. return result;
  43184. }
  43185. return result;
  43186. };
  43187. })();
  43188. var Collider = /** @class */ (function () {
  43189. function Collider() {
  43190. this.radius = BABYLON.Vector3.One();
  43191. this.retry = 0;
  43192. this.basePointWorld = BABYLON.Vector3.Zero();
  43193. this.velocityWorld = BABYLON.Vector3.Zero();
  43194. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43195. this._collisionPoint = BABYLON.Vector3.Zero();
  43196. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43197. this._tempVector = BABYLON.Vector3.Zero();
  43198. this._tempVector2 = BABYLON.Vector3.Zero();
  43199. this._tempVector3 = BABYLON.Vector3.Zero();
  43200. this._tempVector4 = BABYLON.Vector3.Zero();
  43201. this._edge = BABYLON.Vector3.Zero();
  43202. this._baseToVertex = BABYLON.Vector3.Zero();
  43203. this._destinationPoint = BABYLON.Vector3.Zero();
  43204. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43205. this._displacementVector = BABYLON.Vector3.Zero();
  43206. this._collisionMask = -1;
  43207. }
  43208. Object.defineProperty(Collider.prototype, "collisionMask", {
  43209. get: function () {
  43210. return this._collisionMask;
  43211. },
  43212. set: function (mask) {
  43213. this._collisionMask = !isNaN(mask) ? mask : -1;
  43214. },
  43215. enumerable: true,
  43216. configurable: true
  43217. });
  43218. // Methods
  43219. Collider.prototype._initialize = function (source, dir, e) {
  43220. this.velocity = dir;
  43221. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43222. this.basePoint = source;
  43223. source.multiplyToRef(this.radius, this.basePointWorld);
  43224. dir.multiplyToRef(this.radius, this.velocityWorld);
  43225. this.velocityWorldLength = this.velocityWorld.length();
  43226. this.epsilon = e;
  43227. this.collisionFound = false;
  43228. };
  43229. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43230. pa.subtractToRef(point, this._tempVector);
  43231. pb.subtractToRef(point, this._tempVector2);
  43232. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43233. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43234. if (d < 0)
  43235. return false;
  43236. pc.subtractToRef(point, this._tempVector3);
  43237. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43238. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43239. if (d < 0)
  43240. return false;
  43241. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43242. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43243. return d >= 0;
  43244. };
  43245. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43246. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43247. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43248. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43249. return false;
  43250. }
  43251. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43252. return false;
  43253. return true;
  43254. };
  43255. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43256. var t0;
  43257. var embeddedInPlane = false;
  43258. //defensive programming, actually not needed.
  43259. if (!trianglePlaneArray) {
  43260. trianglePlaneArray = [];
  43261. }
  43262. if (!trianglePlaneArray[faceIndex]) {
  43263. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43264. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43265. }
  43266. var trianglePlane = trianglePlaneArray[faceIndex];
  43267. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43268. return;
  43269. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43270. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43271. if (normalDotVelocity == 0) {
  43272. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43273. return;
  43274. embeddedInPlane = true;
  43275. t0 = 0;
  43276. }
  43277. else {
  43278. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43279. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43280. if (t0 > t1) {
  43281. var temp = t1;
  43282. t1 = t0;
  43283. t0 = temp;
  43284. }
  43285. if (t0 > 1.0 || t1 < 0.0)
  43286. return;
  43287. if (t0 < 0)
  43288. t0 = 0;
  43289. if (t0 > 1.0)
  43290. t0 = 1.0;
  43291. }
  43292. this._collisionPoint.copyFromFloats(0, 0, 0);
  43293. var found = false;
  43294. var t = 1.0;
  43295. if (!embeddedInPlane) {
  43296. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43297. this.velocity.scaleToRef(t0, this._tempVector);
  43298. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43299. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43300. found = true;
  43301. t = t0;
  43302. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43303. }
  43304. }
  43305. if (!found) {
  43306. var velocitySquaredLength = this.velocity.lengthSquared();
  43307. var a = velocitySquaredLength;
  43308. this.basePoint.subtractToRef(p1, this._tempVector);
  43309. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43310. var c = this._tempVector.lengthSquared() - 1.0;
  43311. var lowestRoot = getLowestRoot(a, b, c, t);
  43312. if (lowestRoot.found) {
  43313. t = lowestRoot.root;
  43314. found = true;
  43315. this._collisionPoint.copyFrom(p1);
  43316. }
  43317. this.basePoint.subtractToRef(p2, this._tempVector);
  43318. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43319. c = this._tempVector.lengthSquared() - 1.0;
  43320. lowestRoot = getLowestRoot(a, b, c, t);
  43321. if (lowestRoot.found) {
  43322. t = lowestRoot.root;
  43323. found = true;
  43324. this._collisionPoint.copyFrom(p2);
  43325. }
  43326. this.basePoint.subtractToRef(p3, this._tempVector);
  43327. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43328. c = this._tempVector.lengthSquared() - 1.0;
  43329. lowestRoot = getLowestRoot(a, b, c, t);
  43330. if (lowestRoot.found) {
  43331. t = lowestRoot.root;
  43332. found = true;
  43333. this._collisionPoint.copyFrom(p3);
  43334. }
  43335. p2.subtractToRef(p1, this._edge);
  43336. p1.subtractToRef(this.basePoint, this._baseToVertex);
  43337. var edgeSquaredLength = this._edge.lengthSquared();
  43338. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43339. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43340. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43341. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43342. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43343. lowestRoot = getLowestRoot(a, b, c, t);
  43344. if (lowestRoot.found) {
  43345. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43346. if (f >= 0.0 && f <= 1.0) {
  43347. t = lowestRoot.root;
  43348. found = true;
  43349. this._edge.scaleInPlace(f);
  43350. p1.addToRef(this._edge, this._collisionPoint);
  43351. }
  43352. }
  43353. p3.subtractToRef(p2, this._edge);
  43354. p2.subtractToRef(this.basePoint, this._baseToVertex);
  43355. edgeSquaredLength = this._edge.lengthSquared();
  43356. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43357. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43358. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43359. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43360. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43361. lowestRoot = getLowestRoot(a, b, c, t);
  43362. if (lowestRoot.found) {
  43363. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43364. if (f >= 0.0 && f <= 1.0) {
  43365. t = lowestRoot.root;
  43366. found = true;
  43367. this._edge.scaleInPlace(f);
  43368. p2.addToRef(this._edge, this._collisionPoint);
  43369. }
  43370. }
  43371. p1.subtractToRef(p3, this._edge);
  43372. p3.subtractToRef(this.basePoint, this._baseToVertex);
  43373. edgeSquaredLength = this._edge.lengthSquared();
  43374. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43375. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43376. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43377. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43378. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43379. lowestRoot = getLowestRoot(a, b, c, t);
  43380. if (lowestRoot.found) {
  43381. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43382. if (f >= 0.0 && f <= 1.0) {
  43383. t = lowestRoot.root;
  43384. found = true;
  43385. this._edge.scaleInPlace(f);
  43386. p3.addToRef(this._edge, this._collisionPoint);
  43387. }
  43388. }
  43389. }
  43390. if (found) {
  43391. var distToCollision = t * this.velocity.length();
  43392. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  43393. if (!this.intersectionPoint) {
  43394. this.intersectionPoint = this._collisionPoint.clone();
  43395. }
  43396. else {
  43397. this.intersectionPoint.copyFrom(this._collisionPoint);
  43398. }
  43399. this.nearestDistance = distToCollision;
  43400. this.collisionFound = true;
  43401. }
  43402. }
  43403. };
  43404. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  43405. for (var i = indexStart; i < indexEnd; i += 3) {
  43406. var p1 = pts[indices[i] - decal];
  43407. var p2 = pts[indices[i + 1] - decal];
  43408. var p3 = pts[indices[i + 2] - decal];
  43409. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  43410. }
  43411. };
  43412. Collider.prototype._getResponse = function (pos, vel) {
  43413. pos.addToRef(vel, this._destinationPoint);
  43414. vel.scaleInPlace((this.nearestDistance / vel.length()));
  43415. this.basePoint.addToRef(vel, pos);
  43416. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  43417. this._slidePlaneNormal.normalize();
  43418. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  43419. pos.addInPlace(this._displacementVector);
  43420. this.intersectionPoint.addInPlace(this._displacementVector);
  43421. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  43422. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  43423. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  43424. };
  43425. return Collider;
  43426. }());
  43427. BABYLON.Collider = Collider;
  43428. })(BABYLON || (BABYLON = {}));
  43429. //# sourceMappingURL=babylon.collider.js.map
  43430. var BABYLON;
  43431. (function (BABYLON) {
  43432. //WebWorker code will be inserted to this variable.
  43433. BABYLON.CollisionWorker = "";
  43434. var WorkerTaskType;
  43435. (function (WorkerTaskType) {
  43436. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  43437. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  43438. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  43439. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  43440. var WorkerReplyType;
  43441. (function (WorkerReplyType) {
  43442. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  43443. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  43444. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  43445. var CollisionCoordinatorWorker = /** @class */ (function () {
  43446. function CollisionCoordinatorWorker() {
  43447. var _this = this;
  43448. this._scaledPosition = BABYLON.Vector3.Zero();
  43449. this._scaledVelocity = BABYLON.Vector3.Zero();
  43450. this.onMeshUpdated = function (mesh) {
  43451. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  43452. };
  43453. this.onGeometryUpdated = function (geometry) {
  43454. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  43455. };
  43456. this._afterRender = function () {
  43457. if (!_this._init)
  43458. return;
  43459. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  43460. return;
  43461. }
  43462. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  43463. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  43464. if (_this._runningUpdated > 4) {
  43465. return;
  43466. }
  43467. ++_this._runningUpdated;
  43468. var payload = {
  43469. updatedMeshes: _this._addUpdateMeshesList,
  43470. updatedGeometries: _this._addUpdateGeometriesList,
  43471. removedGeometries: _this._toRemoveGeometryArray,
  43472. removedMeshes: _this._toRemoveMeshesArray
  43473. };
  43474. var message = {
  43475. payload: payload,
  43476. taskType: WorkerTaskType.UPDATE
  43477. };
  43478. var serializable = [];
  43479. for (var id in payload.updatedGeometries) {
  43480. if (payload.updatedGeometries.hasOwnProperty(id)) {
  43481. //prepare transferables
  43482. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  43483. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  43484. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  43485. }
  43486. }
  43487. _this._worker.postMessage(message, serializable);
  43488. _this._addUpdateMeshesList = {};
  43489. _this._addUpdateGeometriesList = {};
  43490. _this._toRemoveGeometryArray = [];
  43491. _this._toRemoveMeshesArray = [];
  43492. };
  43493. this._onMessageFromWorker = function (e) {
  43494. var returnData = e.data;
  43495. if (returnData.error != WorkerReplyType.SUCCESS) {
  43496. //TODO what errors can be returned from the worker?
  43497. BABYLON.Tools.Warn("error returned from worker!");
  43498. return;
  43499. }
  43500. switch (returnData.taskType) {
  43501. case WorkerTaskType.INIT:
  43502. _this._init = true;
  43503. //Update the worked with ALL of the scene's current state
  43504. _this._scene.meshes.forEach(function (mesh) {
  43505. _this.onMeshAdded(mesh);
  43506. });
  43507. _this._scene.getGeometries().forEach(function (geometry) {
  43508. _this.onGeometryAdded(geometry);
  43509. });
  43510. break;
  43511. case WorkerTaskType.UPDATE:
  43512. _this._runningUpdated--;
  43513. break;
  43514. case WorkerTaskType.COLLIDE:
  43515. _this._runningCollisionTask = false;
  43516. var returnPayload = returnData.payload;
  43517. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  43518. return;
  43519. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  43520. if (callback) {
  43521. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  43522. if (mesh) {
  43523. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  43524. }
  43525. }
  43526. //cleanup
  43527. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  43528. break;
  43529. }
  43530. };
  43531. this._collisionsCallbackArray = [];
  43532. this._init = false;
  43533. this._runningUpdated = 0;
  43534. this._runningCollisionTask = false;
  43535. this._addUpdateMeshesList = {};
  43536. this._addUpdateGeometriesList = {};
  43537. this._toRemoveGeometryArray = [];
  43538. this._toRemoveMeshesArray = [];
  43539. }
  43540. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43541. if (!this._init)
  43542. return;
  43543. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  43544. return;
  43545. position.divideToRef(collider.radius, this._scaledPosition);
  43546. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43547. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  43548. var payload = {
  43549. collider: {
  43550. position: this._scaledPosition.asArray(),
  43551. velocity: this._scaledVelocity.asArray(),
  43552. radius: collider.radius.asArray()
  43553. },
  43554. collisionId: collisionIndex,
  43555. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43556. maximumRetry: maximumRetry
  43557. };
  43558. var message = {
  43559. payload: payload,
  43560. taskType: WorkerTaskType.COLLIDE
  43561. };
  43562. this._worker.postMessage(message);
  43563. };
  43564. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43565. this._scene = scene;
  43566. this._scene.registerAfterRender(this._afterRender);
  43567. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43568. this._worker = new Worker(workerUrl);
  43569. this._worker.onmessage = this._onMessageFromWorker;
  43570. var message = {
  43571. payload: {},
  43572. taskType: WorkerTaskType.INIT
  43573. };
  43574. this._worker.postMessage(message);
  43575. };
  43576. CollisionCoordinatorWorker.prototype.destroy = function () {
  43577. this._scene.unregisterAfterRender(this._afterRender);
  43578. this._worker.terminate();
  43579. };
  43580. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43581. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43582. this.onMeshUpdated(mesh);
  43583. };
  43584. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43585. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43586. };
  43587. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43588. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43589. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43590. this.onGeometryUpdated(geometry);
  43591. };
  43592. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43593. this._toRemoveGeometryArray.push(geometry.id);
  43594. };
  43595. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43596. var submeshes = [];
  43597. if (mesh.subMeshes) {
  43598. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43599. var boundingInfo = sm.getBoundingInfo();
  43600. return {
  43601. position: idx,
  43602. verticesStart: sm.verticesStart,
  43603. verticesCount: sm.verticesCount,
  43604. indexStart: sm.indexStart,
  43605. indexCount: sm.indexCount,
  43606. hasMaterial: !!sm.getMaterial(),
  43607. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43608. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43609. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43610. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  43611. };
  43612. });
  43613. }
  43614. var geometryId = null;
  43615. if (mesh instanceof BABYLON.Mesh) {
  43616. var geometry = mesh.geometry;
  43617. geometryId = geometry ? geometry.id : null;
  43618. }
  43619. else if (mesh instanceof BABYLON.InstancedMesh) {
  43620. var geometry = mesh.sourceMesh.geometry;
  43621. geometryId = geometry ? geometry.id : null;
  43622. }
  43623. var boundingInfo = mesh.getBoundingInfo();
  43624. return {
  43625. uniqueId: mesh.uniqueId,
  43626. id: mesh.id,
  43627. name: mesh.name,
  43628. geometryId: geometryId,
  43629. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43630. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43631. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43632. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  43633. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43634. subMeshes: submeshes,
  43635. checkCollisions: mesh.checkCollisions
  43636. };
  43637. };
  43638. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43639. return {
  43640. id: geometry.id,
  43641. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43642. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43643. indices: new Uint32Array(geometry.getIndices() || []),
  43644. };
  43645. };
  43646. return CollisionCoordinatorWorker;
  43647. }());
  43648. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43649. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43650. function CollisionCoordinatorLegacy() {
  43651. this._scaledPosition = BABYLON.Vector3.Zero();
  43652. this._scaledVelocity = BABYLON.Vector3.Zero();
  43653. this._finalPosition = BABYLON.Vector3.Zero();
  43654. }
  43655. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43656. position.divideToRef(collider.radius, this._scaledPosition);
  43657. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43658. collider.collidedMesh = null;
  43659. collider.retry = 0;
  43660. collider.initialVelocity = this._scaledVelocity;
  43661. collider.initialPosition = this._scaledPosition;
  43662. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  43663. this._finalPosition.multiplyInPlace(collider.radius);
  43664. //run the callback
  43665. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  43666. };
  43667. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  43668. this._scene = scene;
  43669. };
  43670. CollisionCoordinatorLegacy.prototype.destroy = function () {
  43671. //Legacy need no destruction method.
  43672. };
  43673. //No update in legacy mode
  43674. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  43675. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  43676. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  43677. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  43678. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  43679. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  43680. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  43681. if (excludedMesh === void 0) { excludedMesh = null; }
  43682. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  43683. if (collider.retry >= maximumRetry) {
  43684. finalPosition.copyFrom(position);
  43685. return;
  43686. }
  43687. // Check if this is a mesh else camera or -1
  43688. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  43689. collider._initialize(position, velocity, closeDistance);
  43690. // Check all meshes
  43691. for (var index = 0; index < this._scene.meshes.length; index++) {
  43692. var mesh = this._scene.meshes[index];
  43693. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  43694. mesh._checkCollision(collider);
  43695. }
  43696. }
  43697. if (!collider.collisionFound) {
  43698. position.addToRef(velocity, finalPosition);
  43699. return;
  43700. }
  43701. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  43702. collider._getResponse(position, velocity);
  43703. }
  43704. if (velocity.length() <= closeDistance) {
  43705. finalPosition.copyFrom(position);
  43706. return;
  43707. }
  43708. collider.retry++;
  43709. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  43710. };
  43711. return CollisionCoordinatorLegacy;
  43712. }());
  43713. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  43714. })(BABYLON || (BABYLON = {}));
  43715. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  43716. var BABYLON;
  43717. (function (BABYLON) {
  43718. var Particle = /** @class */ (function () {
  43719. function Particle(particleSystem) {
  43720. this.particleSystem = particleSystem;
  43721. this.position = BABYLON.Vector3.Zero();
  43722. this.direction = BABYLON.Vector3.Zero();
  43723. this.color = new BABYLON.Color4(0, 0, 0, 0);
  43724. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  43725. this.lifeTime = 1.0;
  43726. this.age = 0;
  43727. this.size = 0;
  43728. this.angle = 0;
  43729. this.angularSpeed = 0;
  43730. this._currentFrameCounter = 0;
  43731. this.cellIndex = 0;
  43732. if (!this.particleSystem.isAnimationSheetEnabled) {
  43733. return;
  43734. }
  43735. this.cellIndex = this.particleSystem.startSpriteCellID;
  43736. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  43737. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  43738. }
  43739. else {
  43740. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  43741. }
  43742. }
  43743. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  43744. // (ageOffset / scaledUpdateSpeed) / available cells
  43745. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  43746. this._currentFrameCounter += scaledUpdateSpeed;
  43747. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  43748. this._currentFrameCounter = 0;
  43749. this.cellIndex++;
  43750. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43751. this.cellIndex = this.particleSystem.endSpriteCellID;
  43752. }
  43753. }
  43754. };
  43755. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  43756. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  43757. this.cellIndex++;
  43758. this._currentFrameCounter = 0;
  43759. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43760. if (this.particleSystem.spriteCellLoop) {
  43761. this.cellIndex = this.particleSystem.startSpriteCellID;
  43762. }
  43763. else {
  43764. this.cellIndex = this.particleSystem.endSpriteCellID;
  43765. }
  43766. }
  43767. }
  43768. else {
  43769. this._currentFrameCounter++;
  43770. }
  43771. };
  43772. Particle.prototype.copyTo = function (other) {
  43773. other.position.copyFrom(this.position);
  43774. other.direction.copyFrom(this.direction);
  43775. other.color.copyFrom(this.color);
  43776. other.colorStep.copyFrom(this.colorStep);
  43777. other.lifeTime = this.lifeTime;
  43778. other.age = this.age;
  43779. other.size = this.size;
  43780. other.angle = this.angle;
  43781. other.angularSpeed = this.angularSpeed;
  43782. other.particleSystem = this.particleSystem;
  43783. other.cellIndex = this.cellIndex;
  43784. };
  43785. return Particle;
  43786. }());
  43787. BABYLON.Particle = Particle;
  43788. })(BABYLON || (BABYLON = {}));
  43789. //# sourceMappingURL=babylon.particle.js.map
  43790. var BABYLON;
  43791. (function (BABYLON) {
  43792. var randomNumber = function (min, max) {
  43793. if (min === max) {
  43794. return (min);
  43795. }
  43796. var random = Math.random();
  43797. return ((random * (max - min)) + min);
  43798. };
  43799. var ParticleSystem = /** @class */ (function () {
  43800. // end of sheet animation
  43801. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  43802. if (customEffect === void 0) { customEffect = null; }
  43803. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  43804. if (epsilon === void 0) { epsilon = 0.01; }
  43805. var _this = this;
  43806. this.name = name;
  43807. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  43808. // Members
  43809. this.animations = [];
  43810. this.renderingGroupId = 0;
  43811. this.emitter = null;
  43812. this.emitRate = 10;
  43813. this.manualEmitCount = -1;
  43814. this.updateSpeed = 0.01;
  43815. this.targetStopDuration = 0;
  43816. this.disposeOnStop = false;
  43817. this.minEmitPower = 1;
  43818. this.maxEmitPower = 1;
  43819. this.minLifeTime = 1;
  43820. this.maxLifeTime = 1;
  43821. this.minSize = 1;
  43822. this.maxSize = 1;
  43823. this.minAngularSpeed = 0;
  43824. this.maxAngularSpeed = 0;
  43825. this.layerMask = 0x0FFFFFFF;
  43826. this.customShader = null;
  43827. this.preventAutoStart = false;
  43828. /**
  43829. * An event triggered when the system is disposed.
  43830. * @type {BABYLON.Observable}
  43831. */
  43832. this.onDisposeObservable = new BABYLON.Observable();
  43833. this.onAnimationEnd = null;
  43834. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  43835. this.forceDepthWrite = false;
  43836. this.gravity = BABYLON.Vector3.Zero();
  43837. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  43838. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  43839. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  43840. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43841. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43842. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43843. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  43844. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43845. this.particles = new Array();
  43846. this._stockParticles = new Array();
  43847. this._newPartsExcess = 0;
  43848. this._vertexBuffers = {};
  43849. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  43850. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  43851. this._scaledDirection = BABYLON.Vector3.Zero();
  43852. this._scaledGravity = BABYLON.Vector3.Zero();
  43853. this._currentRenderId = -1;
  43854. this._started = false;
  43855. this._stopped = false;
  43856. this._actualFrame = 0;
  43857. // sheet animation
  43858. this.startSpriteCellID = 0;
  43859. this.endSpriteCellID = 0;
  43860. this.spriteCellLoop = true;
  43861. this.spriteCellChangeSpeed = 0;
  43862. this.spriteCellWidth = 0;
  43863. this.spriteCellHeight = 0;
  43864. this._vertexBufferSize = 11;
  43865. this.appendParticleVertexes = null;
  43866. this.id = name;
  43867. this._capacity = capacity;
  43868. this._epsilon = epsilon;
  43869. if (_isAnimationSheetEnabled) {
  43870. this._vertexBufferSize = 12;
  43871. }
  43872. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43873. this._customEffect = customEffect;
  43874. scene.particleSystems.push(this);
  43875. this._createIndexBuffer();
  43876. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  43877. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  43878. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  43879. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  43880. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  43881. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  43882. if (this._isAnimationSheetEnabled) {
  43883. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  43884. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  43885. }
  43886. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43887. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43888. this._vertexBuffers["options"] = options;
  43889. // Default behaviors
  43890. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  43891. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  43892. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  43893. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  43894. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  43895. };
  43896. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  43897. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  43898. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  43899. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  43900. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  43901. };
  43902. this.updateFunction = function (particles) {
  43903. for (var index = 0; index < particles.length; index++) {
  43904. var particle = particles[index];
  43905. particle.age += _this._scaledUpdateSpeed;
  43906. if (particle.age >= particle.lifeTime) {
  43907. _this.recycleParticle(particle);
  43908. index--;
  43909. continue;
  43910. }
  43911. else {
  43912. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  43913. particle.color.addInPlace(_this._scaledColorStep);
  43914. if (particle.color.a < 0)
  43915. particle.color.a = 0;
  43916. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  43917. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  43918. particle.position.addInPlace(_this._scaledDirection);
  43919. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  43920. particle.direction.addInPlace(_this._scaledGravity);
  43921. if (_this._isAnimationSheetEnabled) {
  43922. particle.updateCellIndex(_this._scaledUpdateSpeed);
  43923. }
  43924. }
  43925. }
  43926. };
  43927. }
  43928. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  43929. set: function (callback) {
  43930. if (this._onDisposeObserver) {
  43931. this.onDisposeObservable.remove(this._onDisposeObserver);
  43932. }
  43933. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43934. },
  43935. enumerable: true,
  43936. configurable: true
  43937. });
  43938. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  43939. get: function () {
  43940. return this._isAnimationSheetEnabled;
  43941. },
  43942. enumerable: true,
  43943. configurable: true
  43944. });
  43945. ParticleSystem.prototype._createIndexBuffer = function () {
  43946. var indices = [];
  43947. var index = 0;
  43948. for (var count = 0; count < this._capacity; count++) {
  43949. indices.push(index);
  43950. indices.push(index + 1);
  43951. indices.push(index + 2);
  43952. indices.push(index);
  43953. indices.push(index + 2);
  43954. indices.push(index + 3);
  43955. index += 4;
  43956. }
  43957. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  43958. };
  43959. ParticleSystem.prototype.recycleParticle = function (particle) {
  43960. var lastParticle = this.particles.pop();
  43961. if (lastParticle !== particle) {
  43962. lastParticle.copyTo(particle);
  43963. this._stockParticles.push(lastParticle);
  43964. }
  43965. };
  43966. ParticleSystem.prototype.getCapacity = function () {
  43967. return this._capacity;
  43968. };
  43969. ParticleSystem.prototype.isAlive = function () {
  43970. return this._alive;
  43971. };
  43972. ParticleSystem.prototype.isStarted = function () {
  43973. return this._started;
  43974. };
  43975. ParticleSystem.prototype.start = function () {
  43976. this._started = true;
  43977. this._stopped = false;
  43978. this._actualFrame = 0;
  43979. };
  43980. ParticleSystem.prototype.stop = function () {
  43981. this._stopped = true;
  43982. };
  43983. // animation sheet
  43984. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  43985. var offset = index * this._vertexBufferSize;
  43986. this._vertexData[offset] = particle.position.x;
  43987. this._vertexData[offset + 1] = particle.position.y;
  43988. this._vertexData[offset + 2] = particle.position.z;
  43989. this._vertexData[offset + 3] = particle.color.r;
  43990. this._vertexData[offset + 4] = particle.color.g;
  43991. this._vertexData[offset + 5] = particle.color.b;
  43992. this._vertexData[offset + 6] = particle.color.a;
  43993. this._vertexData[offset + 7] = particle.angle;
  43994. this._vertexData[offset + 8] = particle.size;
  43995. this._vertexData[offset + 9] = offsetX;
  43996. this._vertexData[offset + 10] = offsetY;
  43997. };
  43998. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  43999. if (offsetX === 0)
  44000. offsetX = this._epsilon;
  44001. else if (offsetX === 1)
  44002. offsetX = 1 - this._epsilon;
  44003. if (offsetY === 0)
  44004. offsetY = this._epsilon;
  44005. else if (offsetY === 1)
  44006. offsetY = 1 - this._epsilon;
  44007. var offset = index * this._vertexBufferSize;
  44008. this._vertexData[offset] = particle.position.x;
  44009. this._vertexData[offset + 1] = particle.position.y;
  44010. this._vertexData[offset + 2] = particle.position.z;
  44011. this._vertexData[offset + 3] = particle.color.r;
  44012. this._vertexData[offset + 4] = particle.color.g;
  44013. this._vertexData[offset + 5] = particle.color.b;
  44014. this._vertexData[offset + 6] = particle.color.a;
  44015. this._vertexData[offset + 7] = particle.angle;
  44016. this._vertexData[offset + 8] = particle.size;
  44017. this._vertexData[offset + 9] = offsetX;
  44018. this._vertexData[offset + 10] = offsetY;
  44019. this._vertexData[offset + 11] = particle.cellIndex;
  44020. };
  44021. ParticleSystem.prototype._update = function (newParticles) {
  44022. // Update current
  44023. this._alive = this.particles.length > 0;
  44024. this.updateFunction(this.particles);
  44025. // Add new ones
  44026. var worldMatrix;
  44027. if (this.emitter.position) {
  44028. var emitterMesh = this.emitter;
  44029. worldMatrix = emitterMesh.getWorldMatrix();
  44030. }
  44031. else {
  44032. var emitterPosition = this.emitter;
  44033. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44034. }
  44035. var particle;
  44036. for (var index = 0; index < newParticles; index++) {
  44037. if (this.particles.length === this._capacity) {
  44038. break;
  44039. }
  44040. if (this._stockParticles.length !== 0) {
  44041. particle = this._stockParticles.pop();
  44042. particle.age = 0;
  44043. particle.cellIndex = this.startSpriteCellID;
  44044. }
  44045. else {
  44046. particle = new BABYLON.Particle(this);
  44047. }
  44048. this.particles.push(particle);
  44049. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44050. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44051. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44052. particle.size = randomNumber(this.minSize, this.maxSize);
  44053. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44054. this.startPositionFunction(worldMatrix, particle.position, particle);
  44055. var step = randomNumber(0, 1.0);
  44056. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44057. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44058. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44059. }
  44060. };
  44061. ParticleSystem.prototype._getEffect = function () {
  44062. if (this._customEffect) {
  44063. return this._customEffect;
  44064. }
  44065. ;
  44066. var defines = [];
  44067. if (this._scene.clipPlane) {
  44068. defines.push("#define CLIPPLANE");
  44069. }
  44070. if (this._isAnimationSheetEnabled) {
  44071. defines.push("#define ANIMATESHEET");
  44072. }
  44073. // Effect
  44074. var join = defines.join("\n");
  44075. if (this._cachedDefines !== join) {
  44076. this._cachedDefines = join;
  44077. var attributesNamesOrOptions;
  44078. var effectCreationOption;
  44079. if (this._isAnimationSheetEnabled) {
  44080. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44081. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44082. }
  44083. else {
  44084. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44085. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44086. }
  44087. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44088. }
  44089. return this._effect;
  44090. };
  44091. ParticleSystem.prototype.animate = function () {
  44092. if (!this._started)
  44093. return;
  44094. var effect = this._getEffect();
  44095. // Check
  44096. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44097. return;
  44098. if (this._currentRenderId === this._scene.getRenderId()) {
  44099. return;
  44100. }
  44101. this._currentRenderId = this._scene.getRenderId();
  44102. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44103. // determine the number of particles we need to create
  44104. var newParticles;
  44105. if (this.manualEmitCount > -1) {
  44106. newParticles = this.manualEmitCount;
  44107. this._newPartsExcess = 0;
  44108. this.manualEmitCount = 0;
  44109. }
  44110. else {
  44111. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44112. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44113. }
  44114. if (this._newPartsExcess > 1.0) {
  44115. newParticles += this._newPartsExcess >> 0;
  44116. this._newPartsExcess -= this._newPartsExcess >> 0;
  44117. }
  44118. this._alive = false;
  44119. if (!this._stopped) {
  44120. this._actualFrame += this._scaledUpdateSpeed;
  44121. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44122. this.stop();
  44123. }
  44124. else {
  44125. newParticles = 0;
  44126. }
  44127. this._update(newParticles);
  44128. // Stopped?
  44129. if (this._stopped) {
  44130. if (!this._alive) {
  44131. this._started = false;
  44132. if (this.onAnimationEnd) {
  44133. this.onAnimationEnd();
  44134. }
  44135. if (this.disposeOnStop) {
  44136. this._scene._toBeDisposed.push(this);
  44137. }
  44138. }
  44139. }
  44140. // Animation sheet
  44141. if (this._isAnimationSheetEnabled) {
  44142. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44143. }
  44144. else {
  44145. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44146. }
  44147. // Update VBO
  44148. var offset = 0;
  44149. for (var index = 0; index < this.particles.length; index++) {
  44150. var particle = this.particles[index];
  44151. this.appendParticleVertexes(offset, particle);
  44152. offset += 4;
  44153. }
  44154. if (this._vertexBuffer) {
  44155. this._vertexBuffer.update(this._vertexData);
  44156. }
  44157. };
  44158. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44159. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44160. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44161. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44162. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44163. };
  44164. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44165. this._appendParticleVertex(offset++, particle, 0, 0);
  44166. this._appendParticleVertex(offset++, particle, 1, 0);
  44167. this._appendParticleVertex(offset++, particle, 1, 1);
  44168. this._appendParticleVertex(offset++, particle, 0, 1);
  44169. };
  44170. ParticleSystem.prototype.rebuild = function () {
  44171. this._createIndexBuffer();
  44172. if (this._vertexBuffer) {
  44173. this._vertexBuffer._rebuild();
  44174. }
  44175. };
  44176. ParticleSystem.prototype.render = function () {
  44177. var effect = this._getEffect();
  44178. // Check
  44179. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44180. return 0;
  44181. var engine = this._scene.getEngine();
  44182. // Render
  44183. engine.enableEffect(effect);
  44184. engine.setState(false);
  44185. var viewMatrix = this._scene.getViewMatrix();
  44186. effect.setTexture("diffuseSampler", this.particleTexture);
  44187. effect.setMatrix("view", viewMatrix);
  44188. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44189. if (this._isAnimationSheetEnabled) {
  44190. var baseSize = this.particleTexture.getBaseSize();
  44191. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44192. }
  44193. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44194. if (this._scene.clipPlane) {
  44195. var clipPlane = this._scene.clipPlane;
  44196. var invView = viewMatrix.clone();
  44197. invView.invert();
  44198. effect.setMatrix("invView", invView);
  44199. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44200. }
  44201. // VBOs
  44202. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44203. // Draw order
  44204. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44205. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44206. }
  44207. else {
  44208. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44209. }
  44210. if (this.forceDepthWrite) {
  44211. engine.setDepthWrite(true);
  44212. }
  44213. engine.draw(true, 0, this.particles.length * 6);
  44214. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44215. return this.particles.length;
  44216. };
  44217. ParticleSystem.prototype.dispose = function () {
  44218. if (this._vertexBuffer) {
  44219. this._vertexBuffer.dispose();
  44220. this._vertexBuffer = null;
  44221. }
  44222. if (this._indexBuffer) {
  44223. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44224. this._indexBuffer = null;
  44225. }
  44226. if (this.particleTexture) {
  44227. this.particleTexture.dispose();
  44228. this.particleTexture = null;
  44229. }
  44230. // Remove from scene
  44231. var index = this._scene.particleSystems.indexOf(this);
  44232. if (index > -1) {
  44233. this._scene.particleSystems.splice(index, 1);
  44234. }
  44235. // Callback
  44236. this.onDisposeObservable.notifyObservers(this);
  44237. this.onDisposeObservable.clear();
  44238. };
  44239. // Clone
  44240. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44241. var custom = null;
  44242. var program = null;
  44243. if (this.customShader != null) {
  44244. program = this.customShader;
  44245. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44246. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44247. }
  44248. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44249. result.customShader = program;
  44250. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44251. if (newEmitter === undefined) {
  44252. newEmitter = this.emitter;
  44253. }
  44254. result.emitter = newEmitter;
  44255. if (this.particleTexture) {
  44256. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44257. }
  44258. if (!this.preventAutoStart) {
  44259. result.start();
  44260. }
  44261. return result;
  44262. };
  44263. ParticleSystem.prototype.serialize = function () {
  44264. var serializationObject = {};
  44265. serializationObject.name = this.name;
  44266. serializationObject.id = this.id;
  44267. // Emitter
  44268. if (this.emitter.position) {
  44269. var emitterMesh = this.emitter;
  44270. serializationObject.emitterId = emitterMesh.id;
  44271. }
  44272. else {
  44273. var emitterPosition = this.emitter;
  44274. serializationObject.emitter = emitterPosition.asArray();
  44275. }
  44276. serializationObject.capacity = this.getCapacity();
  44277. if (this.particleTexture) {
  44278. serializationObject.textureName = this.particleTexture.name;
  44279. }
  44280. // Animations
  44281. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44282. // Particle system
  44283. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44284. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44285. serializationObject.minSize = this.minSize;
  44286. serializationObject.maxSize = this.maxSize;
  44287. serializationObject.minEmitPower = this.minEmitPower;
  44288. serializationObject.maxEmitPower = this.maxEmitPower;
  44289. serializationObject.minLifeTime = this.minLifeTime;
  44290. serializationObject.maxLifeTime = this.maxLifeTime;
  44291. serializationObject.emitRate = this.emitRate;
  44292. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44293. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44294. serializationObject.gravity = this.gravity.asArray();
  44295. serializationObject.direction1 = this.direction1.asArray();
  44296. serializationObject.direction2 = this.direction2.asArray();
  44297. serializationObject.color1 = this.color1.asArray();
  44298. serializationObject.color2 = this.color2.asArray();
  44299. serializationObject.colorDead = this.colorDead.asArray();
  44300. serializationObject.updateSpeed = this.updateSpeed;
  44301. serializationObject.targetStopDuration = this.targetStopDuration;
  44302. serializationObject.textureMask = this.textureMask.asArray();
  44303. serializationObject.blendMode = this.blendMode;
  44304. serializationObject.customShader = this.customShader;
  44305. serializationObject.preventAutoStart = this.preventAutoStart;
  44306. return serializationObject;
  44307. };
  44308. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44309. var name = parsedParticleSystem.name;
  44310. var custom = null;
  44311. var program = null;
  44312. if (parsedParticleSystem.customShader) {
  44313. program = parsedParticleSystem.customShader;
  44314. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44315. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44316. }
  44317. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44318. particleSystem.customShader = program;
  44319. if (parsedParticleSystem.id) {
  44320. particleSystem.id = parsedParticleSystem.id;
  44321. }
  44322. // Auto start
  44323. if (parsedParticleSystem.preventAutoStart) {
  44324. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44325. }
  44326. // Texture
  44327. if (parsedParticleSystem.textureName) {
  44328. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  44329. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  44330. }
  44331. // Emitter
  44332. if (parsedParticleSystem.emitterId) {
  44333. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  44334. }
  44335. else {
  44336. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  44337. }
  44338. // Animations
  44339. if (parsedParticleSystem.animations) {
  44340. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  44341. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  44342. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44343. }
  44344. }
  44345. if (parsedParticleSystem.autoAnimate) {
  44346. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  44347. }
  44348. // Particle system
  44349. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  44350. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  44351. particleSystem.minSize = parsedParticleSystem.minSize;
  44352. particleSystem.maxSize = parsedParticleSystem.maxSize;
  44353. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  44354. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  44355. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  44356. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  44357. particleSystem.emitRate = parsedParticleSystem.emitRate;
  44358. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  44359. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  44360. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  44361. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  44362. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  44363. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  44364. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  44365. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  44366. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  44367. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  44368. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  44369. particleSystem.blendMode = parsedParticleSystem.blendMode;
  44370. if (!particleSystem.preventAutoStart) {
  44371. particleSystem.start();
  44372. }
  44373. return particleSystem;
  44374. };
  44375. // Statics
  44376. ParticleSystem.BLENDMODE_ONEONE = 0;
  44377. ParticleSystem.BLENDMODE_STANDARD = 1;
  44378. return ParticleSystem;
  44379. }());
  44380. BABYLON.ParticleSystem = ParticleSystem;
  44381. })(BABYLON || (BABYLON = {}));
  44382. //# sourceMappingURL=babylon.particleSystem.js.map
  44383. var BABYLON;
  44384. (function (BABYLON) {
  44385. var SolidParticle = /** @class */ (function () {
  44386. /**
  44387. * Creates a Solid Particle object.
  44388. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  44389. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  44390. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  44391. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  44392. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  44393. * `shapeId` (integer) is the model shape identifier in the SPS.
  44394. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  44395. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  44396. */
  44397. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  44398. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  44399. this.idx = 0; // particle global index
  44400. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  44401. this.position = BABYLON.Vector3.Zero(); // position
  44402. this.rotation = BABYLON.Vector3.Zero(); // rotation
  44403. this.scaling = BABYLON.Vector3.One(); // scaling
  44404. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  44405. this.velocity = BABYLON.Vector3.Zero(); // velocity
  44406. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  44407. this.alive = true; // alive
  44408. this.isVisible = true; // visibility
  44409. this._pos = 0; // index of this particle in the global "positions" array
  44410. this._ind = 0; // index of this particle in the global "indices" array
  44411. this.shapeId = 0; // model shape id
  44412. this.idxInShape = 0; // index of the particle in its shape id
  44413. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  44414. this.idx = particleIndex;
  44415. this._pos = positionIndex;
  44416. this._ind = indiceIndex;
  44417. this._model = model;
  44418. this.shapeId = shapeId;
  44419. this.idxInShape = idxInShape;
  44420. this._sps = sps;
  44421. if (modelBoundingInfo) {
  44422. this._modelBoundingInfo = modelBoundingInfo;
  44423. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  44424. }
  44425. }
  44426. Object.defineProperty(SolidParticle.prototype, "scale", {
  44427. /**
  44428. * legacy support, changed scale to scaling
  44429. */
  44430. get: function () {
  44431. return this.scaling;
  44432. },
  44433. set: function (scale) {
  44434. this.scaling = scale;
  44435. },
  44436. enumerable: true,
  44437. configurable: true
  44438. });
  44439. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  44440. /**
  44441. * legacy support, changed quaternion to rotationQuaternion
  44442. */
  44443. get: function () {
  44444. return this.rotationQuaternion;
  44445. },
  44446. set: function (q) {
  44447. this.rotationQuaternion = q;
  44448. },
  44449. enumerable: true,
  44450. configurable: true
  44451. });
  44452. /**
  44453. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  44454. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  44455. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  44456. */
  44457. SolidParticle.prototype.intersectsMesh = function (target) {
  44458. if (!this._boundingInfo || !target._boundingInfo) {
  44459. return false;
  44460. }
  44461. if (this._sps._bSphereOnly) {
  44462. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  44463. }
  44464. return this._boundingInfo.intersects(target._boundingInfo, false);
  44465. };
  44466. return SolidParticle;
  44467. }());
  44468. BABYLON.SolidParticle = SolidParticle;
  44469. var ModelShape = /** @class */ (function () {
  44470. /**
  44471. * 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.
  44472. * SPS internal tool, don't use it manually.
  44473. */
  44474. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  44475. this._indicesLength = 0; // length of the shape in the model indices array
  44476. this.shapeID = id;
  44477. this._shape = shape;
  44478. this._indicesLength = indicesLength;
  44479. this._shapeUV = shapeUV;
  44480. this._positionFunction = posFunction;
  44481. this._vertexFunction = vtxFunction;
  44482. }
  44483. return ModelShape;
  44484. }());
  44485. BABYLON.ModelShape = ModelShape;
  44486. var DepthSortedParticle = /** @class */ (function () {
  44487. function DepthSortedParticle() {
  44488. this.ind = 0; // index of the particle in the "indices" array
  44489. this.indicesLength = 0; // length of the particle shape in the "indices" array
  44490. this.sqDistance = 0.0; // squared distance from the particle to the camera
  44491. }
  44492. return DepthSortedParticle;
  44493. }());
  44494. BABYLON.DepthSortedParticle = DepthSortedParticle;
  44495. })(BABYLON || (BABYLON = {}));
  44496. //# sourceMappingURL=babylon.solidParticle.js.map
  44497. var BABYLON;
  44498. (function (BABYLON) {
  44499. /**
  44500. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  44501. */
  44502. var SolidParticleSystem = /** @class */ (function () {
  44503. /**
  44504. * Creates a SPS (Solid Particle System) object.
  44505. * `name` (String) is the SPS name, this will be the underlying mesh name.
  44506. * `scene` (Scene) is the scene in which the SPS is added.
  44507. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  44508. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  44509. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  44510. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  44511. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  44512. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  44513. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  44514. */
  44515. function SolidParticleSystem(name, scene, options) {
  44516. // public members
  44517. /**
  44518. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  44519. * Example : var p = SPS.particles[i];
  44520. */
  44521. this.particles = new Array();
  44522. /**
  44523. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  44524. */
  44525. this.nbParticles = 0;
  44526. /**
  44527. * If the particles must ever face the camera (default false). Useful for planar particles.
  44528. */
  44529. this.billboard = false;
  44530. /**
  44531. * Recompute normals when adding a shape
  44532. */
  44533. this.recomputeNormals = true;
  44534. /**
  44535. * This a counter ofr your own usage. It's not set by any SPS functions.
  44536. */
  44537. this.counter = 0;
  44538. /**
  44539. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  44540. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  44541. */
  44542. this.vars = {};
  44543. this._positions = new Array();
  44544. this._indices = new Array();
  44545. this._normals = new Array();
  44546. this._colors = new Array();
  44547. this._uvs = new Array();
  44548. this._index = 0; // indices index
  44549. this._updatable = true;
  44550. this._pickable = false;
  44551. this._isVisibilityBoxLocked = false;
  44552. this._alwaysVisible = false;
  44553. this._depthSort = false;
  44554. this._shapeCounter = 0;
  44555. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  44556. this._color = new BABYLON.Color4(0, 0, 0, 0);
  44557. this._computeParticleColor = true;
  44558. this._computeParticleTexture = true;
  44559. this._computeParticleRotation = true;
  44560. this._computeParticleVertex = false;
  44561. this._computeBoundingBox = false;
  44562. this._depthSortParticles = true;
  44563. this._cam_axisZ = BABYLON.Vector3.Zero();
  44564. this._cam_axisY = BABYLON.Vector3.Zero();
  44565. this._cam_axisX = BABYLON.Vector3.Zero();
  44566. this._axisZ = BABYLON.Axis.Z;
  44567. this._camDir = BABYLON.Vector3.Zero();
  44568. this._camInvertedPosition = BABYLON.Vector3.Zero();
  44569. this._rotMatrix = new BABYLON.Matrix();
  44570. this._invertMatrix = new BABYLON.Matrix();
  44571. this._rotated = BABYLON.Vector3.Zero();
  44572. this._quaternion = new BABYLON.Quaternion();
  44573. this._vertex = BABYLON.Vector3.Zero();
  44574. this._normal = BABYLON.Vector3.Zero();
  44575. this._yaw = 0.0;
  44576. this._pitch = 0.0;
  44577. this._roll = 0.0;
  44578. this._halfroll = 0.0;
  44579. this._halfpitch = 0.0;
  44580. this._halfyaw = 0.0;
  44581. this._sinRoll = 0.0;
  44582. this._cosRoll = 0.0;
  44583. this._sinPitch = 0.0;
  44584. this._cosPitch = 0.0;
  44585. this._sinYaw = 0.0;
  44586. this._cosYaw = 0.0;
  44587. this._mustUnrotateFixedNormals = false;
  44588. this._minimum = BABYLON.Tmp.Vector3[0];
  44589. this._maximum = BABYLON.Tmp.Vector3[1];
  44590. this._minBbox = BABYLON.Tmp.Vector3[4];
  44591. this._maxBbox = BABYLON.Tmp.Vector3[5];
  44592. this._particlesIntersect = false;
  44593. this._depthSortFunction = function (p1, p2) {
  44594. return (p2.sqDistance - p1.sqDistance);
  44595. };
  44596. this._needs32Bits = false;
  44597. this._bSphereOnly = false;
  44598. this._bSphereRadiusFactor = 1.0;
  44599. this.name = name;
  44600. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44601. this._camera = scene.activeCamera;
  44602. this._pickable = options ? options.isPickable : false;
  44603. this._depthSort = options ? options.enableDepthSort : false;
  44604. this._particlesIntersect = options ? options.particleIntersection : false;
  44605. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  44606. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  44607. if (options && options.updatable) {
  44608. this._updatable = options.updatable;
  44609. }
  44610. else {
  44611. this._updatable = true;
  44612. }
  44613. if (this._pickable) {
  44614. this.pickedParticles = [];
  44615. }
  44616. if (this._depthSort) {
  44617. this.depthSortedParticles = [];
  44618. }
  44619. }
  44620. /**
  44621. * Builds the SPS underlying mesh. Returns a standard Mesh.
  44622. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  44623. */
  44624. SolidParticleSystem.prototype.buildMesh = function () {
  44625. if (this.nbParticles === 0) {
  44626. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  44627. this.addShape(triangle, 1);
  44628. triangle.dispose();
  44629. }
  44630. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  44631. this._positions32 = new Float32Array(this._positions);
  44632. this._uvs32 = new Float32Array(this._uvs);
  44633. this._colors32 = new Float32Array(this._colors);
  44634. if (this.recomputeNormals) {
  44635. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  44636. }
  44637. this._normals32 = new Float32Array(this._normals);
  44638. this._fixedNormal32 = new Float32Array(this._normals);
  44639. if (this._mustUnrotateFixedNormals) {
  44640. this._unrotateFixedNormals();
  44641. }
  44642. var vertexData = new BABYLON.VertexData();
  44643. vertexData.indices = this._indices32;
  44644. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  44645. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  44646. if (this._uvs32) {
  44647. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  44648. ;
  44649. }
  44650. if (this._colors32) {
  44651. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  44652. }
  44653. var mesh = new BABYLON.Mesh(this.name, this._scene);
  44654. vertexData.applyToMesh(mesh, this._updatable);
  44655. this.mesh = mesh;
  44656. this.mesh.isPickable = this._pickable;
  44657. // free memory
  44658. if (!this._depthSort) {
  44659. this._indices = null;
  44660. }
  44661. this._positions = null;
  44662. this._normals = null;
  44663. this._uvs = null;
  44664. this._colors = null;
  44665. if (!this._updatable) {
  44666. this.particles.length = 0;
  44667. }
  44668. return mesh;
  44669. };
  44670. /**
  44671. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  44672. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  44673. * Thus the particles generated from `digest()` have their property `position` set yet.
  44674. * `mesh` ( Mesh ) is the mesh to be digested
  44675. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  44676. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  44677. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  44678. */
  44679. SolidParticleSystem.prototype.digest = function (mesh, options) {
  44680. var size = (options && options.facetNb) || 1;
  44681. var number = (options && options.number) || 0;
  44682. var delta = (options && options.delta) || 0;
  44683. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44684. var meshInd = mesh.getIndices();
  44685. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44686. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44687. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44688. var f = 0; // facet counter
  44689. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  44690. // compute size from number
  44691. if (number) {
  44692. number = (number > totalFacets) ? totalFacets : number;
  44693. size = Math.round(totalFacets / number);
  44694. delta = 0;
  44695. }
  44696. else {
  44697. size = (size > totalFacets) ? totalFacets : size;
  44698. }
  44699. var facetPos = []; // submesh positions
  44700. var facetInd = []; // submesh indices
  44701. var facetUV = []; // submesh UV
  44702. var facetCol = []; // submesh colors
  44703. var barycenter = BABYLON.Tmp.Vector3[0];
  44704. var sizeO = size;
  44705. while (f < totalFacets) {
  44706. size = sizeO + Math.floor((1 + delta) * Math.random());
  44707. if (f > totalFacets - size) {
  44708. size = totalFacets - f;
  44709. }
  44710. // reset temp arrays
  44711. facetPos.length = 0;
  44712. facetInd.length = 0;
  44713. facetUV.length = 0;
  44714. facetCol.length = 0;
  44715. // iterate over "size" facets
  44716. var fi = 0;
  44717. for (var j = f * 3; j < (f + size) * 3; j++) {
  44718. facetInd.push(fi);
  44719. var i = meshInd[j];
  44720. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  44721. if (meshUV) {
  44722. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  44723. }
  44724. if (meshCol) {
  44725. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  44726. }
  44727. fi++;
  44728. }
  44729. // create a model shape for each single particle
  44730. var idx = this.nbParticles;
  44731. var shape = this._posToShape(facetPos);
  44732. var shapeUV = this._uvsToShapeUV(facetUV);
  44733. // compute the barycenter of the shape
  44734. var v;
  44735. for (v = 0; v < shape.length; v++) {
  44736. barycenter.addInPlace(shape[v]);
  44737. }
  44738. barycenter.scaleInPlace(1 / shape.length);
  44739. // shift the shape from its barycenter to the origin
  44740. for (v = 0; v < shape.length; v++) {
  44741. shape[v].subtractInPlace(barycenter);
  44742. }
  44743. var bInfo;
  44744. if (this._particlesIntersect) {
  44745. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  44746. }
  44747. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  44748. // add the particle in the SPS
  44749. var currentPos = this._positions.length;
  44750. var currentInd = this._indices.length;
  44751. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  44752. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  44753. // initialize the particle position
  44754. this.particles[this.nbParticles].position.addInPlace(barycenter);
  44755. this._index += shape.length;
  44756. idx++;
  44757. this.nbParticles++;
  44758. this._shapeCounter++;
  44759. f += size;
  44760. }
  44761. return this;
  44762. };
  44763. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  44764. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  44765. var index = 0;
  44766. var idx = 0;
  44767. for (var p = 0; p < this.particles.length; p++) {
  44768. this._particle = this.particles[p];
  44769. this._shape = this._particle._model._shape;
  44770. if (this._particle.rotationQuaternion) {
  44771. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44772. }
  44773. else {
  44774. this._yaw = this._particle.rotation.y;
  44775. this._pitch = this._particle.rotation.x;
  44776. this._roll = this._particle.rotation.z;
  44777. this._quaternionRotationYPR();
  44778. }
  44779. this._quaternionToRotationMatrix();
  44780. this._rotMatrix.invertToRef(this._invertMatrix);
  44781. for (var pt = 0; pt < this._shape.length; pt++) {
  44782. idx = index + pt * 3;
  44783. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  44784. this._fixedNormal32[idx] = this._normal.x;
  44785. this._fixedNormal32[idx + 1] = this._normal.y;
  44786. this._fixedNormal32[idx + 2] = this._normal.z;
  44787. }
  44788. index = idx + 3;
  44789. }
  44790. };
  44791. //reset copy
  44792. SolidParticleSystem.prototype._resetCopy = function () {
  44793. this._copy.position.x = 0;
  44794. this._copy.position.y = 0;
  44795. this._copy.position.z = 0;
  44796. this._copy.rotation.x = 0;
  44797. this._copy.rotation.y = 0;
  44798. this._copy.rotation.z = 0;
  44799. this._copy.rotationQuaternion = null;
  44800. this._copy.scaling.x = 1.0;
  44801. this._copy.scaling.y = 1.0;
  44802. this._copy.scaling.z = 1.0;
  44803. this._copy.uvs.x = 0;
  44804. this._copy.uvs.y = 0;
  44805. this._copy.uvs.z = 1.0;
  44806. this._copy.uvs.w = 1.0;
  44807. this._copy.color = null;
  44808. };
  44809. // _meshBuilder : inserts the shape model in the global SPS mesh
  44810. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  44811. var i;
  44812. var u = 0;
  44813. var c = 0;
  44814. var n = 0;
  44815. this._resetCopy();
  44816. if (options && options.positionFunction) {
  44817. options.positionFunction(this._copy, idx, idxInShape);
  44818. this._mustUnrotateFixedNormals = true;
  44819. }
  44820. if (this._copy.rotationQuaternion) {
  44821. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44822. }
  44823. else {
  44824. this._yaw = this._copy.rotation.y;
  44825. this._pitch = this._copy.rotation.x;
  44826. this._roll = this._copy.rotation.z;
  44827. this._quaternionRotationYPR();
  44828. }
  44829. this._quaternionToRotationMatrix();
  44830. for (i = 0; i < shape.length; i++) {
  44831. this._vertex.x = shape[i].x;
  44832. this._vertex.y = shape[i].y;
  44833. this._vertex.z = shape[i].z;
  44834. if (options && options.vertexFunction) {
  44835. options.vertexFunction(this._copy, this._vertex, i);
  44836. }
  44837. this._vertex.x *= this._copy.scaling.x;
  44838. this._vertex.y *= this._copy.scaling.y;
  44839. this._vertex.z *= this._copy.scaling.z;
  44840. this._vertex.x += this._copy.pivot.x;
  44841. this._vertex.y += this._copy.pivot.y;
  44842. this._vertex.z += this._copy.pivot.z;
  44843. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44844. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  44845. if (meshUV) {
  44846. 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);
  44847. u += 2;
  44848. }
  44849. if (this._copy.color) {
  44850. this._color = this._copy.color;
  44851. }
  44852. else if (meshCol && meshCol[c] !== undefined) {
  44853. this._color.r = meshCol[c];
  44854. this._color.g = meshCol[c + 1];
  44855. this._color.b = meshCol[c + 2];
  44856. this._color.a = meshCol[c + 3];
  44857. }
  44858. else {
  44859. this._color.r = 1.0;
  44860. this._color.g = 1.0;
  44861. this._color.b = 1.0;
  44862. this._color.a = 1.0;
  44863. }
  44864. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  44865. c += 4;
  44866. if (!this.recomputeNormals && meshNor) {
  44867. this._normal.x = meshNor[n];
  44868. this._normal.y = meshNor[n + 1];
  44869. this._normal.z = meshNor[n + 2];
  44870. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  44871. normals.push(this._normal.x, this._normal.y, this._normal.z);
  44872. n += 3;
  44873. }
  44874. }
  44875. for (i = 0; i < meshInd.length; i++) {
  44876. var current_ind = p + meshInd[i];
  44877. indices.push(current_ind);
  44878. if (current_ind > 65535) {
  44879. this._needs32Bits = true;
  44880. }
  44881. }
  44882. if (this._pickable) {
  44883. var nbfaces = meshInd.length / 3;
  44884. for (i = 0; i < nbfaces; i++) {
  44885. this.pickedParticles.push({ idx: idx, faceId: i });
  44886. }
  44887. }
  44888. if (this._depthSort) {
  44889. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  44890. }
  44891. return this._copy;
  44892. };
  44893. // returns a shape array from positions array
  44894. SolidParticleSystem.prototype._posToShape = function (positions) {
  44895. var shape = [];
  44896. for (var i = 0; i < positions.length; i += 3) {
  44897. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  44898. }
  44899. return shape;
  44900. };
  44901. // returns a shapeUV array from a Vector4 uvs
  44902. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  44903. var shapeUV = [];
  44904. if (uvs) {
  44905. for (var i = 0; i < uvs.length; i++)
  44906. shapeUV.push(uvs[i]);
  44907. }
  44908. return shapeUV;
  44909. };
  44910. // adds a new particle object in the particles array
  44911. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  44912. if (bInfo === void 0) { bInfo = null; }
  44913. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  44914. this.particles.push(sp);
  44915. return sp;
  44916. };
  44917. /**
  44918. * Adds some particles to the SPS from the model shape. Returns the shape id.
  44919. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  44920. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  44921. * `nb` (positive integer) the number of particles to be created from this model
  44922. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  44923. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  44924. */
  44925. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  44926. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44927. var meshInd = mesh.getIndices();
  44928. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44929. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44930. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44931. var bbInfo;
  44932. if (this._particlesIntersect) {
  44933. bbInfo = mesh.getBoundingInfo();
  44934. }
  44935. var shape = this._posToShape(meshPos);
  44936. var shapeUV = this._uvsToShapeUV(meshUV);
  44937. var posfunc = options ? options.positionFunction : null;
  44938. var vtxfunc = options ? options.vertexFunction : null;
  44939. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  44940. // particles
  44941. var sp;
  44942. var currentCopy;
  44943. var idx = this.nbParticles;
  44944. for (var i = 0; i < nb; i++) {
  44945. var currentPos = this._positions.length;
  44946. var currentInd = this._indices.length;
  44947. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  44948. if (this._updatable) {
  44949. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  44950. sp.position.copyFrom(currentCopy.position);
  44951. sp.rotation.copyFrom(currentCopy.rotation);
  44952. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  44953. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  44954. }
  44955. if (currentCopy.color && sp.color) {
  44956. sp.color.copyFrom(currentCopy.color);
  44957. }
  44958. sp.scaling.copyFrom(currentCopy.scaling);
  44959. sp.uvs.copyFrom(currentCopy.uvs);
  44960. }
  44961. this._index += shape.length;
  44962. idx++;
  44963. }
  44964. this.nbParticles += nb;
  44965. this._shapeCounter++;
  44966. return this._shapeCounter - 1;
  44967. };
  44968. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  44969. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  44970. this._resetCopy();
  44971. if (particle._model._positionFunction) {
  44972. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  44973. }
  44974. if (this._copy.rotationQuaternion) {
  44975. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44976. }
  44977. else {
  44978. this._yaw = this._copy.rotation.y;
  44979. this._pitch = this._copy.rotation.x;
  44980. this._roll = this._copy.rotation.z;
  44981. this._quaternionRotationYPR();
  44982. }
  44983. this._quaternionToRotationMatrix();
  44984. this._shape = particle._model._shape;
  44985. for (var pt = 0; pt < this._shape.length; pt++) {
  44986. this._vertex.x = this._shape[pt].x;
  44987. this._vertex.y = this._shape[pt].y;
  44988. this._vertex.z = this._shape[pt].z;
  44989. if (particle._model._vertexFunction) {
  44990. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  44991. }
  44992. this._vertex.x *= this._copy.scaling.x;
  44993. this._vertex.y *= this._copy.scaling.y;
  44994. this._vertex.z *= this._copy.scaling.z;
  44995. this._vertex.x += this._copy.pivot.x;
  44996. this._vertex.y += this._copy.pivot.y;
  44997. this._vertex.z += this._copy.pivot.z;
  44998. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44999. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45000. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45001. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45002. }
  45003. particle.position.x = 0.0;
  45004. particle.position.y = 0.0;
  45005. particle.position.z = 0.0;
  45006. particle.rotation.x = 0.0;
  45007. particle.rotation.y = 0.0;
  45008. particle.rotation.z = 0.0;
  45009. particle.rotationQuaternion = null;
  45010. particle.scaling.x = 1.0;
  45011. particle.scaling.y = 1.0;
  45012. particle.scaling.z = 1.0;
  45013. };
  45014. /**
  45015. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45016. * Returns the SPS.
  45017. */
  45018. SolidParticleSystem.prototype.rebuildMesh = function () {
  45019. for (var p = 0; p < this.particles.length; p++) {
  45020. this._rebuildParticle(this.particles[p]);
  45021. }
  45022. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45023. return this;
  45024. };
  45025. /**
  45026. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45027. * This method calls `updateParticle()` for each particle of the SPS.
  45028. * For an animated SPS, it is usually called within the render loop.
  45029. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45030. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45031. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45032. * Returns the SPS.
  45033. */
  45034. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45035. if (start === void 0) { start = 0; }
  45036. if (end === void 0) { end = this.nbParticles - 1; }
  45037. if (update === void 0) { update = true; }
  45038. if (!this._updatable) {
  45039. return this;
  45040. }
  45041. // custom beforeUpdate
  45042. this.beforeUpdateParticles(start, end, update);
  45043. this._cam_axisX.x = 1.0;
  45044. this._cam_axisX.y = 0.0;
  45045. this._cam_axisX.z = 0.0;
  45046. this._cam_axisY.x = 0.0;
  45047. this._cam_axisY.y = 1.0;
  45048. this._cam_axisY.z = 0.0;
  45049. this._cam_axisZ.x = 0.0;
  45050. this._cam_axisZ.y = 0.0;
  45051. this._cam_axisZ.z = 1.0;
  45052. // cases when the World Matrix is to be computed first
  45053. if (this.billboard || this._depthSort) {
  45054. this.mesh.computeWorldMatrix(true);
  45055. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45056. }
  45057. // if the particles will always face the camera
  45058. if (this.billboard) {
  45059. // compute the camera position and un-rotate it by the current mesh rotation
  45060. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45061. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45062. this._cam_axisZ.normalize();
  45063. // same for camera up vector extracted from the cam view matrix
  45064. var view = this._camera.getViewMatrix(true);
  45065. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45066. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45067. this._cam_axisY.normalize();
  45068. this._cam_axisX.normalize();
  45069. }
  45070. // if depthSort, compute the camera global position in the mesh local system
  45071. if (this._depthSort) {
  45072. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45073. }
  45074. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45075. var idx = 0; // current position index in the global array positions32
  45076. var index = 0; // position start index in the global array positions32 of the current particle
  45077. var colidx = 0; // current color index in the global array colors32
  45078. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45079. var uvidx = 0; // current uv index in the global array uvs32
  45080. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45081. var pt = 0; // current index in the particle model shape
  45082. if (this.mesh.isFacetDataEnabled) {
  45083. this._computeBoundingBox = true;
  45084. }
  45085. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45086. if (this._computeBoundingBox) {
  45087. if (start == 0 && end == this.nbParticles - 1) {
  45088. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45089. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45090. }
  45091. else {
  45092. if (this.mesh._boundingInfo) {
  45093. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45094. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45095. }
  45096. }
  45097. }
  45098. // particle loop
  45099. index = this.particles[start]._pos;
  45100. var vpos = (index / 3) | 0;
  45101. colorIndex = vpos * 4;
  45102. uvIndex = vpos * 2;
  45103. for (var p = start; p <= end; p++) {
  45104. this._particle = this.particles[p];
  45105. this._shape = this._particle._model._shape;
  45106. this._shapeUV = this._particle._model._shapeUV;
  45107. // call to custom user function to update the particle properties
  45108. this.updateParticle(this._particle);
  45109. // camera-particle distance for depth sorting
  45110. if (this._depthSort && this._depthSortParticles) {
  45111. var dsp = this.depthSortedParticles[p];
  45112. dsp.ind = this._particle._ind;
  45113. dsp.indicesLength = this._particle._model._indicesLength;
  45114. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45115. }
  45116. // skip the computations for inactive or already invisible particles
  45117. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45118. // increment indexes for the next particle
  45119. pt = this._shape.length;
  45120. index += pt * 3;
  45121. colorIndex += pt * 4;
  45122. uvIndex += pt * 2;
  45123. continue;
  45124. }
  45125. if (this._particle.isVisible) {
  45126. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45127. // particle rotation matrix
  45128. if (this.billboard) {
  45129. this._particle.rotation.x = 0.0;
  45130. this._particle.rotation.y = 0.0;
  45131. }
  45132. if (this._computeParticleRotation || this.billboard) {
  45133. if (this._particle.rotationQuaternion) {
  45134. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45135. }
  45136. else {
  45137. this._yaw = this._particle.rotation.y;
  45138. this._pitch = this._particle.rotation.x;
  45139. this._roll = this._particle.rotation.z;
  45140. this._quaternionRotationYPR();
  45141. }
  45142. this._quaternionToRotationMatrix();
  45143. }
  45144. // particle vertex loop
  45145. for (pt = 0; pt < this._shape.length; pt++) {
  45146. idx = index + pt * 3;
  45147. colidx = colorIndex + pt * 4;
  45148. uvidx = uvIndex + pt * 2;
  45149. this._vertex.x = this._shape[pt].x;
  45150. this._vertex.y = this._shape[pt].y;
  45151. this._vertex.z = this._shape[pt].z;
  45152. if (this._computeParticleVertex) {
  45153. this.updateParticleVertex(this._particle, this._vertex, pt);
  45154. }
  45155. // positions
  45156. this._vertex.x *= this._particle.scaling.x;
  45157. this._vertex.y *= this._particle.scaling.y;
  45158. this._vertex.z *= this._particle.scaling.z;
  45159. this._vertex.x += this._particle.pivot.x;
  45160. this._vertex.y += this._particle.pivot.y;
  45161. this._vertex.z += this._particle.pivot.z;
  45162. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45163. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45164. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45165. 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;
  45166. 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;
  45167. 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;
  45168. if (this._computeBoundingBox) {
  45169. if (this._positions32[idx] < this._minimum.x) {
  45170. this._minimum.x = this._positions32[idx];
  45171. }
  45172. if (this._positions32[idx] > this._maximum.x) {
  45173. this._maximum.x = this._positions32[idx];
  45174. }
  45175. if (this._positions32[idx + 1] < this._minimum.y) {
  45176. this._minimum.y = this._positions32[idx + 1];
  45177. }
  45178. if (this._positions32[idx + 1] > this._maximum.y) {
  45179. this._maximum.y = this._positions32[idx + 1];
  45180. }
  45181. if (this._positions32[idx + 2] < this._minimum.z) {
  45182. this._minimum.z = this._positions32[idx + 2];
  45183. }
  45184. if (this._positions32[idx + 2] > this._maximum.z) {
  45185. this._maximum.z = this._positions32[idx + 2];
  45186. }
  45187. }
  45188. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45189. if (!this._computeParticleVertex) {
  45190. this._normal.x = this._fixedNormal32[idx];
  45191. this._normal.y = this._fixedNormal32[idx + 1];
  45192. this._normal.z = this._fixedNormal32[idx + 2];
  45193. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45194. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45195. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45196. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45197. 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;
  45198. 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;
  45199. }
  45200. if (this._computeParticleColor && this._particle.color) {
  45201. this._colors32[colidx] = this._particle.color.r;
  45202. this._colors32[colidx + 1] = this._particle.color.g;
  45203. this._colors32[colidx + 2] = this._particle.color.b;
  45204. this._colors32[colidx + 3] = this._particle.color.a;
  45205. }
  45206. if (this._computeParticleTexture) {
  45207. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45208. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45209. }
  45210. }
  45211. }
  45212. else {
  45213. this._particle._stillInvisible = true; // mark the particle as invisible
  45214. for (pt = 0; pt < this._shape.length; pt++) {
  45215. idx = index + pt * 3;
  45216. colidx = colorIndex + pt * 4;
  45217. uvidx = uvIndex + pt * 2;
  45218. this._positions32[idx] = 0.0;
  45219. this._positions32[idx + 1] = 0.0;
  45220. this._positions32[idx + 2] = 0.0;
  45221. this._normals32[idx] = 0.0;
  45222. this._normals32[idx + 1] = 0.0;
  45223. this._normals32[idx + 2] = 0.0;
  45224. if (this._computeParticleColor && this._particle.color) {
  45225. this._colors32[colidx] = this._particle.color.r;
  45226. this._colors32[colidx + 1] = this._particle.color.g;
  45227. this._colors32[colidx + 2] = this._particle.color.b;
  45228. this._colors32[colidx + 3] = this._particle.color.a;
  45229. }
  45230. if (this._computeParticleTexture) {
  45231. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45232. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45233. }
  45234. }
  45235. }
  45236. // if the particle intersections must be computed : update the bbInfo
  45237. if (this._particlesIntersect) {
  45238. var bInfo = this._particle._boundingInfo;
  45239. var bBox = bInfo.boundingBox;
  45240. var bSphere = bInfo.boundingSphere;
  45241. if (!this._bSphereOnly) {
  45242. // place, scale and rotate the particle bbox within the SPS local system, then update it
  45243. for (var b = 0; b < bBox.vectors.length; b++) {
  45244. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  45245. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  45246. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  45247. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45248. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45249. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45250. 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;
  45251. 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;
  45252. 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;
  45253. }
  45254. bBox._update(this.mesh._worldMatrix);
  45255. }
  45256. // place and scale the particle bouding sphere in the SPS local system, then update it
  45257. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  45258. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  45259. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  45260. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  45261. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  45262. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  45263. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  45264. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  45265. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  45266. 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));
  45267. bSphere._update(this.mesh._worldMatrix);
  45268. }
  45269. // increment indexes for the next particle
  45270. index = idx + 3;
  45271. colorIndex = colidx + 4;
  45272. uvIndex = uvidx + 2;
  45273. }
  45274. // if the VBO must be updated
  45275. if (update) {
  45276. if (this._computeParticleColor) {
  45277. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  45278. }
  45279. if (this._computeParticleTexture) {
  45280. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  45281. }
  45282. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45283. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  45284. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  45285. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  45286. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  45287. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  45288. for (var i = 0; i < this._normals32.length; i++) {
  45289. this._fixedNormal32[i] = this._normals32[i];
  45290. }
  45291. }
  45292. if (!this.mesh.areNormalsFrozen) {
  45293. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  45294. }
  45295. }
  45296. if (this._depthSort && this._depthSortParticles) {
  45297. this.depthSortedParticles.sort(this._depthSortFunction);
  45298. var dspl = this.depthSortedParticles.length;
  45299. var sorted = 0;
  45300. var lind = 0;
  45301. var sind = 0;
  45302. var sid = 0;
  45303. for (sorted = 0; sorted < dspl; sorted++) {
  45304. lind = this.depthSortedParticles[sorted].indicesLength;
  45305. sind = this.depthSortedParticles[sorted].ind;
  45306. for (var i = 0; i < lind; i++) {
  45307. this._indices32[sid] = this._indices[sind + i];
  45308. sid++;
  45309. }
  45310. }
  45311. this.mesh.updateIndices(this._indices32);
  45312. }
  45313. }
  45314. if (this._computeBoundingBox) {
  45315. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  45316. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  45317. }
  45318. this.afterUpdateParticles(start, end, update);
  45319. return this;
  45320. };
  45321. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  45322. this._halfroll = this._roll * 0.5;
  45323. this._halfpitch = this._pitch * 0.5;
  45324. this._halfyaw = this._yaw * 0.5;
  45325. this._sinRoll = Math.sin(this._halfroll);
  45326. this._cosRoll = Math.cos(this._halfroll);
  45327. this._sinPitch = Math.sin(this._halfpitch);
  45328. this._cosPitch = Math.cos(this._halfpitch);
  45329. this._sinYaw = Math.sin(this._halfyaw);
  45330. this._cosYaw = Math.cos(this._halfyaw);
  45331. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  45332. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  45333. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  45334. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  45335. };
  45336. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  45337. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  45338. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  45339. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  45340. this._rotMatrix.m[3] = 0;
  45341. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  45342. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  45343. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  45344. this._rotMatrix.m[7] = 0;
  45345. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  45346. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  45347. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  45348. this._rotMatrix.m[11] = 0;
  45349. this._rotMatrix.m[12] = 0;
  45350. this._rotMatrix.m[13] = 0;
  45351. this._rotMatrix.m[14] = 0;
  45352. this._rotMatrix.m[15] = 1.0;
  45353. };
  45354. /**
  45355. * Disposes the SPS.
  45356. * Returns nothing.
  45357. */
  45358. SolidParticleSystem.prototype.dispose = function () {
  45359. this.mesh.dispose();
  45360. this.vars = null;
  45361. // drop references to internal big arrays for the GC
  45362. this._positions = null;
  45363. this._indices = null;
  45364. this._normals = null;
  45365. this._uvs = null;
  45366. this._colors = null;
  45367. this._indices32 = null;
  45368. this._positions32 = null;
  45369. this._normals32 = null;
  45370. this._fixedNormal32 = null;
  45371. this._uvs32 = null;
  45372. this._colors32 = null;
  45373. this.pickedParticles = null;
  45374. };
  45375. /**
  45376. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  45377. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45378. * Returns the SPS.
  45379. */
  45380. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  45381. if (!this._isVisibilityBoxLocked) {
  45382. this.mesh.refreshBoundingInfo();
  45383. }
  45384. return this;
  45385. };
  45386. /**
  45387. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  45388. * @param size the size (float) of the visibility box
  45389. * note : this doesn't lock the SPS mesh bounding box.
  45390. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45391. */
  45392. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  45393. var vis = size / 2;
  45394. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  45395. };
  45396. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  45397. // getter and setter
  45398. get: function () {
  45399. return this._alwaysVisible;
  45400. },
  45401. /**
  45402. * Sets the SPS as always visible or not
  45403. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45404. */
  45405. set: function (val) {
  45406. this._alwaysVisible = val;
  45407. this.mesh.alwaysSelectAsActiveMesh = val;
  45408. },
  45409. enumerable: true,
  45410. configurable: true
  45411. });
  45412. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  45413. get: function () {
  45414. return this._isVisibilityBoxLocked;
  45415. },
  45416. /**
  45417. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  45418. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45419. */
  45420. set: function (val) {
  45421. this._isVisibilityBoxLocked = val;
  45422. var boundingInfo = this.mesh.getBoundingInfo();
  45423. if (boundingInfo) {
  45424. boundingInfo.isLocked = val;
  45425. }
  45426. },
  45427. enumerable: true,
  45428. configurable: true
  45429. });
  45430. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  45431. // getters
  45432. get: function () {
  45433. return this._computeParticleRotation;
  45434. },
  45435. // Optimizer setters
  45436. /**
  45437. * Tells to `setParticles()` to compute the particle rotations or not.
  45438. * Default value : true. The SPS is faster when it's set to false.
  45439. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  45440. */
  45441. set: function (val) {
  45442. this._computeParticleRotation = val;
  45443. },
  45444. enumerable: true,
  45445. configurable: true
  45446. });
  45447. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  45448. get: function () {
  45449. return this._computeParticleColor;
  45450. },
  45451. /**
  45452. * Tells to `setParticles()` to compute the particle colors or not.
  45453. * Default value : true. The SPS is faster when it's set to false.
  45454. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  45455. */
  45456. set: function (val) {
  45457. this._computeParticleColor = val;
  45458. },
  45459. enumerable: true,
  45460. configurable: true
  45461. });
  45462. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  45463. get: function () {
  45464. return this._computeParticleTexture;
  45465. },
  45466. /**
  45467. * Tells to `setParticles()` to compute the particle textures or not.
  45468. * Default value : true. The SPS is faster when it's set to false.
  45469. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  45470. */
  45471. set: function (val) {
  45472. this._computeParticleTexture = val;
  45473. },
  45474. enumerable: true,
  45475. configurable: true
  45476. });
  45477. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  45478. get: function () {
  45479. return this._computeParticleVertex;
  45480. },
  45481. /**
  45482. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  45483. * Default value : false. The SPS is faster when it's set to false.
  45484. * Note : the particle custom vertex positions aren't stored values.
  45485. */
  45486. set: function (val) {
  45487. this._computeParticleVertex = val;
  45488. },
  45489. enumerable: true,
  45490. configurable: true
  45491. });
  45492. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  45493. get: function () {
  45494. return this._computeBoundingBox;
  45495. },
  45496. /**
  45497. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  45498. */
  45499. set: function (val) {
  45500. this._computeBoundingBox = val;
  45501. },
  45502. enumerable: true,
  45503. configurable: true
  45504. });
  45505. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  45506. get: function () {
  45507. return this._depthSortParticles;
  45508. },
  45509. /**
  45510. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  45511. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  45512. * Default : `true`
  45513. */
  45514. set: function (val) {
  45515. this._depthSortParticles = val;
  45516. },
  45517. enumerable: true,
  45518. configurable: true
  45519. });
  45520. // =======================================================================
  45521. // Particle behavior logic
  45522. // these following methods may be overwritten by the user to fit his needs
  45523. /**
  45524. * This function does nothing. It may be overwritten to set all the particle first values.
  45525. * The SPS doesn't call this function, you may have to call it by your own.
  45526. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45527. */
  45528. SolidParticleSystem.prototype.initParticles = function () {
  45529. };
  45530. /**
  45531. * This function does nothing. It may be overwritten to recycle a particle.
  45532. * The SPS doesn't call this function, you may have to call it by your own.
  45533. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45534. */
  45535. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  45536. return particle;
  45537. };
  45538. /**
  45539. * Updates a particle : this function should be overwritten by the user.
  45540. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  45541. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45542. * ex : just set a particle position or velocity and recycle conditions
  45543. */
  45544. SolidParticleSystem.prototype.updateParticle = function (particle) {
  45545. return particle;
  45546. };
  45547. /**
  45548. * Updates a vertex of a particle : it can be overwritten by the user.
  45549. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  45550. * @param particle the current particle
  45551. * @param vertex the current index of the current particle
  45552. * @param pt the index of the current vertex in the particle shape
  45553. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  45554. * ex : just set a vertex particle position
  45555. */
  45556. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  45557. return vertex;
  45558. };
  45559. /**
  45560. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  45561. * This does nothing and may be overwritten by the user.
  45562. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45563. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45564. * @param update the boolean update value actually passed to setParticles()
  45565. */
  45566. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  45567. };
  45568. /**
  45569. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  45570. * This will be passed three parameters.
  45571. * This does nothing and may be overwritten by the user.
  45572. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45573. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45574. * @param update the boolean update value actually passed to setParticles()
  45575. */
  45576. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  45577. };
  45578. return SolidParticleSystem;
  45579. }());
  45580. BABYLON.SolidParticleSystem = SolidParticleSystem;
  45581. })(BABYLON || (BABYLON = {}));
  45582. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  45583. var BABYLON;
  45584. (function (BABYLON) {
  45585. var GroundMesh = /** @class */ (function (_super) {
  45586. __extends(GroundMesh, _super);
  45587. function GroundMesh(name, scene) {
  45588. var _this = _super.call(this, name, scene) || this;
  45589. _this.generateOctree = false;
  45590. return _this;
  45591. }
  45592. GroundMesh.prototype.getClassName = function () {
  45593. return "GroundMesh";
  45594. };
  45595. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  45596. get: function () {
  45597. return Math.min(this._subdivisionsX, this._subdivisionsY);
  45598. },
  45599. enumerable: true,
  45600. configurable: true
  45601. });
  45602. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  45603. get: function () {
  45604. return this._subdivisionsX;
  45605. },
  45606. enumerable: true,
  45607. configurable: true
  45608. });
  45609. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  45610. get: function () {
  45611. return this._subdivisionsY;
  45612. },
  45613. enumerable: true,
  45614. configurable: true
  45615. });
  45616. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  45617. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  45618. this._subdivisionsX = chunksCount;
  45619. this._subdivisionsY = chunksCount;
  45620. this.subdivide(chunksCount);
  45621. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  45622. };
  45623. /**
  45624. * Returns a height (y) value in the Worl system :
  45625. * the ground altitude at the coordinates (x, z) expressed in the World system.
  45626. * Returns the ground y position if (x, z) are outside the ground surface.
  45627. */
  45628. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  45629. var world = this.getWorldMatrix();
  45630. var invMat = BABYLON.Tmp.Matrix[5];
  45631. world.invertToRef(invMat);
  45632. var tmpVect = BABYLON.Tmp.Vector3[8];
  45633. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  45634. x = tmpVect.x;
  45635. z = tmpVect.z;
  45636. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45637. return this.position.y;
  45638. }
  45639. if (!this._heightQuads || this._heightQuads.length == 0) {
  45640. this._initHeightQuads();
  45641. this._computeHeightQuads();
  45642. }
  45643. var facet = this._getFacetAt(x, z);
  45644. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  45645. // return y in the World system
  45646. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  45647. return tmpVect.y;
  45648. };
  45649. /**
  45650. * Returns a normalized vector (Vector3) orthogonal to the ground
  45651. * at the ground coordinates (x, z) expressed in the World system.
  45652. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  45653. */
  45654. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  45655. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  45656. this.getNormalAtCoordinatesToRef(x, z, normal);
  45657. return normal;
  45658. };
  45659. /**
  45660. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  45661. * at the ground coordinates (x, z) expressed in the World system.
  45662. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  45663. * Returns the GroundMesh.
  45664. */
  45665. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  45666. var world = this.getWorldMatrix();
  45667. var tmpMat = BABYLON.Tmp.Matrix[5];
  45668. world.invertToRef(tmpMat);
  45669. var tmpVect = BABYLON.Tmp.Vector3[8];
  45670. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  45671. x = tmpVect.x;
  45672. z = tmpVect.z;
  45673. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45674. return this;
  45675. }
  45676. if (!this._heightQuads || this._heightQuads.length == 0) {
  45677. this._initHeightQuads();
  45678. this._computeHeightQuads();
  45679. }
  45680. var facet = this._getFacetAt(x, z);
  45681. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  45682. return this;
  45683. };
  45684. /**
  45685. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  45686. * if the ground has been updated.
  45687. * This can be used in the render loop.
  45688. * Returns the GroundMesh.
  45689. */
  45690. GroundMesh.prototype.updateCoordinateHeights = function () {
  45691. if (!this._heightQuads || this._heightQuads.length == 0) {
  45692. this._initHeightQuads();
  45693. }
  45694. this._computeHeightQuads();
  45695. return this;
  45696. };
  45697. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  45698. GroundMesh.prototype._getFacetAt = function (x, z) {
  45699. // retrieve col and row from x, z coordinates in the ground local system
  45700. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  45701. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  45702. var quad = this._heightQuads[row * this._subdivisionsX + col];
  45703. var facet;
  45704. if (z < quad.slope.x * x + quad.slope.y) {
  45705. facet = quad.facet1;
  45706. }
  45707. else {
  45708. facet = quad.facet2;
  45709. }
  45710. return facet;
  45711. };
  45712. // Creates and populates the heightMap array with "facet" elements :
  45713. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  45714. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45715. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45716. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45717. // Returns the GroundMesh.
  45718. GroundMesh.prototype._initHeightQuads = function () {
  45719. var subdivisionsX = this._subdivisionsX;
  45720. var subdivisionsY = this._subdivisionsY;
  45721. this._heightQuads = new Array();
  45722. for (var row = 0; row < subdivisionsY; row++) {
  45723. for (var col = 0; col < subdivisionsX; col++) {
  45724. 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) };
  45725. this._heightQuads[row * subdivisionsX + col] = quad;
  45726. }
  45727. }
  45728. return this;
  45729. };
  45730. // Compute each quad element values and update the the heightMap array :
  45731. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45732. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45733. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45734. // Returns the GroundMesh.
  45735. GroundMesh.prototype._computeHeightQuads = function () {
  45736. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45737. if (!positions) {
  45738. return this;
  45739. }
  45740. var v1 = BABYLON.Tmp.Vector3[3];
  45741. var v2 = BABYLON.Tmp.Vector3[2];
  45742. var v3 = BABYLON.Tmp.Vector3[1];
  45743. var v4 = BABYLON.Tmp.Vector3[0];
  45744. var v1v2 = BABYLON.Tmp.Vector3[4];
  45745. var v1v3 = BABYLON.Tmp.Vector3[5];
  45746. var v1v4 = BABYLON.Tmp.Vector3[6];
  45747. var norm1 = BABYLON.Tmp.Vector3[7];
  45748. var norm2 = BABYLON.Tmp.Vector3[8];
  45749. var i = 0;
  45750. var j = 0;
  45751. var k = 0;
  45752. var cd = 0; // 2D slope coefficient : z = cd * x + h
  45753. var h = 0;
  45754. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  45755. var d2 = 0;
  45756. var subdivisionsX = this._subdivisionsX;
  45757. var subdivisionsY = this._subdivisionsY;
  45758. for (var row = 0; row < subdivisionsY; row++) {
  45759. for (var col = 0; col < subdivisionsX; col++) {
  45760. i = col * 3;
  45761. j = row * (subdivisionsX + 1) * 3;
  45762. k = (row + 1) * (subdivisionsX + 1) * 3;
  45763. v1.x = positions[j + i];
  45764. v1.y = positions[j + i + 1];
  45765. v1.z = positions[j + i + 2];
  45766. v2.x = positions[j + i + 3];
  45767. v2.y = positions[j + i + 4];
  45768. v2.z = positions[j + i + 5];
  45769. v3.x = positions[k + i];
  45770. v3.y = positions[k + i + 1];
  45771. v3.z = positions[k + i + 2];
  45772. v4.x = positions[k + i + 3];
  45773. v4.y = positions[k + i + 4];
  45774. v4.z = positions[k + i + 5];
  45775. // 2D slope V1V4
  45776. cd = (v4.z - v1.z) / (v4.x - v1.x);
  45777. h = v1.z - cd * v1.x; // v1 belongs to the slope
  45778. // facet equations :
  45779. // we compute each facet normal vector
  45780. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  45781. // we compute the value d by applying the equation to v1 which belongs to the plane
  45782. // then we store the facet equation in a Vector4
  45783. v2.subtractToRef(v1, v1v2);
  45784. v3.subtractToRef(v1, v1v3);
  45785. v4.subtractToRef(v1, v1v4);
  45786. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  45787. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  45788. norm1.normalize();
  45789. norm2.normalize();
  45790. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  45791. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  45792. var quad = this._heightQuads[row * subdivisionsX + col];
  45793. quad.slope.copyFromFloats(cd, h);
  45794. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  45795. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  45796. }
  45797. }
  45798. return this;
  45799. };
  45800. GroundMesh.prototype.serialize = function (serializationObject) {
  45801. _super.prototype.serialize.call(this, serializationObject);
  45802. serializationObject.subdivisionsX = this._subdivisionsX;
  45803. serializationObject.subdivisionsY = this._subdivisionsY;
  45804. serializationObject.minX = this._minX;
  45805. serializationObject.maxX = this._maxX;
  45806. serializationObject.minZ = this._minZ;
  45807. serializationObject.maxZ = this._maxZ;
  45808. serializationObject.width = this._width;
  45809. serializationObject.height = this._height;
  45810. };
  45811. GroundMesh.Parse = function (parsedMesh, scene) {
  45812. var result = new GroundMesh(parsedMesh.name, scene);
  45813. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  45814. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  45815. result._minX = parsedMesh.minX;
  45816. result._maxX = parsedMesh.maxX;
  45817. result._minZ = parsedMesh.minZ;
  45818. result._maxZ = parsedMesh.maxZ;
  45819. result._width = parsedMesh.width;
  45820. result._height = parsedMesh.height;
  45821. return result;
  45822. };
  45823. return GroundMesh;
  45824. }(BABYLON.Mesh));
  45825. BABYLON.GroundMesh = GroundMesh;
  45826. })(BABYLON || (BABYLON = {}));
  45827. //# sourceMappingURL=babylon.groundMesh.js.map
  45828. var BABYLON;
  45829. (function (BABYLON) {
  45830. /**
  45831. * Creates an instance based on a source mesh.
  45832. */
  45833. var InstancedMesh = /** @class */ (function (_super) {
  45834. __extends(InstancedMesh, _super);
  45835. function InstancedMesh(name, source) {
  45836. var _this = _super.call(this, name, source.getScene()) || this;
  45837. source.instances.push(_this);
  45838. _this._sourceMesh = source;
  45839. _this.position.copyFrom(source.position);
  45840. _this.rotation.copyFrom(source.rotation);
  45841. _this.scaling.copyFrom(source.scaling);
  45842. if (source.rotationQuaternion) {
  45843. _this.rotationQuaternion = source.rotationQuaternion.clone();
  45844. }
  45845. _this.infiniteDistance = source.infiniteDistance;
  45846. _this.setPivotMatrix(source.getPivotMatrix());
  45847. _this.refreshBoundingInfo();
  45848. _this._syncSubMeshes();
  45849. return _this;
  45850. }
  45851. /**
  45852. * Returns the string "InstancedMesh".
  45853. */
  45854. InstancedMesh.prototype.getClassName = function () {
  45855. return "InstancedMesh";
  45856. };
  45857. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  45858. // Methods
  45859. get: function () {
  45860. return this._sourceMesh.receiveShadows;
  45861. },
  45862. enumerable: true,
  45863. configurable: true
  45864. });
  45865. Object.defineProperty(InstancedMesh.prototype, "material", {
  45866. get: function () {
  45867. return this._sourceMesh.material;
  45868. },
  45869. enumerable: true,
  45870. configurable: true
  45871. });
  45872. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  45873. get: function () {
  45874. return this._sourceMesh.visibility;
  45875. },
  45876. enumerable: true,
  45877. configurable: true
  45878. });
  45879. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  45880. get: function () {
  45881. return this._sourceMesh.skeleton;
  45882. },
  45883. enumerable: true,
  45884. configurable: true
  45885. });
  45886. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  45887. get: function () {
  45888. return this._sourceMesh.renderingGroupId;
  45889. },
  45890. enumerable: true,
  45891. configurable: true
  45892. });
  45893. /**
  45894. * Returns the total number of vertices (integer).
  45895. */
  45896. InstancedMesh.prototype.getTotalVertices = function () {
  45897. return this._sourceMesh.getTotalVertices();
  45898. };
  45899. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  45900. get: function () {
  45901. return this._sourceMesh;
  45902. },
  45903. enumerable: true,
  45904. configurable: true
  45905. });
  45906. /**
  45907. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  45908. */
  45909. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  45910. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  45911. };
  45912. /**
  45913. * Sets the vertex data of the mesh geometry for the requested `kind`.
  45914. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  45915. * The `data` are either a numeric array either a Float32Array.
  45916. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  45917. * 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).
  45918. * Note that a new underlying VertexBuffer object is created each call.
  45919. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  45920. *
  45921. * Possible `kind` values :
  45922. * - BABYLON.VertexBuffer.PositionKind
  45923. * - BABYLON.VertexBuffer.UVKind
  45924. * - BABYLON.VertexBuffer.UV2Kind
  45925. * - BABYLON.VertexBuffer.UV3Kind
  45926. * - BABYLON.VertexBuffer.UV4Kind
  45927. * - BABYLON.VertexBuffer.UV5Kind
  45928. * - BABYLON.VertexBuffer.UV6Kind
  45929. * - BABYLON.VertexBuffer.ColorKind
  45930. * - BABYLON.VertexBuffer.MatricesIndicesKind
  45931. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  45932. * - BABYLON.VertexBuffer.MatricesWeightsKind
  45933. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  45934. *
  45935. * Returns the Mesh.
  45936. */
  45937. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  45938. if (this.sourceMesh) {
  45939. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  45940. }
  45941. return this.sourceMesh;
  45942. };
  45943. /**
  45944. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  45945. * If the mesh has no geometry, it is simply returned as it is.
  45946. * The `data` are either a numeric array either a Float32Array.
  45947. * No new underlying VertexBuffer object is created.
  45948. * 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.
  45949. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  45950. *
  45951. * Possible `kind` values :
  45952. * - BABYLON.VertexBuffer.PositionKind
  45953. * - BABYLON.VertexBuffer.UVKind
  45954. * - BABYLON.VertexBuffer.UV2Kind
  45955. * - BABYLON.VertexBuffer.UV3Kind
  45956. * - BABYLON.VertexBuffer.UV4Kind
  45957. * - BABYLON.VertexBuffer.UV5Kind
  45958. * - BABYLON.VertexBuffer.UV6Kind
  45959. * - BABYLON.VertexBuffer.ColorKind
  45960. * - BABYLON.VertexBuffer.MatricesIndicesKind
  45961. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  45962. * - BABYLON.VertexBuffer.MatricesWeightsKind
  45963. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  45964. *
  45965. * Returns the Mesh.
  45966. */
  45967. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  45968. if (this.sourceMesh) {
  45969. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  45970. }
  45971. return this.sourceMesh;
  45972. };
  45973. /**
  45974. * Sets the mesh indices.
  45975. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  45976. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  45977. * This method creates a new index buffer each call.
  45978. * Returns the Mesh.
  45979. */
  45980. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  45981. if (totalVertices === void 0) { totalVertices = null; }
  45982. if (this.sourceMesh) {
  45983. this.sourceMesh.setIndices(indices, totalVertices);
  45984. }
  45985. return this.sourceMesh;
  45986. };
  45987. /**
  45988. * Boolean : True if the mesh owns the requested kind of data.
  45989. */
  45990. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  45991. return this._sourceMesh.isVerticesDataPresent(kind);
  45992. };
  45993. /**
  45994. * Returns an array of indices (IndicesArray).
  45995. */
  45996. InstancedMesh.prototype.getIndices = function () {
  45997. return this._sourceMesh.getIndices();
  45998. };
  45999. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46000. get: function () {
  46001. return this._sourceMesh._positions;
  46002. },
  46003. enumerable: true,
  46004. configurable: true
  46005. });
  46006. /**
  46007. * Sets a new updated BoundingInfo to the mesh.
  46008. * Returns the mesh.
  46009. */
  46010. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46011. var meshBB = this._sourceMesh.getBoundingInfo();
  46012. if (meshBB) {
  46013. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46014. }
  46015. this._updateBoundingInfo();
  46016. return this;
  46017. };
  46018. InstancedMesh.prototype._preActivate = function () {
  46019. if (this._currentLOD) {
  46020. this._currentLOD._preActivate();
  46021. }
  46022. return this;
  46023. };
  46024. InstancedMesh.prototype._activate = function (renderId) {
  46025. if (this._currentLOD) {
  46026. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46027. }
  46028. return this;
  46029. };
  46030. /**
  46031. * Returns the current associated LOD AbstractMesh.
  46032. */
  46033. InstancedMesh.prototype.getLOD = function (camera) {
  46034. if (!camera) {
  46035. return this;
  46036. }
  46037. var boundingInfo = this.getBoundingInfo();
  46038. if (!boundingInfo) {
  46039. return this;
  46040. }
  46041. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46042. if (this._currentLOD === this.sourceMesh) {
  46043. return this;
  46044. }
  46045. return this._currentLOD;
  46046. };
  46047. InstancedMesh.prototype._syncSubMeshes = function () {
  46048. this.releaseSubMeshes();
  46049. if (this._sourceMesh.subMeshes) {
  46050. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46051. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46052. }
  46053. }
  46054. return this;
  46055. };
  46056. InstancedMesh.prototype._generatePointsArray = function () {
  46057. return this._sourceMesh._generatePointsArray();
  46058. };
  46059. /**
  46060. * Creates a new InstancedMesh from the current mesh.
  46061. * - name (string) : the cloned mesh name
  46062. * - newParent (optional Node) : the optional Node to parent the clone to.
  46063. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46064. *
  46065. * Returns the clone.
  46066. */
  46067. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46068. var result = this._sourceMesh.createInstance(name);
  46069. // Deep copy
  46070. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46071. // Bounding info
  46072. this.refreshBoundingInfo();
  46073. // Parent
  46074. if (newParent) {
  46075. result.parent = newParent;
  46076. }
  46077. if (!doNotCloneChildren) {
  46078. // Children
  46079. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46080. var mesh = this.getScene().meshes[index];
  46081. if (mesh.parent === this) {
  46082. mesh.clone(mesh.name, result);
  46083. }
  46084. }
  46085. }
  46086. result.computeWorldMatrix(true);
  46087. return result;
  46088. };
  46089. /**
  46090. * Disposes the InstancedMesh.
  46091. * Returns nothing.
  46092. */
  46093. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46094. // Remove from mesh
  46095. var index = this._sourceMesh.instances.indexOf(this);
  46096. this._sourceMesh.instances.splice(index, 1);
  46097. _super.prototype.dispose.call(this, doNotRecurse);
  46098. };
  46099. return InstancedMesh;
  46100. }(BABYLON.AbstractMesh));
  46101. BABYLON.InstancedMesh = InstancedMesh;
  46102. })(BABYLON || (BABYLON = {}));
  46103. //# sourceMappingURL=babylon.instancedMesh.js.map
  46104. var BABYLON;
  46105. (function (BABYLON) {
  46106. var LinesMesh = /** @class */ (function (_super) {
  46107. __extends(LinesMesh, _super);
  46108. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  46109. if (scene === void 0) { scene = null; }
  46110. if (parent === void 0) { parent = null; }
  46111. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46112. _this.useVertexColor = useVertexColor;
  46113. _this.color = new BABYLON.Color3(1, 1, 1);
  46114. _this.alpha = 1;
  46115. if (source) {
  46116. _this.color = source.color.clone();
  46117. _this.alpha = source.alpha;
  46118. _this.useVertexColor = source.useVertexColor;
  46119. }
  46120. _this._intersectionThreshold = 0.1;
  46121. var options = {
  46122. attributes: [BABYLON.VertexBuffer.PositionKind],
  46123. uniforms: ["world", "viewProjection"],
  46124. needAlphaBlending: false,
  46125. };
  46126. if (!useVertexColor) {
  46127. options.uniforms.push("color");
  46128. options.needAlphaBlending = true;
  46129. }
  46130. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46131. return _this;
  46132. }
  46133. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46134. /**
  46135. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46136. * This margin is expressed in world space coordinates, so its value may vary.
  46137. * Default value is 0.1
  46138. * @returns the intersection Threshold value.
  46139. */
  46140. get: function () {
  46141. return this._intersectionThreshold;
  46142. },
  46143. /**
  46144. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46145. * This margin is expressed in world space coordinates, so its value may vary.
  46146. * @param value the new threshold to apply
  46147. */
  46148. set: function (value) {
  46149. if (this._intersectionThreshold === value) {
  46150. return;
  46151. }
  46152. this._intersectionThreshold = value;
  46153. if (this.geometry) {
  46154. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46155. }
  46156. },
  46157. enumerable: true,
  46158. configurable: true
  46159. });
  46160. /**
  46161. * Returns the string "LineMesh"
  46162. */
  46163. LinesMesh.prototype.getClassName = function () {
  46164. return "LinesMesh";
  46165. };
  46166. Object.defineProperty(LinesMesh.prototype, "material", {
  46167. get: function () {
  46168. return this._colorShader;
  46169. },
  46170. enumerable: true,
  46171. configurable: true
  46172. });
  46173. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46174. get: function () {
  46175. return false;
  46176. },
  46177. enumerable: true,
  46178. configurable: true
  46179. });
  46180. LinesMesh.prototype.createInstance = function (name) {
  46181. throw new Error("LinesMeshes do not support createInstance.");
  46182. };
  46183. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46184. if (!this._geometry) {
  46185. return this;
  46186. }
  46187. // VBOs
  46188. this._geometry._bind(this._colorShader.getEffect());
  46189. // Color
  46190. if (!this.useVertexColor) {
  46191. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46192. }
  46193. return this;
  46194. };
  46195. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46196. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46197. return this;
  46198. }
  46199. var engine = this.getScene().getEngine();
  46200. // Draw order
  46201. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46202. return this;
  46203. };
  46204. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46205. this._colorShader.dispose();
  46206. _super.prototype.dispose.call(this, doNotRecurse);
  46207. };
  46208. /**
  46209. * Returns a new LineMesh object cloned from the current one.
  46210. */
  46211. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46212. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  46213. };
  46214. return LinesMesh;
  46215. }(BABYLON.Mesh));
  46216. BABYLON.LinesMesh = LinesMesh;
  46217. })(BABYLON || (BABYLON = {}));
  46218. //# sourceMappingURL=babylon.linesMesh.js.map
  46219. var BABYLON;
  46220. (function (BABYLON) {
  46221. var ShaderMaterial = /** @class */ (function (_super) {
  46222. __extends(ShaderMaterial, _super);
  46223. function ShaderMaterial(name, scene, shaderPath, options) {
  46224. var _this = _super.call(this, name, scene) || this;
  46225. _this._textures = {};
  46226. _this._textureArrays = {};
  46227. _this._floats = {};
  46228. _this._floatsArrays = {};
  46229. _this._colors3 = {};
  46230. _this._colors3Arrays = {};
  46231. _this._colors4 = {};
  46232. _this._vectors2 = {};
  46233. _this._vectors3 = {};
  46234. _this._vectors4 = {};
  46235. _this._matrices = {};
  46236. _this._matrices3x3 = {};
  46237. _this._matrices2x2 = {};
  46238. _this._vectors3Arrays = {};
  46239. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46240. _this._shaderPath = shaderPath;
  46241. options.needAlphaBlending = options.needAlphaBlending || false;
  46242. options.needAlphaTesting = options.needAlphaTesting || false;
  46243. options.attributes = options.attributes || ["position", "normal", "uv"];
  46244. options.uniforms = options.uniforms || ["worldViewProjection"];
  46245. options.uniformBuffers = options.uniformBuffers || [];
  46246. options.samplers = options.samplers || [];
  46247. options.defines = options.defines || [];
  46248. _this._options = options;
  46249. return _this;
  46250. }
  46251. ShaderMaterial.prototype.getClassName = function () {
  46252. return "ShaderMaterial";
  46253. };
  46254. ShaderMaterial.prototype.needAlphaBlending = function () {
  46255. return this._options.needAlphaBlending;
  46256. };
  46257. ShaderMaterial.prototype.needAlphaTesting = function () {
  46258. return this._options.needAlphaTesting;
  46259. };
  46260. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46261. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46262. this._options.uniforms.push(uniformName);
  46263. }
  46264. };
  46265. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46266. if (this._options.samplers.indexOf(name) === -1) {
  46267. this._options.samplers.push(name);
  46268. }
  46269. this._textures[name] = texture;
  46270. return this;
  46271. };
  46272. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46273. if (this._options.samplers.indexOf(name) === -1) {
  46274. this._options.samplers.push(name);
  46275. }
  46276. this._checkUniform(name);
  46277. this._textureArrays[name] = textures;
  46278. return this;
  46279. };
  46280. ShaderMaterial.prototype.setFloat = function (name, value) {
  46281. this._checkUniform(name);
  46282. this._floats[name] = value;
  46283. return this;
  46284. };
  46285. ShaderMaterial.prototype.setFloats = function (name, value) {
  46286. this._checkUniform(name);
  46287. this._floatsArrays[name] = value;
  46288. return this;
  46289. };
  46290. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46291. this._checkUniform(name);
  46292. this._colors3[name] = value;
  46293. return this;
  46294. };
  46295. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  46296. this._checkUniform(name);
  46297. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  46298. color.toArray(arr, arr.length);
  46299. return arr;
  46300. }, []);
  46301. return this;
  46302. };
  46303. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46304. this._checkUniform(name);
  46305. this._colors4[name] = value;
  46306. return this;
  46307. };
  46308. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46309. this._checkUniform(name);
  46310. this._vectors2[name] = value;
  46311. return this;
  46312. };
  46313. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46314. this._checkUniform(name);
  46315. this._vectors3[name] = value;
  46316. return this;
  46317. };
  46318. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46319. this._checkUniform(name);
  46320. this._vectors4[name] = value;
  46321. return this;
  46322. };
  46323. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46324. this._checkUniform(name);
  46325. this._matrices[name] = value;
  46326. return this;
  46327. };
  46328. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46329. this._checkUniform(name);
  46330. this._matrices3x3[name] = value;
  46331. return this;
  46332. };
  46333. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46334. this._checkUniform(name);
  46335. this._matrices2x2[name] = value;
  46336. return this;
  46337. };
  46338. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46339. this._checkUniform(name);
  46340. this._vectors3Arrays[name] = value;
  46341. return this;
  46342. };
  46343. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46344. if (!mesh) {
  46345. return true;
  46346. }
  46347. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46348. return false;
  46349. }
  46350. return false;
  46351. };
  46352. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46353. var scene = this.getScene();
  46354. var engine = scene.getEngine();
  46355. if (!this.checkReadyOnEveryCall) {
  46356. if (this._renderId === scene.getRenderId()) {
  46357. if (this._checkCache(scene, mesh, useInstances)) {
  46358. return true;
  46359. }
  46360. }
  46361. }
  46362. // Instances
  46363. var defines = [];
  46364. var attribs = [];
  46365. var fallbacks = new BABYLON.EffectFallbacks();
  46366. if (useInstances) {
  46367. defines.push("#define INSTANCES");
  46368. }
  46369. for (var index = 0; index < this._options.defines.length; index++) {
  46370. defines.push(this._options.defines[index]);
  46371. }
  46372. for (var index = 0; index < this._options.attributes.length; index++) {
  46373. attribs.push(this._options.attributes[index]);
  46374. }
  46375. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  46376. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46377. defines.push("#define VERTEXCOLOR");
  46378. }
  46379. // Bones
  46380. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  46381. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46382. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46383. if (mesh.numBoneInfluencers > 4) {
  46384. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46385. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46386. }
  46387. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46388. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46389. fallbacks.addCPUSkinningFallback(0, mesh);
  46390. if (this._options.uniforms.indexOf("mBones") === -1) {
  46391. this._options.uniforms.push("mBones");
  46392. }
  46393. }
  46394. else {
  46395. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46396. }
  46397. // Textures
  46398. for (var name in this._textures) {
  46399. if (!this._textures[name].isReady()) {
  46400. return false;
  46401. }
  46402. }
  46403. // Alpha test
  46404. if (engine.getAlphaTesting()) {
  46405. defines.push("#define ALPHATEST");
  46406. }
  46407. var previousEffect = this._effect;
  46408. var join = defines.join("\n");
  46409. this._effect = engine.createEffect(this._shaderPath, {
  46410. attributes: attribs,
  46411. uniformsNames: this._options.uniforms,
  46412. uniformBuffersNames: this._options.uniformBuffers,
  46413. samplers: this._options.samplers,
  46414. defines: join,
  46415. fallbacks: fallbacks,
  46416. onCompiled: this.onCompiled,
  46417. onError: this.onError
  46418. }, engine);
  46419. if (!this._effect.isReady()) {
  46420. return false;
  46421. }
  46422. if (previousEffect !== this._effect) {
  46423. scene.resetCachedMaterial();
  46424. }
  46425. this._renderId = scene.getRenderId();
  46426. return true;
  46427. };
  46428. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46429. var scene = this.getScene();
  46430. if (!this._effect) {
  46431. return;
  46432. }
  46433. if (this._options.uniforms.indexOf("world") !== -1) {
  46434. this._effect.setMatrix("world", world);
  46435. }
  46436. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46437. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46438. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46439. }
  46440. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46441. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46442. }
  46443. };
  46444. ShaderMaterial.prototype.bind = function (world, mesh) {
  46445. // Std values
  46446. this.bindOnlyWorldMatrix(world);
  46447. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  46448. if (this._options.uniforms.indexOf("view") !== -1) {
  46449. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46450. }
  46451. if (this._options.uniforms.indexOf("projection") !== -1) {
  46452. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46453. }
  46454. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46455. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46456. }
  46457. // Bones
  46458. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46459. var name;
  46460. // Texture
  46461. for (name in this._textures) {
  46462. this._effect.setTexture(name, this._textures[name]);
  46463. }
  46464. // Texture arrays
  46465. for (name in this._textureArrays) {
  46466. this._effect.setTextureArray(name, this._textureArrays[name]);
  46467. }
  46468. // Float
  46469. for (name in this._floats) {
  46470. this._effect.setFloat(name, this._floats[name]);
  46471. }
  46472. // Float s
  46473. for (name in this._floatsArrays) {
  46474. this._effect.setArray(name, this._floatsArrays[name]);
  46475. }
  46476. // Color3
  46477. for (name in this._colors3) {
  46478. this._effect.setColor3(name, this._colors3[name]);
  46479. }
  46480. for (name in this._colors3Arrays) {
  46481. this._effect.setArray3(name, this._colors3Arrays[name]);
  46482. }
  46483. // Color4
  46484. for (name in this._colors4) {
  46485. var color = this._colors4[name];
  46486. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46487. }
  46488. // Vector2
  46489. for (name in this._vectors2) {
  46490. this._effect.setVector2(name, this._vectors2[name]);
  46491. }
  46492. // Vector3
  46493. for (name in this._vectors3) {
  46494. this._effect.setVector3(name, this._vectors3[name]);
  46495. }
  46496. // Vector4
  46497. for (name in this._vectors4) {
  46498. this._effect.setVector4(name, this._vectors4[name]);
  46499. }
  46500. // Matrix
  46501. for (name in this._matrices) {
  46502. this._effect.setMatrix(name, this._matrices[name]);
  46503. }
  46504. // Matrix 3x3
  46505. for (name in this._matrices3x3) {
  46506. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46507. }
  46508. // Matrix 2x2
  46509. for (name in this._matrices2x2) {
  46510. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46511. }
  46512. // Vector3Array
  46513. for (name in this._vectors3Arrays) {
  46514. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46515. }
  46516. }
  46517. this._afterBind(mesh);
  46518. };
  46519. ShaderMaterial.prototype.getActiveTextures = function () {
  46520. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46521. for (var name in this._textures) {
  46522. activeTextures.push(this._textures[name]);
  46523. }
  46524. for (var name in this._textureArrays) {
  46525. var array = this._textureArrays[name];
  46526. for (var index = 0; index < array.length; index++) {
  46527. activeTextures.push(array[index]);
  46528. }
  46529. }
  46530. return activeTextures;
  46531. };
  46532. ShaderMaterial.prototype.hasTexture = function (texture) {
  46533. if (_super.prototype.hasTexture.call(this, texture)) {
  46534. return true;
  46535. }
  46536. for (var name in this._textures) {
  46537. if (this._textures[name] === texture) {
  46538. return true;
  46539. }
  46540. }
  46541. for (var name in this._textureArrays) {
  46542. var array = this._textureArrays[name];
  46543. for (var index = 0; index < array.length; index++) {
  46544. if (array[index] === texture) {
  46545. return true;
  46546. }
  46547. }
  46548. }
  46549. return false;
  46550. };
  46551. ShaderMaterial.prototype.clone = function (name) {
  46552. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46553. return newShaderMaterial;
  46554. };
  46555. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46556. if (forceDisposeTextures) {
  46557. var name;
  46558. for (name in this._textures) {
  46559. this._textures[name].dispose();
  46560. }
  46561. for (name in this._textureArrays) {
  46562. var array = this._textureArrays[name];
  46563. for (var index = 0; index < array.length; index++) {
  46564. array[index].dispose();
  46565. }
  46566. }
  46567. }
  46568. this._textures = {};
  46569. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46570. };
  46571. ShaderMaterial.prototype.serialize = function () {
  46572. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46573. serializationObject.customType = "BABYLON.ShaderMaterial";
  46574. serializationObject.options = this._options;
  46575. serializationObject.shaderPath = this._shaderPath;
  46576. var name;
  46577. // Texture
  46578. serializationObject.textures = {};
  46579. for (name in this._textures) {
  46580. serializationObject.textures[name] = this._textures[name].serialize();
  46581. }
  46582. // Texture arrays
  46583. serializationObject.textureArrays = {};
  46584. for (name in this._textureArrays) {
  46585. serializationObject.textureArrays[name] = [];
  46586. var array = this._textureArrays[name];
  46587. for (var index = 0; index < array.length; index++) {
  46588. serializationObject.textureArrays[name].push(array[index].serialize());
  46589. }
  46590. }
  46591. // Float
  46592. serializationObject.floats = {};
  46593. for (name in this._floats) {
  46594. serializationObject.floats[name] = this._floats[name];
  46595. }
  46596. // Float s
  46597. serializationObject.FloatArrays = {};
  46598. for (name in this._floatsArrays) {
  46599. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  46600. }
  46601. // Color3
  46602. serializationObject.colors3 = {};
  46603. for (name in this._colors3) {
  46604. serializationObject.colors3[name] = this._colors3[name].asArray();
  46605. }
  46606. // Color3 array
  46607. serializationObject.colors3Arrays = {};
  46608. for (name in this._colors3Arrays) {
  46609. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  46610. }
  46611. // Color4
  46612. serializationObject.colors4 = {};
  46613. for (name in this._colors4) {
  46614. serializationObject.colors4[name] = this._colors4[name].asArray();
  46615. }
  46616. // Vector2
  46617. serializationObject.vectors2 = {};
  46618. for (name in this._vectors2) {
  46619. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46620. }
  46621. // Vector3
  46622. serializationObject.vectors3 = {};
  46623. for (name in this._vectors3) {
  46624. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46625. }
  46626. // Vector4
  46627. serializationObject.vectors4 = {};
  46628. for (name in this._vectors4) {
  46629. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46630. }
  46631. // Matrix
  46632. serializationObject.matrices = {};
  46633. for (name in this._matrices) {
  46634. serializationObject.matrices[name] = this._matrices[name].asArray();
  46635. }
  46636. // Matrix 3x3
  46637. serializationObject.matrices3x3 = {};
  46638. for (name in this._matrices3x3) {
  46639. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46640. }
  46641. // Matrix 2x2
  46642. serializationObject.matrices2x2 = {};
  46643. for (name in this._matrices2x2) {
  46644. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46645. }
  46646. // Vector3Array
  46647. serializationObject.vectors3Arrays = {};
  46648. for (name in this._vectors3Arrays) {
  46649. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46650. }
  46651. return serializationObject;
  46652. };
  46653. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46654. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46655. var name;
  46656. // Texture
  46657. for (name in source.textures) {
  46658. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46659. }
  46660. // Texture arrays
  46661. for (name in source.textureArrays) {
  46662. var array = source.textureArrays[name];
  46663. var textureArray = new Array();
  46664. for (var index = 0; index < array.length; index++) {
  46665. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46666. }
  46667. material.setTextureArray(name, textureArray);
  46668. }
  46669. // Float
  46670. for (name in source.floats) {
  46671. material.setFloat(name, source.floats[name]);
  46672. }
  46673. // Float s
  46674. for (name in source.floatsArrays) {
  46675. material.setFloats(name, source.floatsArrays[name]);
  46676. }
  46677. // Color3
  46678. for (name in source.colors3) {
  46679. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46680. }
  46681. // Color3 arrays
  46682. for (name in source.colors3Arrays) {
  46683. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  46684. if (i % 3 === 0) {
  46685. arr.push([num]);
  46686. }
  46687. else {
  46688. arr[arr.length - 1].push(num);
  46689. }
  46690. return arr;
  46691. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  46692. material.setColor3Array(name, colors);
  46693. }
  46694. // Color4
  46695. for (name in source.colors4) {
  46696. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46697. }
  46698. // Vector2
  46699. for (name in source.vectors2) {
  46700. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46701. }
  46702. // Vector3
  46703. for (name in source.vectors3) {
  46704. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46705. }
  46706. // Vector4
  46707. for (name in source.vectors4) {
  46708. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46709. }
  46710. // Matrix
  46711. for (name in source.matrices) {
  46712. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46713. }
  46714. // Matrix 3x3
  46715. for (name in source.matrices3x3) {
  46716. material.setMatrix3x3(name, source.matrices3x3[name]);
  46717. }
  46718. // Matrix 2x2
  46719. for (name in source.matrices2x2) {
  46720. material.setMatrix2x2(name, source.matrices2x2[name]);
  46721. }
  46722. // Vector3Array
  46723. for (name in source.vectors3Arrays) {
  46724. material.setArray3(name, source.vectors3Arrays[name]);
  46725. }
  46726. return material;
  46727. };
  46728. return ShaderMaterial;
  46729. }(BABYLON.Material));
  46730. BABYLON.ShaderMaterial = ShaderMaterial;
  46731. })(BABYLON || (BABYLON = {}));
  46732. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46733. var BABYLON;
  46734. (function (BABYLON) {
  46735. var MeshBuilder = /** @class */ (function () {
  46736. function MeshBuilder() {
  46737. }
  46738. MeshBuilder.updateSideOrientation = function (orientation) {
  46739. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  46740. return BABYLON.Mesh.DOUBLESIDE;
  46741. }
  46742. if (orientation === undefined || orientation === null) {
  46743. return BABYLON.Mesh.FRONTSIDE;
  46744. }
  46745. return orientation;
  46746. };
  46747. /**
  46748. * Creates a box mesh.
  46749. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  46750. * The parameter `size` sets the size (float) of each box side (default 1).
  46751. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  46752. * 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).
  46753. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46755. * 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).
  46756. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46758. */
  46759. MeshBuilder.CreateBox = function (name, options, scene) {
  46760. if (scene === void 0) { scene = null; }
  46761. var box = new BABYLON.Mesh(name, scene);
  46762. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46763. box._originalBuilderSideOrientation = options.sideOrientation;
  46764. var vertexData = BABYLON.VertexData.CreateBox(options);
  46765. vertexData.applyToMesh(box, options.updatable);
  46766. return box;
  46767. };
  46768. /**
  46769. * Creates a sphere mesh.
  46770. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  46771. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  46772. * 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`).
  46773. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  46774. * 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
  46775. * 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).
  46776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46777. * 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).
  46778. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46780. */
  46781. MeshBuilder.CreateSphere = function (name, options, scene) {
  46782. var sphere = new BABYLON.Mesh(name, scene);
  46783. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46784. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46785. var vertexData = BABYLON.VertexData.CreateSphere(options);
  46786. vertexData.applyToMesh(sphere, options.updatable);
  46787. return sphere;
  46788. };
  46789. /**
  46790. * Creates a plane polygonal mesh. By default, this is a disc.
  46791. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  46792. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  46793. * 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.
  46794. * 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
  46795. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46796. * 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).
  46797. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46799. */
  46800. MeshBuilder.CreateDisc = function (name, options, scene) {
  46801. if (scene === void 0) { scene = null; }
  46802. var disc = new BABYLON.Mesh(name, scene);
  46803. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46804. disc._originalBuilderSideOrientation = options.sideOrientation;
  46805. var vertexData = BABYLON.VertexData.CreateDisc(options);
  46806. vertexData.applyToMesh(disc, options.updatable);
  46807. return disc;
  46808. };
  46809. /**
  46810. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  46811. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  46812. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  46813. * 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`).
  46814. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  46815. * 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.
  46816. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46817. * 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).
  46818. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46820. */
  46821. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  46822. var sphere = new BABYLON.Mesh(name, scene);
  46823. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46824. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46825. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  46826. vertexData.applyToMesh(sphere, options.updatable);
  46827. return sphere;
  46828. };
  46829. ;
  46830. /**
  46831. * Creates a ribbon mesh.
  46832. * 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.
  46833. *
  46834. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  46835. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  46836. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  46837. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  46838. * 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.
  46839. * 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.
  46840. * 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
  46841. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46842. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  46843. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46844. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46845. * 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.
  46846. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  46847. * 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
  46848. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  46849. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  46850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46851. */
  46852. MeshBuilder.CreateRibbon = function (name, options, scene) {
  46853. if (scene === void 0) { scene = null; }
  46854. var pathArray = options.pathArray;
  46855. var closeArray = options.closeArray;
  46856. var closePath = options.closePath;
  46857. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46858. var instance = options.instance;
  46859. var updatable = options.updatable;
  46860. if (instance) {
  46861. // positionFunction : ribbon case
  46862. // only pathArray and sideOrientation parameters are taken into account for positions update
  46863. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  46864. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  46865. var positionFunction = function (positions) {
  46866. var minlg = pathArray[0].length;
  46867. var i = 0;
  46868. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  46869. for (var si = 1; si <= ns; si++) {
  46870. for (var p = 0; p < pathArray.length; p++) {
  46871. var path = pathArray[p];
  46872. var l = path.length;
  46873. minlg = (minlg < l) ? minlg : l;
  46874. var j = 0;
  46875. while (j < minlg) {
  46876. positions[i] = path[j].x;
  46877. positions[i + 1] = path[j].y;
  46878. positions[i + 2] = path[j].z;
  46879. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  46880. BABYLON.Tmp.Vector3[0].x = path[j].x;
  46881. }
  46882. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  46883. BABYLON.Tmp.Vector3[1].x = path[j].x;
  46884. }
  46885. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  46886. BABYLON.Tmp.Vector3[0].y = path[j].y;
  46887. }
  46888. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  46889. BABYLON.Tmp.Vector3[1].y = path[j].y;
  46890. }
  46891. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  46892. BABYLON.Tmp.Vector3[0].z = path[j].z;
  46893. }
  46894. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  46895. BABYLON.Tmp.Vector3[1].z = path[j].z;
  46896. }
  46897. j++;
  46898. i += 3;
  46899. }
  46900. if (instance._closePath) {
  46901. positions[i] = path[0].x;
  46902. positions[i + 1] = path[0].y;
  46903. positions[i + 2] = path[0].z;
  46904. i += 3;
  46905. }
  46906. }
  46907. }
  46908. };
  46909. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46910. positionFunction(positions);
  46911. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  46912. instance._boundingInfo.update(instance._worldMatrix);
  46913. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  46914. if (options.colors) {
  46915. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46916. for (var c = 0; c < options.colors.length; c++) {
  46917. colors[c * 4] = options.colors[c].r;
  46918. colors[c * 4 + 1] = options.colors[c].g;
  46919. colors[c * 4 + 2] = options.colors[c].b;
  46920. colors[c * 4 + 3] = options.colors[c].a;
  46921. }
  46922. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  46923. }
  46924. if (options.uvs) {
  46925. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46926. for (var i = 0; i < options.uvs.length; i++) {
  46927. uvs[i * 2] = options.uvs[i].x;
  46928. uvs[i * 2 + 1] = options.uvs[i].y;
  46929. }
  46930. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  46931. }
  46932. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  46933. var indices = instance.getIndices();
  46934. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46935. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  46936. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  46937. if (instance._closePath) {
  46938. var indexFirst = 0;
  46939. var indexLast = 0;
  46940. for (var p = 0; p < pathArray.length; p++) {
  46941. indexFirst = instance._idx[p] * 3;
  46942. if (p + 1 < pathArray.length) {
  46943. indexLast = (instance._idx[p + 1] - 1) * 3;
  46944. }
  46945. else {
  46946. indexLast = normals.length - 3;
  46947. }
  46948. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  46949. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  46950. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  46951. normals[indexLast] = normals[indexFirst];
  46952. normals[indexLast + 1] = normals[indexFirst + 1];
  46953. normals[indexLast + 2] = normals[indexFirst + 2];
  46954. }
  46955. }
  46956. if (!(instance.areNormalsFrozen)) {
  46957. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  46958. }
  46959. }
  46960. return instance;
  46961. }
  46962. else {
  46963. var ribbon = new BABYLON.Mesh(name, scene);
  46964. ribbon._originalBuilderSideOrientation = sideOrientation;
  46965. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  46966. if (closePath) {
  46967. ribbon._idx = vertexData._idx;
  46968. }
  46969. ribbon._closePath = closePath;
  46970. ribbon._closeArray = closeArray;
  46971. vertexData.applyToMesh(ribbon, updatable);
  46972. return ribbon;
  46973. }
  46974. };
  46975. /**
  46976. * Creates a cylinder or a cone mesh.
  46977. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  46978. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  46979. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  46980. * 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.
  46981. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  46982. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  46983. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  46984. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  46985. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  46986. * 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).
  46987. * 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
  46988. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  46989. * 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
  46990. * 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.
  46991. * If `enclose` is false, a ring surface is one element.
  46992. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  46993. * 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
  46994. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46995. * 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).
  46996. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46997. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46998. */
  46999. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47000. var cylinder = new BABYLON.Mesh(name, scene);
  47001. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47002. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47003. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47004. vertexData.applyToMesh(cylinder, options.updatable);
  47005. return cylinder;
  47006. };
  47007. /**
  47008. * Creates a torus mesh.
  47009. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47010. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47011. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47012. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47013. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47014. * 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).
  47015. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47016. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47017. */
  47018. MeshBuilder.CreateTorus = function (name, options, scene) {
  47019. var torus = new BABYLON.Mesh(name, scene);
  47020. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47021. torus._originalBuilderSideOrientation = options.sideOrientation;
  47022. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47023. vertexData.applyToMesh(torus, options.updatable);
  47024. return torus;
  47025. };
  47026. /**
  47027. * Creates a torus knot mesh.
  47028. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47029. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47030. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47031. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47032. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47033. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47034. * 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).
  47035. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47036. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47037. */
  47038. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47039. var torusKnot = new BABYLON.Mesh(name, scene);
  47040. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47041. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47042. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47043. vertexData.applyToMesh(torusKnot, options.updatable);
  47044. return torusKnot;
  47045. };
  47046. /**
  47047. * Creates a line system mesh.
  47048. * A line system is a pool of many lines gathered in a single mesh.
  47049. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47050. * 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.
  47051. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47052. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47053. * 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
  47054. * 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
  47055. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47056. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47057. */
  47058. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47059. var instance = options.instance;
  47060. var lines = options.lines;
  47061. if (instance) {
  47062. var positionFunction = function (positions) {
  47063. var i = 0;
  47064. for (var l = 0; l < lines.length; l++) {
  47065. var points = lines[l];
  47066. for (var p = 0; p < points.length; p++) {
  47067. positions[i] = points[p].x;
  47068. positions[i + 1] = points[p].y;
  47069. positions[i + 2] = points[p].z;
  47070. i += 3;
  47071. }
  47072. }
  47073. };
  47074. instance.updateMeshPositions(positionFunction, false);
  47075. return instance;
  47076. }
  47077. // line system creation
  47078. var lineSystem = new BABYLON.LinesMesh(name, scene);
  47079. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47080. vertexData.applyToMesh(lineSystem, options.updatable);
  47081. return lineSystem;
  47082. };
  47083. /**
  47084. * Creates a line mesh.
  47085. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47086. * 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.
  47087. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47088. * The parameter `points` is an array successive Vector3.
  47089. * 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
  47090. * When updating an instance, remember that only point positions can change, not the number of points.
  47091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47092. */
  47093. MeshBuilder.CreateLines = function (name, options, scene) {
  47094. if (scene === void 0) { scene = null; }
  47095. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  47096. return lines;
  47097. };
  47098. /**
  47099. * Creates a dashed line mesh.
  47100. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47101. * 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.
  47102. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47103. * The parameter `points` is an array successive Vector3.
  47104. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47105. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47106. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47107. * 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
  47108. * When updating an instance, remember that only point positions can change, not the number of points.
  47109. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47110. */
  47111. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47112. if (scene === void 0) { scene = null; }
  47113. var points = options.points;
  47114. var instance = options.instance;
  47115. var gapSize = options.gapSize || 1;
  47116. var dashSize = options.dashSize || 3;
  47117. if (instance) {
  47118. var positionFunction = function (positions) {
  47119. var curvect = BABYLON.Vector3.Zero();
  47120. var nbSeg = positions.length / 6;
  47121. var lg = 0;
  47122. var nb = 0;
  47123. var shft = 0;
  47124. var dashshft = 0;
  47125. var curshft = 0;
  47126. var p = 0;
  47127. var i = 0;
  47128. var j = 0;
  47129. for (i = 0; i < points.length - 1; i++) {
  47130. points[i + 1].subtractToRef(points[i], curvect);
  47131. lg += curvect.length();
  47132. }
  47133. shft = lg / nbSeg;
  47134. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47135. for (i = 0; i < points.length - 1; i++) {
  47136. points[i + 1].subtractToRef(points[i], curvect);
  47137. nb = Math.floor(curvect.length() / shft);
  47138. curvect.normalize();
  47139. j = 0;
  47140. while (j < nb && p < positions.length) {
  47141. curshft = shft * j;
  47142. positions[p] = points[i].x + curshft * curvect.x;
  47143. positions[p + 1] = points[i].y + curshft * curvect.y;
  47144. positions[p + 2] = points[i].z + curshft * curvect.z;
  47145. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47146. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47147. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47148. p += 6;
  47149. j++;
  47150. }
  47151. }
  47152. while (p < positions.length) {
  47153. positions[p] = points[i].x;
  47154. positions[p + 1] = points[i].y;
  47155. positions[p + 2] = points[i].z;
  47156. p += 3;
  47157. }
  47158. };
  47159. instance.updateMeshPositions(positionFunction, false);
  47160. return instance;
  47161. }
  47162. // dashed lines creation
  47163. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47164. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47165. vertexData.applyToMesh(dashedLines, options.updatable);
  47166. dashedLines.dashSize = dashSize;
  47167. dashedLines.gapSize = gapSize;
  47168. return dashedLines;
  47169. };
  47170. /**
  47171. * Creates an extruded shape mesh.
  47172. * 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.
  47173. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47174. *
  47175. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47176. * 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
  47177. * extruded along the Z axis.
  47178. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47179. * 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.
  47180. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47181. * 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
  47182. * 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
  47183. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47184. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47185. * 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).
  47186. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47187. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47188. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47189. */
  47190. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  47191. if (scene === void 0) { scene = null; }
  47192. var path = options.path;
  47193. var shape = options.shape;
  47194. var scale = options.scale || 1;
  47195. var rotation = options.rotation || 0;
  47196. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47197. var updatable = options.updatable;
  47198. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47199. var instance = options.instance || null;
  47200. var invertUV = options.invertUV || false;
  47201. 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);
  47202. };
  47203. /**
  47204. * Creates an custom extruded shape mesh.
  47205. * 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.
  47206. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  47207. *
  47208. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47209. * 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
  47210. * extruded along the Z axis.
  47211. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47212. * 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
  47213. * and the distance of this point from the begining of the path :
  47214. * ```javascript
  47215. * var rotationFunction = function(i, distance) {
  47216. * // do things
  47217. * return rotationValue; }
  47218. * ```
  47219. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  47220. * 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
  47221. * and the distance of this point from the begining of the path :
  47222. * ```javascript
  47223. * var scaleFunction = function(i, distance) {
  47224. * // do things
  47225. * return scaleValue;}
  47226. * ```
  47227. * It must returns a float value that will be the scale value applied to the shape on each path point.
  47228. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  47229. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  47230. * 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
  47231. * 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
  47232. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47233. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47234. * 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).
  47235. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47236. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47238. */
  47239. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  47240. var path = options.path;
  47241. var shape = options.shape;
  47242. var scaleFunction = options.scaleFunction || (function () { return 1; });
  47243. var rotationFunction = options.rotationFunction || (function () { return 0; });
  47244. var ribbonCloseArray = options.ribbonCloseArray || false;
  47245. var ribbonClosePath = options.ribbonClosePath || false;
  47246. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47247. var updatable = options.updatable;
  47248. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47249. var instance = options.instance;
  47250. var invertUV = options.invertUV || false;
  47251. 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);
  47252. };
  47253. /**
  47254. * Creates lathe mesh.
  47255. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  47256. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  47257. *
  47258. * 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
  47259. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  47260. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  47261. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  47262. * 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.
  47263. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  47264. * 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
  47265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47266. * 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).
  47267. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47268. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47269. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47270. */
  47271. MeshBuilder.CreateLathe = function (name, options, scene) {
  47272. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  47273. var closed = (options.closed === undefined) ? true : options.closed;
  47274. var shape = options.shape;
  47275. var radius = options.radius || 1;
  47276. var tessellation = options.tessellation || 64;
  47277. var updatable = options.updatable;
  47278. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47279. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47280. var pi2 = Math.PI * 2;
  47281. var paths = new Array();
  47282. var invertUV = options.invertUV || false;
  47283. var i = 0;
  47284. var p = 0;
  47285. var step = pi2 / tessellation * arc;
  47286. var rotated;
  47287. var path = new Array();
  47288. ;
  47289. for (i = 0; i <= tessellation; i++) {
  47290. var path = [];
  47291. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  47292. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  47293. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  47294. }
  47295. for (p = 0; p < shape.length; p++) {
  47296. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  47297. path.push(rotated);
  47298. }
  47299. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  47300. 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));
  47301. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  47302. }
  47303. paths.push(path);
  47304. }
  47305. // lathe ribbon
  47306. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47307. return lathe;
  47308. };
  47309. /**
  47310. * Creates a plane mesh.
  47311. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47312. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  47313. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  47314. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  47315. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47316. * 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).
  47317. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47318. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47319. */
  47320. MeshBuilder.CreatePlane = function (name, options, scene) {
  47321. var plane = new BABYLON.Mesh(name, scene);
  47322. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47323. plane._originalBuilderSideOrientation = options.sideOrientation;
  47324. var vertexData = BABYLON.VertexData.CreatePlane(options);
  47325. vertexData.applyToMesh(plane, options.updatable);
  47326. if (options.sourcePlane) {
  47327. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  47328. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  47329. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  47330. plane.rotate(vectorProduct, product);
  47331. }
  47332. return plane;
  47333. };
  47334. /**
  47335. * Creates a ground mesh.
  47336. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47337. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  47338. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  47339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47340. */
  47341. MeshBuilder.CreateGround = function (name, options, scene) {
  47342. var ground = new BABYLON.GroundMesh(name, scene);
  47343. ground._setReady(false);
  47344. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  47345. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  47346. ground._width = options.width || 1;
  47347. ground._height = options.height || 1;
  47348. ground._maxX = ground._width / 2;
  47349. ground._maxZ = ground._height / 2;
  47350. ground._minX = -ground._maxX;
  47351. ground._minZ = -ground._maxZ;
  47352. var vertexData = BABYLON.VertexData.CreateGround(options);
  47353. vertexData.applyToMesh(ground, options.updatable);
  47354. ground._setReady(true);
  47355. return ground;
  47356. };
  47357. /**
  47358. * Creates a tiled ground mesh.
  47359. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  47360. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  47361. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  47362. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  47363. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  47364. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  47365. * numbers of subdivisions on the ground width and height of each tile.
  47366. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47367. */
  47368. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  47369. var tiledGround = new BABYLON.Mesh(name, scene);
  47370. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  47371. vertexData.applyToMesh(tiledGround, options.updatable);
  47372. return tiledGround;
  47373. };
  47374. /**
  47375. * Creates a ground mesh from a height map.
  47376. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  47377. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  47378. * The parameter `url` sets the URL of the height map image resource.
  47379. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  47380. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  47381. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  47382. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  47383. * 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.
  47384. * 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).
  47385. * This function is passed the newly built mesh :
  47386. * ```javascript
  47387. * function(mesh) { // do things
  47388. * return; }
  47389. * ```
  47390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47391. */
  47392. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  47393. var width = options.width || 10.0;
  47394. var height = options.height || 10.0;
  47395. var subdivisions = options.subdivisions || 1 | 0;
  47396. var minHeight = options.minHeight || 0.0;
  47397. var maxHeight = options.maxHeight || 1.0;
  47398. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  47399. var updatable = options.updatable;
  47400. var onReady = options.onReady;
  47401. var ground = new BABYLON.GroundMesh(name, scene);
  47402. ground._subdivisionsX = subdivisions;
  47403. ground._subdivisionsY = subdivisions;
  47404. ground._width = width;
  47405. ground._height = height;
  47406. ground._maxX = ground._width / 2.0;
  47407. ground._maxZ = ground._height / 2.0;
  47408. ground._minX = -ground._maxX;
  47409. ground._minZ = -ground._maxZ;
  47410. ground._setReady(false);
  47411. var onload = function (img) {
  47412. // Getting height map data
  47413. var canvas = document.createElement("canvas");
  47414. var context = canvas.getContext("2d");
  47415. if (!context) {
  47416. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  47417. }
  47418. var bufferWidth = img.width;
  47419. var bufferHeight = img.height;
  47420. canvas.width = bufferWidth;
  47421. canvas.height = bufferHeight;
  47422. context.drawImage(img, 0, 0);
  47423. // Create VertexData from map data
  47424. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  47425. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  47426. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  47427. width: width, height: height,
  47428. subdivisions: subdivisions,
  47429. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  47430. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  47431. });
  47432. vertexData.applyToMesh(ground, updatable);
  47433. ground._setReady(true);
  47434. //execute ready callback, if set
  47435. if (onReady) {
  47436. onReady(ground);
  47437. }
  47438. };
  47439. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  47440. return ground;
  47441. };
  47442. /**
  47443. * Creates a polygon mesh.
  47444. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  47445. * 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.
  47446. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47447. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47448. * 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).
  47449. * Remember you can only change the shape positions, not their number when updating a polygon.
  47450. */
  47451. MeshBuilder.CreatePolygon = function (name, options, scene) {
  47452. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47453. var shape = options.shape;
  47454. var holes = options.holes || [];
  47455. var depth = options.depth || 0;
  47456. var contours = [];
  47457. var hole = [];
  47458. for (var i = 0; i < shape.length; i++) {
  47459. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  47460. }
  47461. var epsilon = 0.00000001;
  47462. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  47463. contours.pop();
  47464. }
  47465. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  47466. for (var hNb = 0; hNb < holes.length; hNb++) {
  47467. hole = [];
  47468. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  47469. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  47470. }
  47471. polygonTriangulation.addHole(hole);
  47472. }
  47473. var polygon = polygonTriangulation.build(options.updatable, depth);
  47474. polygon._originalBuilderSideOrientation = options.sideOrientation;
  47475. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  47476. vertexData.applyToMesh(polygon, options.updatable);
  47477. return polygon;
  47478. };
  47479. ;
  47480. /**
  47481. * Creates an extruded polygon mesh, with depth in the Y direction.
  47482. * 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).
  47483. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47484. */
  47485. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  47486. return MeshBuilder.CreatePolygon(name, options, scene);
  47487. };
  47488. ;
  47489. /**
  47490. * Creates a tube mesh.
  47491. * 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.
  47492. *
  47493. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  47494. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  47495. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  47496. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  47497. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  47498. * 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.
  47499. * It must return a radius value (positive float) :
  47500. * ```javascript
  47501. * var radiusFunction = function(i, distance) {
  47502. * // do things
  47503. * return radius; }
  47504. * ```
  47505. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  47506. * 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
  47507. * 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
  47508. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47509. * 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).
  47510. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47511. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47513. */
  47514. MeshBuilder.CreateTube = function (name, options, scene) {
  47515. var path = options.path;
  47516. var instance = options.instance;
  47517. var radius = 1.0;
  47518. if (instance) {
  47519. radius = instance.radius;
  47520. }
  47521. if (options.radius !== undefined) {
  47522. radius = options.radius;
  47523. }
  47524. ;
  47525. var tessellation = options.tessellation || 64 | 0;
  47526. var radiusFunction = options.radiusFunction || null;
  47527. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47528. var invertUV = options.invertUV || false;
  47529. var updatable = options.updatable;
  47530. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47531. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  47532. // tube geometry
  47533. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  47534. var tangents = path3D.getTangents();
  47535. var normals = path3D.getNormals();
  47536. var distances = path3D.getDistances();
  47537. var pi2 = Math.PI * 2;
  47538. var step = pi2 / tessellation * arc;
  47539. var returnRadius = function () { return radius; };
  47540. var radiusFunctionFinal = radiusFunction || returnRadius;
  47541. var circlePath;
  47542. var rad;
  47543. var normal;
  47544. var rotated;
  47545. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47546. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47547. for (var i = 0; i < path.length; i++) {
  47548. rad = radiusFunctionFinal(i, distances[i]); // current radius
  47549. circlePath = Array(); // current circle array
  47550. normal = normals[i]; // current normal
  47551. for (var t = 0; t < tessellation; t++) {
  47552. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  47553. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  47554. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  47555. rotated.scaleInPlace(rad).addInPlace(path[i]);
  47556. circlePath[t] = rotated;
  47557. }
  47558. circlePaths[index] = circlePath;
  47559. index++;
  47560. }
  47561. // cap
  47562. var capPath = function (nbPoints, pathIndex) {
  47563. var pointCap = Array();
  47564. for (var i = 0; i < nbPoints; i++) {
  47565. pointCap.push(path[pathIndex]);
  47566. }
  47567. return pointCap;
  47568. };
  47569. switch (cap) {
  47570. case BABYLON.Mesh.NO_CAP:
  47571. break;
  47572. case BABYLON.Mesh.CAP_START:
  47573. circlePaths[0] = capPath(tessellation, 0);
  47574. circlePaths[1] = circlePaths[2].slice(0);
  47575. break;
  47576. case BABYLON.Mesh.CAP_END:
  47577. circlePaths[index] = circlePaths[index - 1].slice(0);
  47578. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47579. break;
  47580. case BABYLON.Mesh.CAP_ALL:
  47581. circlePaths[0] = capPath(tessellation, 0);
  47582. circlePaths[1] = circlePaths[2].slice(0);
  47583. circlePaths[index] = circlePaths[index - 1].slice(0);
  47584. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47585. break;
  47586. default:
  47587. break;
  47588. }
  47589. return circlePaths;
  47590. };
  47591. var path3D;
  47592. var pathArray;
  47593. if (instance) {
  47594. var arc = options.arc || instance.arc;
  47595. path3D = (instance.path3D).update(path);
  47596. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  47597. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  47598. instance.path3D = path3D;
  47599. instance.pathArray = pathArray;
  47600. instance.arc = arc;
  47601. instance.radius = radius;
  47602. return instance;
  47603. }
  47604. // tube creation
  47605. path3D = new BABYLON.Path3D(path);
  47606. var newPathArray = new Array();
  47607. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47608. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  47609. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47610. tube.pathArray = pathArray;
  47611. tube.path3D = path3D;
  47612. tube.tessellation = tessellation;
  47613. tube.cap = cap;
  47614. tube.arc = options.arc;
  47615. tube.radius = radius;
  47616. return tube;
  47617. };
  47618. /**
  47619. * Creates a polyhedron mesh.
  47620. *
  47621. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  47622. * 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
  47623. * to choose the wanted type.
  47624. * The parameter `size` (positive float, default 1) sets the polygon size.
  47625. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  47626. * 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`.
  47627. * 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
  47628. * 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)`).
  47629. * 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
  47630. * 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.
  47631. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47632. * 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).
  47633. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47634. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47635. */
  47636. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  47637. var polyhedron = new BABYLON.Mesh(name, scene);
  47638. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47639. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  47640. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  47641. vertexData.applyToMesh(polyhedron, options.updatable);
  47642. return polyhedron;
  47643. };
  47644. /**
  47645. * Creates a decal mesh.
  47646. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  47647. * 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.
  47648. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  47649. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  47650. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  47651. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  47652. */
  47653. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  47654. var indices = sourceMesh.getIndices();
  47655. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47656. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47657. var position = options.position || BABYLON.Vector3.Zero();
  47658. var normal = options.normal || BABYLON.Vector3.Up();
  47659. var size = options.size || BABYLON.Vector3.One();
  47660. var angle = options.angle || 0;
  47661. // Getting correct rotation
  47662. if (!normal) {
  47663. var target = new BABYLON.Vector3(0, 0, 1);
  47664. var camera = sourceMesh.getScene().activeCamera;
  47665. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  47666. normal = camera.globalPosition.subtract(cameraWorldTarget);
  47667. }
  47668. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  47669. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  47670. var pitch = Math.atan2(normal.y, len);
  47671. // Matrix
  47672. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  47673. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  47674. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  47675. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  47676. var vertexData = new BABYLON.VertexData();
  47677. vertexData.indices = [];
  47678. vertexData.positions = [];
  47679. vertexData.normals = [];
  47680. vertexData.uvs = [];
  47681. var currentVertexDataIndex = 0;
  47682. var extractDecalVector3 = function (indexId) {
  47683. var result = new BABYLON.PositionNormalVertex();
  47684. if (!indices || !positions || !normals) {
  47685. return result;
  47686. }
  47687. var vertexId = indices[indexId];
  47688. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  47689. // Send vector to decal local world
  47690. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  47691. // Get normal
  47692. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  47693. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  47694. return result;
  47695. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  47696. var clip = function (vertices, axis) {
  47697. if (vertices.length === 0) {
  47698. return vertices;
  47699. }
  47700. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  47701. var clipVertices = function (v0, v1) {
  47702. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  47703. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  47704. };
  47705. var result = new Array();
  47706. for (var index = 0; index < vertices.length; index += 3) {
  47707. var v1Out;
  47708. var v2Out;
  47709. var v3Out;
  47710. var total = 0;
  47711. var nV1 = null;
  47712. var nV2 = null;
  47713. var nV3 = null;
  47714. var nV4 = null;
  47715. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  47716. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  47717. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  47718. v1Out = d1 > 0;
  47719. v2Out = d2 > 0;
  47720. v3Out = d3 > 0;
  47721. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  47722. switch (total) {
  47723. case 0:
  47724. result.push(vertices[index]);
  47725. result.push(vertices[index + 1]);
  47726. result.push(vertices[index + 2]);
  47727. break;
  47728. case 1:
  47729. if (v1Out) {
  47730. nV1 = vertices[index + 1];
  47731. nV2 = vertices[index + 2];
  47732. nV3 = clipVertices(vertices[index], nV1);
  47733. nV4 = clipVertices(vertices[index], nV2);
  47734. }
  47735. if (v2Out) {
  47736. nV1 = vertices[index];
  47737. nV2 = vertices[index + 2];
  47738. nV3 = clipVertices(vertices[index + 1], nV1);
  47739. nV4 = clipVertices(vertices[index + 1], nV2);
  47740. result.push(nV3);
  47741. result.push(nV2.clone());
  47742. result.push(nV1.clone());
  47743. result.push(nV2.clone());
  47744. result.push(nV3.clone());
  47745. result.push(nV4);
  47746. break;
  47747. }
  47748. if (v3Out) {
  47749. nV1 = vertices[index];
  47750. nV2 = vertices[index + 1];
  47751. nV3 = clipVertices(vertices[index + 2], nV1);
  47752. nV4 = clipVertices(vertices[index + 2], nV2);
  47753. }
  47754. if (nV1 && nV2 && nV3 && nV4) {
  47755. result.push(nV1.clone());
  47756. result.push(nV2.clone());
  47757. result.push(nV3);
  47758. result.push(nV4);
  47759. result.push(nV3.clone());
  47760. result.push(nV2.clone());
  47761. }
  47762. break;
  47763. case 2:
  47764. if (!v1Out) {
  47765. nV1 = vertices[index].clone();
  47766. nV2 = clipVertices(nV1, vertices[index + 1]);
  47767. nV3 = clipVertices(nV1, vertices[index + 2]);
  47768. result.push(nV1);
  47769. result.push(nV2);
  47770. result.push(nV3);
  47771. }
  47772. if (!v2Out) {
  47773. nV1 = vertices[index + 1].clone();
  47774. nV2 = clipVertices(nV1, vertices[index + 2]);
  47775. nV3 = clipVertices(nV1, vertices[index]);
  47776. result.push(nV1);
  47777. result.push(nV2);
  47778. result.push(nV3);
  47779. }
  47780. if (!v3Out) {
  47781. nV1 = vertices[index + 2].clone();
  47782. nV2 = clipVertices(nV1, vertices[index]);
  47783. nV3 = clipVertices(nV1, vertices[index + 1]);
  47784. result.push(nV1);
  47785. result.push(nV2);
  47786. result.push(nV3);
  47787. }
  47788. break;
  47789. case 3:
  47790. break;
  47791. }
  47792. }
  47793. return result;
  47794. };
  47795. for (var index = 0; index < indices.length; index += 3) {
  47796. var faceVertices = new Array();
  47797. faceVertices.push(extractDecalVector3(index));
  47798. faceVertices.push(extractDecalVector3(index + 1));
  47799. faceVertices.push(extractDecalVector3(index + 2));
  47800. // Clip
  47801. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  47802. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  47803. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  47804. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  47805. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  47806. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  47807. if (faceVertices.length === 0) {
  47808. continue;
  47809. }
  47810. // Add UVs and get back to world
  47811. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  47812. var vertex = faceVertices[vIndex];
  47813. //TODO check for Int32Array | Uint32Array | Uint16Array
  47814. vertexData.indices.push(currentVertexDataIndex);
  47815. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  47816. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  47817. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  47818. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  47819. currentVertexDataIndex++;
  47820. }
  47821. }
  47822. // Return mesh
  47823. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  47824. vertexData.applyToMesh(decal);
  47825. decal.position = position.clone();
  47826. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  47827. return decal;
  47828. };
  47829. // Privates
  47830. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  47831. // extrusion geometry
  47832. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  47833. var tangents = path3D.getTangents();
  47834. var normals = path3D.getNormals();
  47835. var binormals = path3D.getBinormals();
  47836. var distances = path3D.getDistances();
  47837. var angle = 0;
  47838. var returnScale = function () { return scale !== null ? scale : 1; };
  47839. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  47840. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  47841. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  47842. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47843. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47844. for (var i = 0; i < curve.length; i++) {
  47845. var shapePath = new Array();
  47846. var angleStep = rotate(i, distances[i]);
  47847. var scaleRatio = scl(i, distances[i]);
  47848. for (var p = 0; p < shape.length; p++) {
  47849. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  47850. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  47851. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  47852. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  47853. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  47854. shapePath[p] = rotated;
  47855. }
  47856. shapePaths[index] = shapePath;
  47857. angle += angleStep;
  47858. index++;
  47859. }
  47860. // cap
  47861. var capPath = function (shapePath) {
  47862. var pointCap = Array();
  47863. var barycenter = BABYLON.Vector3.Zero();
  47864. var i;
  47865. for (i = 0; i < shapePath.length; i++) {
  47866. barycenter.addInPlace(shapePath[i]);
  47867. }
  47868. barycenter.scaleInPlace(1.0 / shapePath.length);
  47869. for (i = 0; i < shapePath.length; i++) {
  47870. pointCap.push(barycenter);
  47871. }
  47872. return pointCap;
  47873. };
  47874. switch (cap) {
  47875. case BABYLON.Mesh.NO_CAP:
  47876. break;
  47877. case BABYLON.Mesh.CAP_START:
  47878. shapePaths[0] = capPath(shapePaths[2]);
  47879. shapePaths[1] = shapePaths[2];
  47880. break;
  47881. case BABYLON.Mesh.CAP_END:
  47882. shapePaths[index] = shapePaths[index - 1];
  47883. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  47884. break;
  47885. case BABYLON.Mesh.CAP_ALL:
  47886. shapePaths[0] = capPath(shapePaths[2]);
  47887. shapePaths[1] = shapePaths[2];
  47888. shapePaths[index] = shapePaths[index - 1];
  47889. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  47890. break;
  47891. default:
  47892. break;
  47893. }
  47894. return shapePaths;
  47895. };
  47896. var path3D;
  47897. var pathArray;
  47898. if (instance) {
  47899. path3D = (instance.path3D).update(curve);
  47900. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  47901. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  47902. return instance;
  47903. }
  47904. // extruded shape creation
  47905. path3D = new BABYLON.Path3D(curve);
  47906. var newShapePaths = new Array();
  47907. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47908. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  47909. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  47910. extrudedGeneric.pathArray = pathArray;
  47911. extrudedGeneric.path3D = path3D;
  47912. extrudedGeneric.cap = cap;
  47913. return extrudedGeneric;
  47914. };
  47915. return MeshBuilder;
  47916. }());
  47917. BABYLON.MeshBuilder = MeshBuilder;
  47918. })(BABYLON || (BABYLON = {}));
  47919. //# sourceMappingURL=babylon.meshBuilder.js.map
  47920. var BABYLON;
  47921. (function (BABYLON) {
  47922. var AudioEngine = /** @class */ (function () {
  47923. function AudioEngine() {
  47924. this._audioContext = null;
  47925. this._audioContextInitialized = false;
  47926. this.canUseWebAudio = false;
  47927. this.WarnedWebAudioUnsupported = false;
  47928. this.unlocked = false;
  47929. this.isMP3supported = false;
  47930. this.isOGGsupported = false;
  47931. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  47932. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  47933. this.canUseWebAudio = true;
  47934. }
  47935. var audioElem = document.createElement('audio');
  47936. try {
  47937. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  47938. this.isMP3supported = true;
  47939. }
  47940. }
  47941. catch (e) {
  47942. // protect error during capability check.
  47943. }
  47944. try {
  47945. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  47946. this.isOGGsupported = true;
  47947. }
  47948. }
  47949. catch (e) {
  47950. // protect error during capability check.
  47951. }
  47952. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  47953. this._unlockiOSaudio();
  47954. }
  47955. else {
  47956. this.unlocked = true;
  47957. }
  47958. }
  47959. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  47960. get: function () {
  47961. if (!this._audioContextInitialized) {
  47962. this._initializeAudioContext();
  47963. }
  47964. return this._audioContext;
  47965. },
  47966. enumerable: true,
  47967. configurable: true
  47968. });
  47969. AudioEngine.prototype._unlockiOSaudio = function () {
  47970. var _this = this;
  47971. var unlockaudio = function () {
  47972. if (!_this.audioContext) {
  47973. return;
  47974. }
  47975. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  47976. var source = _this.audioContext.createBufferSource();
  47977. source.buffer = buffer;
  47978. source.connect(_this.audioContext.destination);
  47979. source.start(0);
  47980. setTimeout(function () {
  47981. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  47982. _this.unlocked = true;
  47983. window.removeEventListener('touchend', unlockaudio, false);
  47984. if (_this.onAudioUnlocked) {
  47985. _this.onAudioUnlocked();
  47986. }
  47987. }
  47988. }, 0);
  47989. };
  47990. window.addEventListener('touchend', unlockaudio, false);
  47991. };
  47992. AudioEngine.prototype._initializeAudioContext = function () {
  47993. try {
  47994. if (this.canUseWebAudio) {
  47995. this._audioContext = new AudioContext();
  47996. // create a global volume gain node
  47997. this.masterGain = this._audioContext.createGain();
  47998. this.masterGain.gain.value = 1;
  47999. this.masterGain.connect(this._audioContext.destination);
  48000. this._audioContextInitialized = true;
  48001. }
  48002. }
  48003. catch (e) {
  48004. this.canUseWebAudio = false;
  48005. BABYLON.Tools.Error("Web Audio: " + e.message);
  48006. }
  48007. };
  48008. AudioEngine.prototype.dispose = function () {
  48009. if (this.canUseWebAudio && this._audioContextInitialized) {
  48010. if (this._connectedAnalyser && this._audioContext) {
  48011. this._connectedAnalyser.stopDebugCanvas();
  48012. this._connectedAnalyser.dispose();
  48013. this.masterGain.disconnect();
  48014. this.masterGain.connect(this._audioContext.destination);
  48015. this._connectedAnalyser = null;
  48016. }
  48017. this.masterGain.gain.value = 1;
  48018. }
  48019. this.WarnedWebAudioUnsupported = false;
  48020. };
  48021. AudioEngine.prototype.getGlobalVolume = function () {
  48022. if (this.canUseWebAudio && this._audioContextInitialized) {
  48023. return this.masterGain.gain.value;
  48024. }
  48025. else {
  48026. return -1;
  48027. }
  48028. };
  48029. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48030. if (this.canUseWebAudio && this._audioContextInitialized) {
  48031. this.masterGain.gain.value = newVolume;
  48032. }
  48033. };
  48034. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48035. if (this._connectedAnalyser) {
  48036. this._connectedAnalyser.stopDebugCanvas();
  48037. }
  48038. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48039. this._connectedAnalyser = analyser;
  48040. this.masterGain.disconnect();
  48041. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48042. }
  48043. };
  48044. return AudioEngine;
  48045. }());
  48046. BABYLON.AudioEngine = AudioEngine;
  48047. })(BABYLON || (BABYLON = {}));
  48048. //# sourceMappingURL=babylon.audioEngine.js.map
  48049. var BABYLON;
  48050. (function (BABYLON) {
  48051. var Sound = /** @class */ (function () {
  48052. /**
  48053. * Create a sound and attach it to a scene
  48054. * @param name Name of your sound
  48055. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48056. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48057. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48058. */
  48059. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48060. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48061. var _this = this;
  48062. this.autoplay = false;
  48063. this.loop = false;
  48064. this.useCustomAttenuation = false;
  48065. this.spatialSound = false;
  48066. this.refDistance = 1;
  48067. this.rolloffFactor = 1;
  48068. this.maxDistance = 100;
  48069. this.distanceModel = "linear";
  48070. this._panningModel = "equalpower";
  48071. this._playbackRate = 1;
  48072. this._streaming = false;
  48073. this._startTime = 0;
  48074. this._startOffset = 0;
  48075. this._position = BABYLON.Vector3.Zero();
  48076. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48077. this._volume = 1;
  48078. this._isLoaded = false;
  48079. this._isReadyToPlay = false;
  48080. this.isPlaying = false;
  48081. this.isPaused = false;
  48082. this._isDirectional = false;
  48083. // Used if you'd like to create a directional sound.
  48084. // If not set, the sound will be omnidirectional
  48085. this._coneInnerAngle = 360;
  48086. this._coneOuterAngle = 360;
  48087. this._coneOuterGain = 0;
  48088. this._isOutputConnected = false;
  48089. this._urlType = "Unknown";
  48090. this.name = name;
  48091. this._scene = scene;
  48092. this._readyToPlayCallback = readyToPlayCallback;
  48093. // Default custom attenuation function is a linear attenuation
  48094. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48095. if (currentDistance < maxDistance) {
  48096. return currentVolume * (1 - currentDistance / maxDistance);
  48097. }
  48098. else {
  48099. return 0;
  48100. }
  48101. };
  48102. if (options) {
  48103. this.autoplay = options.autoplay || false;
  48104. this.loop = options.loop || false;
  48105. // if volume === 0, we need another way to check this option
  48106. if (options.volume !== undefined) {
  48107. this._volume = options.volume;
  48108. }
  48109. this.spatialSound = options.spatialSound || false;
  48110. this.maxDistance = options.maxDistance || 100;
  48111. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48112. this.rolloffFactor = options.rolloffFactor || 1;
  48113. this.refDistance = options.refDistance || 1;
  48114. this.distanceModel = options.distanceModel || "linear";
  48115. this._playbackRate = options.playbackRate || 1;
  48116. this._streaming = options.streaming || false;
  48117. }
  48118. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48119. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48120. this._soundGain.gain.value = this._volume;
  48121. this._inputAudioNode = this._soundGain;
  48122. this._ouputAudioNode = this._soundGain;
  48123. if (this.spatialSound) {
  48124. this._createSpatialParameters();
  48125. }
  48126. this._scene.mainSoundTrack.AddSound(this);
  48127. var validParameter = true;
  48128. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48129. if (urlOrArrayBuffer) {
  48130. if (typeof (urlOrArrayBuffer) === "string")
  48131. this._urlType = "String";
  48132. if (Array.isArray(urlOrArrayBuffer))
  48133. this._urlType = "Array";
  48134. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48135. this._urlType = "ArrayBuffer";
  48136. var urls = [];
  48137. var codecSupportedFound = false;
  48138. switch (this._urlType) {
  48139. case "ArrayBuffer":
  48140. if (urlOrArrayBuffer.byteLength > 0) {
  48141. codecSupportedFound = true;
  48142. this._soundLoaded(urlOrArrayBuffer);
  48143. }
  48144. break;
  48145. case "String":
  48146. urls.push(urlOrArrayBuffer);
  48147. case "Array":
  48148. if (urls.length === 0)
  48149. urls = urlOrArrayBuffer;
  48150. // If we found a supported format, we load it immediately and stop the loop
  48151. for (var i = 0; i < urls.length; i++) {
  48152. var url = urls[i];
  48153. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48154. codecSupportedFound = true;
  48155. }
  48156. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48157. codecSupportedFound = true;
  48158. }
  48159. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48160. codecSupportedFound = true;
  48161. }
  48162. if (url.indexOf("blob:") !== -1) {
  48163. codecSupportedFound = true;
  48164. }
  48165. if (codecSupportedFound) {
  48166. // Loading sound using XHR2
  48167. if (!this._streaming) {
  48168. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48169. }
  48170. else {
  48171. this._htmlAudioElement = new Audio(url);
  48172. this._htmlAudioElement.controls = false;
  48173. this._htmlAudioElement.loop = this.loop;
  48174. this._htmlAudioElement.crossOrigin = "anonymous";
  48175. this._htmlAudioElement.preload = "auto";
  48176. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48177. _this._isReadyToPlay = true;
  48178. if (_this.autoplay) {
  48179. _this.play();
  48180. }
  48181. if (_this._readyToPlayCallback) {
  48182. _this._readyToPlayCallback();
  48183. }
  48184. });
  48185. document.body.appendChild(this._htmlAudioElement);
  48186. }
  48187. break;
  48188. }
  48189. }
  48190. break;
  48191. default:
  48192. validParameter = false;
  48193. break;
  48194. }
  48195. if (!validParameter) {
  48196. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  48197. }
  48198. else {
  48199. if (!codecSupportedFound) {
  48200. this._isReadyToPlay = true;
  48201. // Simulating a ready to play event to avoid breaking code path
  48202. if (this._readyToPlayCallback) {
  48203. window.setTimeout(function () {
  48204. if (_this._readyToPlayCallback) {
  48205. _this._readyToPlayCallback();
  48206. }
  48207. }, 1000);
  48208. }
  48209. }
  48210. }
  48211. }
  48212. }
  48213. else {
  48214. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  48215. this._scene.mainSoundTrack.AddSound(this);
  48216. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  48217. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  48218. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  48219. }
  48220. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  48221. if (this._readyToPlayCallback) {
  48222. window.setTimeout(function () {
  48223. if (_this._readyToPlayCallback) {
  48224. _this._readyToPlayCallback();
  48225. }
  48226. }, 1000);
  48227. }
  48228. }
  48229. }
  48230. Sound.prototype.dispose = function () {
  48231. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  48232. if (this.isPlaying) {
  48233. this.stop();
  48234. }
  48235. this._isReadyToPlay = false;
  48236. if (this.soundTrackId === -1) {
  48237. this._scene.mainSoundTrack.RemoveSound(this);
  48238. }
  48239. else {
  48240. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  48241. }
  48242. if (this._soundGain) {
  48243. this._soundGain.disconnect();
  48244. this._soundGain = null;
  48245. }
  48246. if (this._soundPanner) {
  48247. this._soundPanner.disconnect();
  48248. this._soundPanner = null;
  48249. }
  48250. if (this._soundSource) {
  48251. this._soundSource.disconnect();
  48252. this._soundSource = null;
  48253. }
  48254. this._audioBuffer = null;
  48255. if (this._htmlAudioElement) {
  48256. this._htmlAudioElement.pause();
  48257. this._htmlAudioElement.src = "";
  48258. document.body.removeChild(this._htmlAudioElement);
  48259. }
  48260. if (this._connectedMesh && this._registerFunc) {
  48261. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48262. this._connectedMesh = null;
  48263. }
  48264. }
  48265. };
  48266. Sound.prototype.isReady = function () {
  48267. return this._isReadyToPlay;
  48268. };
  48269. Sound.prototype._soundLoaded = function (audioData) {
  48270. var _this = this;
  48271. this._isLoaded = true;
  48272. if (!BABYLON.Engine.audioEngine.audioContext) {
  48273. return;
  48274. }
  48275. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  48276. _this._audioBuffer = buffer;
  48277. _this._isReadyToPlay = true;
  48278. if (_this.autoplay) {
  48279. _this.play();
  48280. }
  48281. if (_this._readyToPlayCallback) {
  48282. _this._readyToPlayCallback();
  48283. }
  48284. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  48285. };
  48286. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  48287. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48288. this._audioBuffer = audioBuffer;
  48289. this._isReadyToPlay = true;
  48290. }
  48291. };
  48292. Sound.prototype.updateOptions = function (options) {
  48293. if (options) {
  48294. this.loop = options.loop || this.loop;
  48295. this.maxDistance = options.maxDistance || this.maxDistance;
  48296. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  48297. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  48298. this.refDistance = options.refDistance || this.refDistance;
  48299. this.distanceModel = options.distanceModel || this.distanceModel;
  48300. this._playbackRate = options.playbackRate || this._playbackRate;
  48301. this._updateSpatialParameters();
  48302. if (this.isPlaying) {
  48303. if (this._streaming) {
  48304. this._htmlAudioElement.playbackRate = this._playbackRate;
  48305. }
  48306. else {
  48307. if (this._soundSource) {
  48308. this._soundSource.playbackRate.value = this._playbackRate;
  48309. }
  48310. }
  48311. }
  48312. }
  48313. };
  48314. Sound.prototype._createSpatialParameters = function () {
  48315. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48316. if (this._scene.headphone) {
  48317. this._panningModel = "HRTF";
  48318. }
  48319. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  48320. this._updateSpatialParameters();
  48321. this._soundPanner.connect(this._ouputAudioNode);
  48322. this._inputAudioNode = this._soundPanner;
  48323. }
  48324. };
  48325. Sound.prototype._updateSpatialParameters = function () {
  48326. if (this.spatialSound && this._soundPanner) {
  48327. if (this.useCustomAttenuation) {
  48328. // Tricks to disable in a way embedded Web Audio attenuation
  48329. this._soundPanner.distanceModel = "linear";
  48330. this._soundPanner.maxDistance = Number.MAX_VALUE;
  48331. this._soundPanner.refDistance = 1;
  48332. this._soundPanner.rolloffFactor = 1;
  48333. this._soundPanner.panningModel = this._panningModel;
  48334. }
  48335. else {
  48336. this._soundPanner.distanceModel = this.distanceModel;
  48337. this._soundPanner.maxDistance = this.maxDistance;
  48338. this._soundPanner.refDistance = this.refDistance;
  48339. this._soundPanner.rolloffFactor = this.rolloffFactor;
  48340. this._soundPanner.panningModel = this._panningModel;
  48341. }
  48342. }
  48343. };
  48344. Sound.prototype.switchPanningModelToHRTF = function () {
  48345. this._panningModel = "HRTF";
  48346. this._switchPanningModel();
  48347. };
  48348. Sound.prototype.switchPanningModelToEqualPower = function () {
  48349. this._panningModel = "equalpower";
  48350. this._switchPanningModel();
  48351. };
  48352. Sound.prototype._switchPanningModel = function () {
  48353. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48354. this._soundPanner.panningModel = this._panningModel;
  48355. }
  48356. };
  48357. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  48358. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48359. if (this._isOutputConnected) {
  48360. this._ouputAudioNode.disconnect();
  48361. }
  48362. this._ouputAudioNode.connect(soundTrackAudioNode);
  48363. this._isOutputConnected = true;
  48364. }
  48365. };
  48366. /**
  48367. * Transform this sound into a directional source
  48368. * @param coneInnerAngle Size of the inner cone in degree
  48369. * @param coneOuterAngle Size of the outer cone in degree
  48370. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  48371. */
  48372. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  48373. if (coneOuterAngle < coneInnerAngle) {
  48374. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  48375. return;
  48376. }
  48377. this._coneInnerAngle = coneInnerAngle;
  48378. this._coneOuterAngle = coneOuterAngle;
  48379. this._coneOuterGain = coneOuterGain;
  48380. this._isDirectional = true;
  48381. if (this.isPlaying && this.loop) {
  48382. this.stop();
  48383. this.play();
  48384. }
  48385. };
  48386. Sound.prototype.setPosition = function (newPosition) {
  48387. this._position = newPosition;
  48388. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48389. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48390. }
  48391. };
  48392. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  48393. this._localDirection = newLocalDirection;
  48394. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  48395. this._updateDirection();
  48396. }
  48397. };
  48398. Sound.prototype._updateDirection = function () {
  48399. if (!this._connectedMesh || !this._soundPanner) {
  48400. return;
  48401. }
  48402. var mat = this._connectedMesh.getWorldMatrix();
  48403. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  48404. direction.normalize();
  48405. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  48406. };
  48407. Sound.prototype.updateDistanceFromListener = function () {
  48408. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  48409. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  48410. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  48411. }
  48412. };
  48413. Sound.prototype.setAttenuationFunction = function (callback) {
  48414. this._customAttenuationFunction = callback;
  48415. };
  48416. /**
  48417. * Play the sound
  48418. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  48419. * @param offset (optional) Start the sound setting it at a specific time
  48420. */
  48421. Sound.prototype.play = function (time, offset) {
  48422. var _this = this;
  48423. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  48424. try {
  48425. if (this._startOffset < 0) {
  48426. time = -this._startOffset;
  48427. this._startOffset = 0;
  48428. }
  48429. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48430. if (!this._soundSource || !this._streamingSource) {
  48431. if (this.spatialSound && this._soundPanner) {
  48432. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48433. if (this._isDirectional) {
  48434. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  48435. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  48436. this._soundPanner.coneOuterGain = this._coneOuterGain;
  48437. if (this._connectedMesh) {
  48438. this._updateDirection();
  48439. }
  48440. else {
  48441. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  48442. }
  48443. }
  48444. }
  48445. }
  48446. if (this._streaming) {
  48447. if (!this._streamingSource) {
  48448. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  48449. this._htmlAudioElement.onended = function () { _this._onended(); };
  48450. this._htmlAudioElement.playbackRate = this._playbackRate;
  48451. }
  48452. this._streamingSource.disconnect();
  48453. this._streamingSource.connect(this._inputAudioNode);
  48454. this._htmlAudioElement.play();
  48455. }
  48456. else {
  48457. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  48458. this._soundSource.buffer = this._audioBuffer;
  48459. this._soundSource.connect(this._inputAudioNode);
  48460. this._soundSource.loop = this.loop;
  48461. this._soundSource.playbackRate.value = this._playbackRate;
  48462. this._soundSource.onended = function () { _this._onended(); };
  48463. if (this._soundSource.buffer) {
  48464. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  48465. }
  48466. }
  48467. this._startTime = startTime;
  48468. this.isPlaying = true;
  48469. this.isPaused = false;
  48470. }
  48471. catch (ex) {
  48472. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  48473. }
  48474. }
  48475. };
  48476. Sound.prototype._onended = function () {
  48477. this.isPlaying = false;
  48478. if (this.onended) {
  48479. this.onended();
  48480. }
  48481. };
  48482. /**
  48483. * Stop the sound
  48484. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  48485. */
  48486. Sound.prototype.stop = function (time) {
  48487. if (this.isPlaying) {
  48488. if (this._streaming) {
  48489. this._htmlAudioElement.pause();
  48490. // Test needed for Firefox or it will generate an Invalid State Error
  48491. if (this._htmlAudioElement.currentTime > 0) {
  48492. this._htmlAudioElement.currentTime = 0;
  48493. }
  48494. }
  48495. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  48496. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48497. this._soundSource.stop(stopTime);
  48498. this._soundSource.onended = function () { };
  48499. if (!this.isPaused) {
  48500. this._startOffset = 0;
  48501. }
  48502. }
  48503. this.isPlaying = false;
  48504. }
  48505. };
  48506. Sound.prototype.pause = function () {
  48507. if (this.isPlaying) {
  48508. this.isPaused = true;
  48509. if (this._streaming) {
  48510. this._htmlAudioElement.pause();
  48511. }
  48512. else if (BABYLON.Engine.audioEngine.audioContext) {
  48513. this.stop(0);
  48514. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  48515. }
  48516. }
  48517. };
  48518. Sound.prototype.setVolume = function (newVolume, time) {
  48519. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  48520. if (time && BABYLON.Engine.audioEngine.audioContext) {
  48521. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  48522. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  48523. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  48524. }
  48525. else {
  48526. this._soundGain.gain.value = newVolume;
  48527. }
  48528. }
  48529. this._volume = newVolume;
  48530. };
  48531. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  48532. this._playbackRate = newPlaybackRate;
  48533. if (this.isPlaying) {
  48534. if (this._streaming) {
  48535. this._htmlAudioElement.playbackRate = this._playbackRate;
  48536. }
  48537. else if (this._soundSource) {
  48538. this._soundSource.playbackRate.value = this._playbackRate;
  48539. }
  48540. }
  48541. };
  48542. Sound.prototype.getVolume = function () {
  48543. return this._volume;
  48544. };
  48545. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  48546. var _this = this;
  48547. if (this._connectedMesh && this._registerFunc) {
  48548. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48549. this._registerFunc = null;
  48550. }
  48551. this._connectedMesh = meshToConnectTo;
  48552. if (!this.spatialSound) {
  48553. this.spatialSound = true;
  48554. this._createSpatialParameters();
  48555. if (this.isPlaying && this.loop) {
  48556. this.stop();
  48557. this.play();
  48558. }
  48559. }
  48560. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  48561. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  48562. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  48563. };
  48564. Sound.prototype.detachFromMesh = function () {
  48565. if (this._connectedMesh && this._registerFunc) {
  48566. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48567. this._registerFunc = null;
  48568. this._connectedMesh = null;
  48569. }
  48570. };
  48571. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  48572. var boundingInfo = connectedMesh.getBoundingInfo();
  48573. if (!boundingInfo) {
  48574. return;
  48575. }
  48576. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  48577. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  48578. this._updateDirection();
  48579. }
  48580. };
  48581. Sound.prototype.clone = function () {
  48582. var _this = this;
  48583. if (!this._streaming) {
  48584. var setBufferAndRun = function () {
  48585. if (_this._isReadyToPlay) {
  48586. clonedSound._audioBuffer = _this.getAudioBuffer();
  48587. clonedSound._isReadyToPlay = true;
  48588. if (clonedSound.autoplay) {
  48589. clonedSound.play();
  48590. }
  48591. }
  48592. else {
  48593. window.setTimeout(setBufferAndRun, 300);
  48594. }
  48595. };
  48596. var currentOptions = {
  48597. autoplay: this.autoplay, loop: this.loop,
  48598. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  48599. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  48600. refDistance: this.refDistance, distanceModel: this.distanceModel
  48601. };
  48602. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  48603. if (this.useCustomAttenuation) {
  48604. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  48605. }
  48606. clonedSound.setPosition(this._position);
  48607. clonedSound.setPlaybackRate(this._playbackRate);
  48608. setBufferAndRun();
  48609. return clonedSound;
  48610. }
  48611. else {
  48612. return null;
  48613. }
  48614. };
  48615. Sound.prototype.getAudioBuffer = function () {
  48616. return this._audioBuffer;
  48617. };
  48618. Sound.prototype.serialize = function () {
  48619. var serializationObject = {
  48620. name: this.name,
  48621. url: this.name,
  48622. autoplay: this.autoplay,
  48623. loop: this.loop,
  48624. volume: this._volume,
  48625. spatialSound: this.spatialSound,
  48626. maxDistance: this.maxDistance,
  48627. rolloffFactor: this.rolloffFactor,
  48628. refDistance: this.refDistance,
  48629. distanceModel: this.distanceModel,
  48630. playbackRate: this._playbackRate,
  48631. panningModel: this._panningModel,
  48632. soundTrackId: this.soundTrackId
  48633. };
  48634. if (this.spatialSound) {
  48635. if (this._connectedMesh)
  48636. serializationObject.connectedMeshId = this._connectedMesh.id;
  48637. serializationObject.position = this._position.asArray();
  48638. serializationObject.refDistance = this.refDistance;
  48639. serializationObject.distanceModel = this.distanceModel;
  48640. serializationObject.isDirectional = this._isDirectional;
  48641. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  48642. serializationObject.coneInnerAngle = this._coneInnerAngle;
  48643. serializationObject.coneOuterAngle = this._coneOuterAngle;
  48644. serializationObject.coneOuterGain = this._coneOuterGain;
  48645. }
  48646. return serializationObject;
  48647. };
  48648. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  48649. var soundName = parsedSound.name;
  48650. var soundUrl;
  48651. if (parsedSound.url) {
  48652. soundUrl = rootUrl + parsedSound.url;
  48653. }
  48654. else {
  48655. soundUrl = rootUrl + soundName;
  48656. }
  48657. var options = {
  48658. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  48659. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  48660. rolloffFactor: parsedSound.rolloffFactor,
  48661. refDistance: parsedSound.refDistance,
  48662. distanceModel: parsedSound.distanceModel,
  48663. playbackRate: parsedSound.playbackRate
  48664. };
  48665. var newSound;
  48666. if (!sourceSound) {
  48667. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  48668. scene._addPendingData(newSound);
  48669. }
  48670. else {
  48671. var setBufferAndRun = function () {
  48672. if (sourceSound._isReadyToPlay) {
  48673. newSound._audioBuffer = sourceSound.getAudioBuffer();
  48674. newSound._isReadyToPlay = true;
  48675. if (newSound.autoplay) {
  48676. newSound.play();
  48677. }
  48678. }
  48679. else {
  48680. window.setTimeout(setBufferAndRun, 300);
  48681. }
  48682. };
  48683. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  48684. setBufferAndRun();
  48685. }
  48686. if (parsedSound.position) {
  48687. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  48688. newSound.setPosition(soundPosition);
  48689. }
  48690. if (parsedSound.isDirectional) {
  48691. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  48692. if (parsedSound.localDirectionToMesh) {
  48693. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  48694. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  48695. }
  48696. }
  48697. if (parsedSound.connectedMeshId) {
  48698. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  48699. if (connectedMesh) {
  48700. newSound.attachToMesh(connectedMesh);
  48701. }
  48702. }
  48703. return newSound;
  48704. };
  48705. return Sound;
  48706. }());
  48707. BABYLON.Sound = Sound;
  48708. })(BABYLON || (BABYLON = {}));
  48709. //# sourceMappingURL=babylon.sound.js.map
  48710. var BABYLON;
  48711. (function (BABYLON) {
  48712. var SoundTrack = /** @class */ (function () {
  48713. function SoundTrack(scene, options) {
  48714. this.id = -1;
  48715. this._isMainTrack = false;
  48716. this._isInitialized = false;
  48717. this._scene = scene;
  48718. this.soundCollection = new Array();
  48719. this._options = options;
  48720. if (!this._isMainTrack) {
  48721. this._scene.soundTracks.push(this);
  48722. this.id = this._scene.soundTracks.length - 1;
  48723. }
  48724. }
  48725. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  48726. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48727. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  48728. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  48729. if (this._options) {
  48730. if (this._options.volume) {
  48731. this._outputAudioNode.gain.value = this._options.volume;
  48732. }
  48733. if (this._options.mainTrack) {
  48734. this._isMainTrack = this._options.mainTrack;
  48735. }
  48736. }
  48737. this._isInitialized = true;
  48738. }
  48739. };
  48740. SoundTrack.prototype.dispose = function () {
  48741. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48742. if (this._connectedAnalyser) {
  48743. this._connectedAnalyser.stopDebugCanvas();
  48744. }
  48745. while (this.soundCollection.length) {
  48746. this.soundCollection[0].dispose();
  48747. }
  48748. if (this._outputAudioNode) {
  48749. this._outputAudioNode.disconnect();
  48750. }
  48751. this._outputAudioNode = null;
  48752. }
  48753. };
  48754. SoundTrack.prototype.AddSound = function (sound) {
  48755. if (!this._isInitialized) {
  48756. this._initializeSoundTrackAudioGraph();
  48757. }
  48758. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48759. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  48760. }
  48761. if (sound.soundTrackId) {
  48762. if (sound.soundTrackId === -1) {
  48763. this._scene.mainSoundTrack.RemoveSound(sound);
  48764. }
  48765. else {
  48766. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  48767. }
  48768. }
  48769. this.soundCollection.push(sound);
  48770. sound.soundTrackId = this.id;
  48771. };
  48772. SoundTrack.prototype.RemoveSound = function (sound) {
  48773. var index = this.soundCollection.indexOf(sound);
  48774. if (index !== -1) {
  48775. this.soundCollection.splice(index, 1);
  48776. }
  48777. };
  48778. SoundTrack.prototype.setVolume = function (newVolume) {
  48779. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48780. this._outputAudioNode.gain.value = newVolume;
  48781. }
  48782. };
  48783. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  48784. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48785. for (var i = 0; i < this.soundCollection.length; i++) {
  48786. this.soundCollection[i].switchPanningModelToHRTF();
  48787. }
  48788. }
  48789. };
  48790. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  48791. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48792. for (var i = 0; i < this.soundCollection.length; i++) {
  48793. this.soundCollection[i].switchPanningModelToEqualPower();
  48794. }
  48795. }
  48796. };
  48797. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  48798. if (this._connectedAnalyser) {
  48799. this._connectedAnalyser.stopDebugCanvas();
  48800. }
  48801. this._connectedAnalyser = analyser;
  48802. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48803. this._outputAudioNode.disconnect();
  48804. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  48805. }
  48806. };
  48807. return SoundTrack;
  48808. }());
  48809. BABYLON.SoundTrack = SoundTrack;
  48810. })(BABYLON || (BABYLON = {}));
  48811. //# sourceMappingURL=babylon.soundtrack.js.map
  48812. var BABYLON;
  48813. (function (BABYLON) {
  48814. var Analyser = /** @class */ (function () {
  48815. function Analyser(scene) {
  48816. this.SMOOTHING = 0.75;
  48817. this.FFT_SIZE = 512;
  48818. this.BARGRAPHAMPLITUDE = 256;
  48819. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  48820. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  48821. this._scene = scene;
  48822. this._audioEngine = BABYLON.Engine.audioEngine;
  48823. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  48824. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  48825. this._webAudioAnalyser.minDecibels = -140;
  48826. this._webAudioAnalyser.maxDecibels = 0;
  48827. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48828. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48829. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  48830. }
  48831. }
  48832. Analyser.prototype.getFrequencyBinCount = function () {
  48833. if (this._audioEngine.canUseWebAudio) {
  48834. return this._webAudioAnalyser.frequencyBinCount;
  48835. }
  48836. else {
  48837. return 0;
  48838. }
  48839. };
  48840. Analyser.prototype.getByteFrequencyData = function () {
  48841. if (this._audioEngine.canUseWebAudio) {
  48842. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48843. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48844. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  48845. }
  48846. return this._byteFreqs;
  48847. };
  48848. Analyser.prototype.getByteTimeDomainData = function () {
  48849. if (this._audioEngine.canUseWebAudio) {
  48850. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48851. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48852. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  48853. }
  48854. return this._byteTime;
  48855. };
  48856. Analyser.prototype.getFloatFrequencyData = function () {
  48857. if (this._audioEngine.canUseWebAudio) {
  48858. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48859. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48860. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  48861. }
  48862. return this._floatFreqs;
  48863. };
  48864. Analyser.prototype.drawDebugCanvas = function () {
  48865. var _this = this;
  48866. if (this._audioEngine.canUseWebAudio) {
  48867. if (!this._debugCanvas) {
  48868. this._debugCanvas = document.createElement("canvas");
  48869. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  48870. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  48871. this._debugCanvas.style.position = "absolute";
  48872. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  48873. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  48874. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  48875. document.body.appendChild(this._debugCanvas);
  48876. this._registerFunc = function () {
  48877. _this.drawDebugCanvas();
  48878. };
  48879. this._scene.registerBeforeRender(this._registerFunc);
  48880. }
  48881. if (this._registerFunc && this._debugCanvasContext) {
  48882. var workingArray = this.getByteFrequencyData();
  48883. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  48884. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  48885. // Draw the frequency domain chart.
  48886. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  48887. var value = workingArray[i];
  48888. var percent = value / this.BARGRAPHAMPLITUDE;
  48889. var height = this.DEBUGCANVASSIZE.height * percent;
  48890. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  48891. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  48892. var hue = i / this.getFrequencyBinCount() * 360;
  48893. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  48894. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  48895. }
  48896. }
  48897. }
  48898. };
  48899. Analyser.prototype.stopDebugCanvas = function () {
  48900. if (this._debugCanvas) {
  48901. if (this._registerFunc) {
  48902. this._scene.unregisterBeforeRender(this._registerFunc);
  48903. this._registerFunc = null;
  48904. }
  48905. document.body.removeChild(this._debugCanvas);
  48906. this._debugCanvas = null;
  48907. this._debugCanvasContext = null;
  48908. }
  48909. };
  48910. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  48911. if (this._audioEngine.canUseWebAudio) {
  48912. inputAudioNode.connect(this._webAudioAnalyser);
  48913. this._webAudioAnalyser.connect(outputAudioNode);
  48914. }
  48915. };
  48916. Analyser.prototype.dispose = function () {
  48917. if (this._audioEngine.canUseWebAudio) {
  48918. this._webAudioAnalyser.disconnect();
  48919. }
  48920. };
  48921. return Analyser;
  48922. }());
  48923. BABYLON.Analyser = Analyser;
  48924. })(BABYLON || (BABYLON = {}));
  48925. //# sourceMappingURL=babylon.analyser.js.map
  48926. var BABYLON;
  48927. (function (BABYLON) {
  48928. var CubeTexture = /** @class */ (function (_super) {
  48929. __extends(CubeTexture, _super);
  48930. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  48931. if (extensions === void 0) { extensions = null; }
  48932. if (noMipmap === void 0) { noMipmap = false; }
  48933. if (files === void 0) { files = null; }
  48934. if (onLoad === void 0) { onLoad = null; }
  48935. if (onError === void 0) { onError = null; }
  48936. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  48937. if (prefiltered === void 0) { prefiltered = false; }
  48938. if (forcedExtension === void 0) { forcedExtension = null; }
  48939. var _this = _super.call(this, scene) || this;
  48940. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  48941. _this.name = rootUrl;
  48942. _this.url = rootUrl;
  48943. _this._noMipmap = noMipmap;
  48944. _this.hasAlpha = false;
  48945. _this._format = format;
  48946. _this._prefiltered = prefiltered;
  48947. _this.isCube = true;
  48948. _this._textureMatrix = BABYLON.Matrix.Identity();
  48949. if (prefiltered) {
  48950. _this.gammaSpace = false;
  48951. }
  48952. if (!rootUrl && !files) {
  48953. return _this;
  48954. }
  48955. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  48956. if (!files) {
  48957. if (!extensions) {
  48958. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  48959. }
  48960. files = [];
  48961. for (var index = 0; index < extensions.length; index++) {
  48962. files.push(rootUrl + extensions[index]);
  48963. }
  48964. _this._extensions = extensions;
  48965. }
  48966. _this._files = files;
  48967. if (!_this._texture) {
  48968. if (!scene.useDelayedTextureLoading) {
  48969. if (prefiltered) {
  48970. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  48971. }
  48972. else {
  48973. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  48974. }
  48975. }
  48976. else {
  48977. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  48978. }
  48979. }
  48980. else if (onLoad) {
  48981. if (_this._texture.isReady) {
  48982. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  48983. }
  48984. else {
  48985. _this._texture.onLoadedObservable.add(onLoad);
  48986. }
  48987. }
  48988. return _this;
  48989. }
  48990. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  48991. return new CubeTexture("", scene, null, noMipmap, files);
  48992. };
  48993. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  48994. if (forcedExtension === void 0) { forcedExtension = null; }
  48995. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  48996. };
  48997. // Methods
  48998. CubeTexture.prototype.delayLoad = function () {
  48999. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49000. return;
  49001. }
  49002. var scene = this.getScene();
  49003. if (!scene) {
  49004. return;
  49005. }
  49006. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49007. this._texture = this._getFromCache(this.url, this._noMipmap);
  49008. if (!this._texture) {
  49009. if (this._prefiltered) {
  49010. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49011. }
  49012. else {
  49013. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49014. }
  49015. }
  49016. };
  49017. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49018. return this._textureMatrix;
  49019. };
  49020. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49021. this._textureMatrix = value;
  49022. };
  49023. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49024. var texture = BABYLON.SerializationHelper.Parse(function () {
  49025. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49026. }, parsedTexture, scene);
  49027. // Animations
  49028. if (parsedTexture.animations) {
  49029. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49030. var parsedAnimation = parsedTexture.animations[animationIndex];
  49031. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49032. }
  49033. }
  49034. return texture;
  49035. };
  49036. CubeTexture.prototype.clone = function () {
  49037. var _this = this;
  49038. return BABYLON.SerializationHelper.Clone(function () {
  49039. var scene = _this.getScene();
  49040. if (!scene) {
  49041. return _this;
  49042. }
  49043. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49044. }, this);
  49045. };
  49046. return CubeTexture;
  49047. }(BABYLON.BaseTexture));
  49048. BABYLON.CubeTexture = CubeTexture;
  49049. })(BABYLON || (BABYLON = {}));
  49050. //# sourceMappingURL=babylon.cubeTexture.js.map
  49051. var BABYLON;
  49052. (function (BABYLON) {
  49053. var RenderTargetTexture = /** @class */ (function (_super) {
  49054. __extends(RenderTargetTexture, _super);
  49055. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49056. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49057. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49058. if (isCube === void 0) { isCube = false; }
  49059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49060. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49061. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49062. if (isMulti === void 0) { isMulti = false; }
  49063. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49064. _this.isCube = isCube;
  49065. /**
  49066. * Use this list to define the list of mesh you want to render.
  49067. */
  49068. _this.renderList = new Array();
  49069. _this.renderParticles = true;
  49070. _this.renderSprites = false;
  49071. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49072. _this.ignoreCameraViewport = false;
  49073. // Events
  49074. /**
  49075. * An event triggered when the texture is unbind.
  49076. * @type {BABYLON.Observable}
  49077. */
  49078. _this.onBeforeBindObservable = new BABYLON.Observable();
  49079. /**
  49080. * An event triggered when the texture is unbind.
  49081. * @type {BABYLON.Observable}
  49082. */
  49083. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49084. /**
  49085. * An event triggered before rendering the texture
  49086. * @type {BABYLON.Observable}
  49087. */
  49088. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49089. /**
  49090. * An event triggered after rendering the texture
  49091. * @type {BABYLON.Observable}
  49092. */
  49093. _this.onAfterRenderObservable = new BABYLON.Observable();
  49094. /**
  49095. * An event triggered after the texture clear
  49096. * @type {BABYLON.Observable}
  49097. */
  49098. _this.onClearObservable = new BABYLON.Observable();
  49099. _this._currentRefreshId = -1;
  49100. _this._refreshRate = 1;
  49101. _this._samples = 1;
  49102. scene = _this.getScene();
  49103. if (!scene) {
  49104. return _this;
  49105. }
  49106. _this.name = name;
  49107. _this.isRenderTarget = true;
  49108. _this._size = size;
  49109. _this._generateMipMaps = generateMipMaps ? true : false;
  49110. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49111. // Rendering groups
  49112. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49113. if (isMulti) {
  49114. return _this;
  49115. }
  49116. _this._renderTargetOptions = {
  49117. generateMipMaps: generateMipMaps,
  49118. type: type,
  49119. samplingMode: samplingMode,
  49120. generateDepthBuffer: generateDepthBuffer,
  49121. generateStencilBuffer: generateStencilBuffer
  49122. };
  49123. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49124. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49125. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49126. }
  49127. if (isCube) {
  49128. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  49129. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49130. _this._textureMatrix = BABYLON.Matrix.Identity();
  49131. }
  49132. else {
  49133. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  49134. }
  49135. return _this;
  49136. }
  49137. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49138. get: function () {
  49139. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49140. },
  49141. enumerable: true,
  49142. configurable: true
  49143. });
  49144. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49145. get: function () {
  49146. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49147. },
  49148. enumerable: true,
  49149. configurable: true
  49150. });
  49151. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49152. get: function () {
  49153. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49154. },
  49155. enumerable: true,
  49156. configurable: true
  49157. });
  49158. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49159. set: function (callback) {
  49160. if (this._onAfterUnbindObserver) {
  49161. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49162. }
  49163. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49164. },
  49165. enumerable: true,
  49166. configurable: true
  49167. });
  49168. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  49169. set: function (callback) {
  49170. if (this._onBeforeRenderObserver) {
  49171. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49172. }
  49173. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49174. },
  49175. enumerable: true,
  49176. configurable: true
  49177. });
  49178. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49179. set: function (callback) {
  49180. if (this._onAfterRenderObserver) {
  49181. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49182. }
  49183. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49184. },
  49185. enumerable: true,
  49186. configurable: true
  49187. });
  49188. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  49189. set: function (callback) {
  49190. if (this._onClearObserver) {
  49191. this.onClearObservable.remove(this._onClearObserver);
  49192. }
  49193. this._onClearObserver = this.onClearObservable.add(callback);
  49194. },
  49195. enumerable: true,
  49196. configurable: true
  49197. });
  49198. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  49199. get: function () {
  49200. return this._renderTargetOptions;
  49201. },
  49202. enumerable: true,
  49203. configurable: true
  49204. });
  49205. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  49206. get: function () {
  49207. return this._samples;
  49208. },
  49209. set: function (value) {
  49210. if (this._samples === value) {
  49211. return;
  49212. }
  49213. var scene = this.getScene();
  49214. if (!scene) {
  49215. return;
  49216. }
  49217. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  49218. },
  49219. enumerable: true,
  49220. configurable: true
  49221. });
  49222. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  49223. this._currentRefreshId = -1;
  49224. };
  49225. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  49226. get: function () {
  49227. return this._refreshRate;
  49228. },
  49229. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49230. set: function (value) {
  49231. this._refreshRate = value;
  49232. this.resetRefreshCounter();
  49233. },
  49234. enumerable: true,
  49235. configurable: true
  49236. });
  49237. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  49238. if (!this._postProcessManager) {
  49239. var scene = this.getScene();
  49240. if (!scene) {
  49241. return;
  49242. }
  49243. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  49244. this._postProcesses = new Array();
  49245. }
  49246. this._postProcesses.push(postProcess);
  49247. this._postProcesses[0].autoClear = false;
  49248. };
  49249. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  49250. if (!this._postProcesses) {
  49251. return;
  49252. }
  49253. if (dispose) {
  49254. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  49255. var postProcess = _a[_i];
  49256. postProcess.dispose();
  49257. }
  49258. }
  49259. this._postProcesses = [];
  49260. };
  49261. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  49262. if (!this._postProcesses) {
  49263. return;
  49264. }
  49265. var index = this._postProcesses.indexOf(postProcess);
  49266. if (index === -1) {
  49267. return;
  49268. }
  49269. this._postProcesses.splice(index, 1);
  49270. if (this._postProcesses.length > 0) {
  49271. this._postProcesses[0].autoClear = false;
  49272. }
  49273. };
  49274. RenderTargetTexture.prototype._shouldRender = function () {
  49275. if (this._currentRefreshId === -1) {
  49276. this._currentRefreshId = 1;
  49277. return true;
  49278. }
  49279. if (this.refreshRate === this._currentRefreshId) {
  49280. this._currentRefreshId = 1;
  49281. return true;
  49282. }
  49283. this._currentRefreshId++;
  49284. return false;
  49285. };
  49286. RenderTargetTexture.prototype.getRenderSize = function () {
  49287. return this._size;
  49288. };
  49289. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  49290. get: function () {
  49291. return true;
  49292. },
  49293. enumerable: true,
  49294. configurable: true
  49295. });
  49296. RenderTargetTexture.prototype.scale = function (ratio) {
  49297. var newSize = this._size * ratio;
  49298. this.resize(newSize);
  49299. };
  49300. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  49301. if (this.isCube) {
  49302. return this._textureMatrix;
  49303. }
  49304. return _super.prototype.getReflectionTextureMatrix.call(this);
  49305. };
  49306. RenderTargetTexture.prototype.resize = function (size) {
  49307. this.releaseInternalTexture();
  49308. var scene = this.getScene();
  49309. if (!scene) {
  49310. return;
  49311. }
  49312. if (this.isCube) {
  49313. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  49314. }
  49315. else {
  49316. this._texture = scene.getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  49317. }
  49318. this._size = size;
  49319. };
  49320. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  49321. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  49322. if (dumpForDebug === void 0) { dumpForDebug = false; }
  49323. var scene = this.getScene();
  49324. if (!scene) {
  49325. return;
  49326. }
  49327. var engine = scene.getEngine();
  49328. if (this.useCameraPostProcesses !== undefined) {
  49329. useCameraPostProcess = this.useCameraPostProcesses;
  49330. }
  49331. if (this._waitingRenderList) {
  49332. this.renderList = [];
  49333. for (var index = 0; index < this._waitingRenderList.length; index++) {
  49334. var id = this._waitingRenderList[index];
  49335. var mesh_1 = scene.getMeshByID(id);
  49336. if (mesh_1) {
  49337. this.renderList.push(mesh_1);
  49338. }
  49339. }
  49340. delete this._waitingRenderList;
  49341. }
  49342. // Is predicate defined?
  49343. if (this.renderListPredicate) {
  49344. if (this.renderList) {
  49345. this.renderList.splice(0); // Clear previous renderList
  49346. }
  49347. else {
  49348. this.renderList = [];
  49349. }
  49350. var scene = this.getScene();
  49351. if (!scene) {
  49352. return;
  49353. }
  49354. var sceneMeshes = scene.meshes;
  49355. for (var index = 0; index < sceneMeshes.length; index++) {
  49356. var mesh = sceneMeshes[index];
  49357. if (this.renderListPredicate(mesh)) {
  49358. this.renderList.push(mesh);
  49359. }
  49360. }
  49361. }
  49362. this.onBeforeBindObservable.notifyObservers(this);
  49363. // Set custom projection.
  49364. // Needs to be before binding to prevent changing the aspect ratio.
  49365. var camera;
  49366. if (this.activeCamera) {
  49367. camera = this.activeCamera;
  49368. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  49369. if (this.activeCamera !== scene.activeCamera) {
  49370. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  49371. }
  49372. }
  49373. else {
  49374. camera = scene.activeCamera;
  49375. if (camera) {
  49376. engine.setViewport(camera.viewport, this._size, this._size);
  49377. }
  49378. }
  49379. // Prepare renderingManager
  49380. this._renderingManager.reset();
  49381. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  49382. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  49383. var sceneRenderId = scene.getRenderId();
  49384. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  49385. var mesh = currentRenderList[meshIndex];
  49386. if (mesh) {
  49387. if (!mesh.isReady()) {
  49388. // Reset _currentRefreshId
  49389. this.resetRefreshCounter();
  49390. continue;
  49391. }
  49392. mesh._preActivateForIntermediateRendering(sceneRenderId);
  49393. var isMasked = void 0;
  49394. if (!this.renderList && camera) {
  49395. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  49396. }
  49397. else {
  49398. isMasked = false;
  49399. }
  49400. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  49401. mesh._activate(sceneRenderId);
  49402. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49403. var subMesh = mesh.subMeshes[subIndex];
  49404. scene._activeIndices.addCount(subMesh.indexCount, false);
  49405. this._renderingManager.dispatch(subMesh);
  49406. }
  49407. }
  49408. }
  49409. }
  49410. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  49411. var particleSystem = scene.particleSystems[particleIndex];
  49412. var emitter = particleSystem.emitter;
  49413. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  49414. continue;
  49415. }
  49416. if (currentRenderList.indexOf(emitter) >= 0) {
  49417. this._renderingManager.dispatchParticles(particleSystem);
  49418. }
  49419. }
  49420. if (this.isCube) {
  49421. for (var face = 0; face < 6; face++) {
  49422. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49423. scene.incrementRenderId();
  49424. scene.resetCachedMaterial();
  49425. }
  49426. }
  49427. else {
  49428. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49429. }
  49430. this.onAfterUnbindObservable.notifyObservers(this);
  49431. if (scene.activeCamera) {
  49432. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  49433. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  49434. }
  49435. engine.setViewport(scene.activeCamera.viewport);
  49436. }
  49437. scene.resetCachedMaterial();
  49438. };
  49439. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  49440. var _this = this;
  49441. var scene = this.getScene();
  49442. if (!scene) {
  49443. return;
  49444. }
  49445. var engine = scene.getEngine();
  49446. if (!this._texture) {
  49447. return;
  49448. }
  49449. // Bind
  49450. if (this._postProcessManager) {
  49451. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  49452. }
  49453. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  49454. if (this._texture) {
  49455. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  49456. }
  49457. }
  49458. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  49459. // Clear
  49460. if (this.onClearObservable.hasObservers()) {
  49461. this.onClearObservable.notifyObservers(engine);
  49462. }
  49463. else {
  49464. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  49465. }
  49466. if (!this._doNotChangeAspectRatio) {
  49467. scene.updateTransformMatrix(true);
  49468. }
  49469. // Render
  49470. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  49471. if (this._postProcessManager) {
  49472. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  49473. }
  49474. else if (useCameraPostProcess) {
  49475. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  49476. }
  49477. if (!this._doNotChangeAspectRatio) {
  49478. scene.updateTransformMatrix(true);
  49479. }
  49480. // Dump ?
  49481. if (dumpForDebug) {
  49482. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  49483. }
  49484. // Unbind
  49485. if (!this.isCube || faceIndex === 5) {
  49486. if (this.isCube) {
  49487. if (faceIndex === 5) {
  49488. engine.generateMipMapsForCubemap(this._texture);
  49489. }
  49490. }
  49491. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  49492. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  49493. });
  49494. }
  49495. else {
  49496. this.onAfterRenderObservable.notifyObservers(faceIndex);
  49497. }
  49498. };
  49499. /**
  49500. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  49501. * This allowed control for front to back rendering or reversly depending of the special needs.
  49502. *
  49503. * @param renderingGroupId The rendering group id corresponding to its index
  49504. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  49505. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  49506. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  49507. */
  49508. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  49509. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  49510. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  49511. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  49512. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  49513. };
  49514. /**
  49515. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  49516. *
  49517. * @param renderingGroupId The rendering group id corresponding to its index
  49518. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  49519. */
  49520. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  49521. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  49522. };
  49523. RenderTargetTexture.prototype.clone = function () {
  49524. var textureSize = this.getSize();
  49525. 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);
  49526. // Base texture
  49527. newTexture.hasAlpha = this.hasAlpha;
  49528. newTexture.level = this.level;
  49529. // RenderTarget Texture
  49530. newTexture.coordinatesMode = this.coordinatesMode;
  49531. if (this.renderList) {
  49532. newTexture.renderList = this.renderList.slice(0);
  49533. }
  49534. return newTexture;
  49535. };
  49536. RenderTargetTexture.prototype.serialize = function () {
  49537. if (!this.name) {
  49538. return null;
  49539. }
  49540. var serializationObject = _super.prototype.serialize.call(this);
  49541. serializationObject.renderTargetSize = this.getRenderSize();
  49542. serializationObject.renderList = [];
  49543. if (this.renderList) {
  49544. for (var index = 0; index < this.renderList.length; index++) {
  49545. serializationObject.renderList.push(this.renderList[index].id);
  49546. }
  49547. }
  49548. return serializationObject;
  49549. };
  49550. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  49551. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  49552. var objBuffer = this.getInternalTexture();
  49553. var scene = this.getScene();
  49554. if (objBuffer && scene) {
  49555. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  49556. }
  49557. };
  49558. RenderTargetTexture.prototype.dispose = function () {
  49559. if (this._postProcessManager) {
  49560. this._postProcessManager.dispose();
  49561. this._postProcessManager = null;
  49562. }
  49563. this.clearPostProcesses(true);
  49564. this.renderList = null;
  49565. // Remove from custom render targets
  49566. var scene = this.getScene();
  49567. if (!scene) {
  49568. return;
  49569. }
  49570. var index = scene.customRenderTargets.indexOf(this);
  49571. if (index >= 0) {
  49572. scene.customRenderTargets.splice(index, 1);
  49573. }
  49574. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  49575. var camera = _a[_i];
  49576. index = camera.customRenderTargets.indexOf(this);
  49577. if (index >= 0) {
  49578. camera.customRenderTargets.splice(index, 1);
  49579. }
  49580. }
  49581. _super.prototype.dispose.call(this);
  49582. };
  49583. RenderTargetTexture.prototype._rebuild = function () {
  49584. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  49585. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  49586. }
  49587. if (this._postProcessManager) {
  49588. this._postProcessManager._rebuild();
  49589. }
  49590. };
  49591. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  49592. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  49593. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  49594. return RenderTargetTexture;
  49595. }(BABYLON.Texture));
  49596. BABYLON.RenderTargetTexture = RenderTargetTexture;
  49597. })(BABYLON || (BABYLON = {}));
  49598. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  49599. var BABYLON;
  49600. (function (BABYLON) {
  49601. ;
  49602. var MultiRenderTarget = /** @class */ (function (_super) {
  49603. __extends(MultiRenderTarget, _super);
  49604. function MultiRenderTarget(name, size, count, scene, options) {
  49605. var _this = this;
  49606. options = options || {};
  49607. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  49608. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  49609. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  49610. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  49611. _this._engine = scene.getEngine();
  49612. if (!_this.isSupported) {
  49613. _this.dispose();
  49614. return;
  49615. }
  49616. var types = [];
  49617. var samplingModes = [];
  49618. for (var i = 0; i < count; i++) {
  49619. if (options.types && options.types[i]) {
  49620. types.push(options.types[i]);
  49621. }
  49622. else {
  49623. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  49624. }
  49625. if (options.samplingModes && options.samplingModes[i]) {
  49626. samplingModes.push(options.samplingModes[i]);
  49627. }
  49628. else {
  49629. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49630. }
  49631. }
  49632. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  49633. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  49634. _this._count = count;
  49635. _this._size = size;
  49636. _this._multiRenderTargetOptions = {
  49637. samplingModes: samplingModes,
  49638. generateMipMaps: generateMipMaps,
  49639. generateDepthBuffer: generateDepthBuffer,
  49640. generateStencilBuffer: generateStencilBuffer,
  49641. generateDepthTexture: generateDepthTexture,
  49642. types: types,
  49643. textureCount: count
  49644. };
  49645. _this._createInternalTextures();
  49646. _this._createTextures();
  49647. return _this;
  49648. }
  49649. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  49650. get: function () {
  49651. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  49652. },
  49653. enumerable: true,
  49654. configurable: true
  49655. });
  49656. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  49657. get: function () {
  49658. return this._textures;
  49659. },
  49660. enumerable: true,
  49661. configurable: true
  49662. });
  49663. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  49664. get: function () {
  49665. return this._textures[this._textures.length - 1];
  49666. },
  49667. enumerable: true,
  49668. configurable: true
  49669. });
  49670. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  49671. set: function (wrap) {
  49672. if (this._textures) {
  49673. for (var i = 0; i < this._textures.length; i++) {
  49674. this._textures[i].wrapU = wrap;
  49675. }
  49676. }
  49677. },
  49678. enumerable: true,
  49679. configurable: true
  49680. });
  49681. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  49682. set: function (wrap) {
  49683. if (this._textures) {
  49684. for (var i = 0; i < this._textures.length; i++) {
  49685. this._textures[i].wrapV = wrap;
  49686. }
  49687. }
  49688. },
  49689. enumerable: true,
  49690. configurable: true
  49691. });
  49692. MultiRenderTarget.prototype._rebuild = function () {
  49693. this.releaseInternalTextures();
  49694. this._createInternalTextures();
  49695. for (var i = 0; i < this._internalTextures.length; i++) {
  49696. var texture = this._textures[i];
  49697. texture._texture = this._internalTextures[i];
  49698. }
  49699. // Keeps references to frame buffer and stencil/depth buffer
  49700. this._texture = this._internalTextures[0];
  49701. };
  49702. MultiRenderTarget.prototype._createInternalTextures = function () {
  49703. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  49704. };
  49705. MultiRenderTarget.prototype._createTextures = function () {
  49706. this._textures = [];
  49707. for (var i = 0; i < this._internalTextures.length; i++) {
  49708. var texture = new BABYLON.Texture(null, this.getScene());
  49709. texture._texture = this._internalTextures[i];
  49710. this._textures.push(texture);
  49711. }
  49712. // Keeps references to frame buffer and stencil/depth buffer
  49713. this._texture = this._internalTextures[0];
  49714. };
  49715. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  49716. get: function () {
  49717. return this._samples;
  49718. },
  49719. set: function (value) {
  49720. if (this._samples === value) {
  49721. return;
  49722. }
  49723. for (var i = 0; i < this._internalTextures.length; i++) {
  49724. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  49725. }
  49726. },
  49727. enumerable: true,
  49728. configurable: true
  49729. });
  49730. MultiRenderTarget.prototype.resize = function (size) {
  49731. this.releaseInternalTextures();
  49732. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  49733. this._createInternalTextures();
  49734. };
  49735. MultiRenderTarget.prototype.dispose = function () {
  49736. this.releaseInternalTextures();
  49737. _super.prototype.dispose.call(this);
  49738. };
  49739. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  49740. if (!this._internalTextures) {
  49741. return;
  49742. }
  49743. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  49744. if (this._internalTextures[i] !== undefined) {
  49745. this._internalTextures[i].dispose();
  49746. this._internalTextures.splice(i, 1);
  49747. }
  49748. }
  49749. };
  49750. return MultiRenderTarget;
  49751. }(BABYLON.RenderTargetTexture));
  49752. BABYLON.MultiRenderTarget = MultiRenderTarget;
  49753. })(BABYLON || (BABYLON = {}));
  49754. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  49755. var BABYLON;
  49756. (function (BABYLON) {
  49757. var MirrorTexture = /** @class */ (function (_super) {
  49758. __extends(MirrorTexture, _super);
  49759. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  49760. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49761. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49762. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49763. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  49764. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  49765. _this._transformMatrix = BABYLON.Matrix.Zero();
  49766. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  49767. _this._blurKernelX = 0;
  49768. _this._blurKernelY = 0;
  49769. _this._blurRatio = 1.0;
  49770. _this.ignoreCameraViewport = true;
  49771. _this.onBeforeRenderObservable.add(function () {
  49772. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  49773. _this._savedViewMatrix = scene.getViewMatrix();
  49774. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  49775. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  49776. scene.clipPlane = _this.mirrorPlane;
  49777. scene.getEngine().cullBackFaces = false;
  49778. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  49779. });
  49780. _this.onAfterRenderObservable.add(function () {
  49781. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  49782. scene.getEngine().cullBackFaces = true;
  49783. scene._mirroredCameraPosition = null;
  49784. delete scene.clipPlane;
  49785. });
  49786. return _this;
  49787. }
  49788. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  49789. get: function () {
  49790. return this._blurRatio;
  49791. },
  49792. set: function (value) {
  49793. if (this._blurRatio === value) {
  49794. return;
  49795. }
  49796. this._blurRatio = value;
  49797. this._preparePostProcesses();
  49798. },
  49799. enumerable: true,
  49800. configurable: true
  49801. });
  49802. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  49803. set: function (value) {
  49804. this.blurKernelX = value;
  49805. this.blurKernelY = value;
  49806. },
  49807. enumerable: true,
  49808. configurable: true
  49809. });
  49810. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  49811. get: function () {
  49812. return this._blurKernelX;
  49813. },
  49814. set: function (value) {
  49815. if (this._blurKernelX === value) {
  49816. return;
  49817. }
  49818. this._blurKernelX = value;
  49819. this._preparePostProcesses();
  49820. },
  49821. enumerable: true,
  49822. configurable: true
  49823. });
  49824. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  49825. get: function () {
  49826. return this._blurKernelY;
  49827. },
  49828. set: function (value) {
  49829. if (this._blurKernelY === value) {
  49830. return;
  49831. }
  49832. this._blurKernelY = value;
  49833. this._preparePostProcesses();
  49834. },
  49835. enumerable: true,
  49836. configurable: true
  49837. });
  49838. MirrorTexture.prototype._preparePostProcesses = function () {
  49839. this.clearPostProcesses(true);
  49840. if (this._blurKernelX && this._blurKernelY) {
  49841. var engine = this.getScene().getEngine();
  49842. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49843. 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);
  49844. this._blurX.autoClear = false;
  49845. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  49846. this._blurX.outputTexture = this._texture;
  49847. }
  49848. else {
  49849. this._blurX.alwaysForcePOT = true;
  49850. }
  49851. 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);
  49852. this._blurY.autoClear = false;
  49853. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  49854. this.addPostProcess(this._blurX);
  49855. this.addPostProcess(this._blurY);
  49856. }
  49857. };
  49858. MirrorTexture.prototype.clone = function () {
  49859. var scene = this.getScene();
  49860. if (!scene) {
  49861. return this;
  49862. }
  49863. var textureSize = this.getSize();
  49864. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  49865. // Base texture
  49866. newTexture.hasAlpha = this.hasAlpha;
  49867. newTexture.level = this.level;
  49868. // Mirror Texture
  49869. newTexture.mirrorPlane = this.mirrorPlane.clone();
  49870. if (this.renderList) {
  49871. newTexture.renderList = this.renderList.slice(0);
  49872. }
  49873. return newTexture;
  49874. };
  49875. MirrorTexture.prototype.serialize = function () {
  49876. if (!this.name) {
  49877. return null;
  49878. }
  49879. var serializationObject = _super.prototype.serialize.call(this);
  49880. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  49881. return serializationObject;
  49882. };
  49883. return MirrorTexture;
  49884. }(BABYLON.RenderTargetTexture));
  49885. BABYLON.MirrorTexture = MirrorTexture;
  49886. })(BABYLON || (BABYLON = {}));
  49887. //# sourceMappingURL=babylon.mirrorTexture.js.map
  49888. var BABYLON;
  49889. (function (BABYLON) {
  49890. /**
  49891. * Creates a refraction texture used by refraction channel of the standard material.
  49892. * @param name the texture name
  49893. * @param size size of the underlying texture
  49894. * @param scene root scene
  49895. */
  49896. var RefractionTexture = /** @class */ (function (_super) {
  49897. __extends(RefractionTexture, _super);
  49898. function RefractionTexture(name, size, scene, generateMipMaps) {
  49899. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  49900. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  49901. _this.depth = 2.0;
  49902. _this.onBeforeRenderObservable.add(function () {
  49903. scene.clipPlane = _this.refractionPlane;
  49904. });
  49905. _this.onAfterRenderObservable.add(function () {
  49906. delete scene.clipPlane;
  49907. });
  49908. return _this;
  49909. }
  49910. RefractionTexture.prototype.clone = function () {
  49911. var scene = this.getScene();
  49912. if (!scene) {
  49913. return this;
  49914. }
  49915. var textureSize = this.getSize();
  49916. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  49917. // Base texture
  49918. newTexture.hasAlpha = this.hasAlpha;
  49919. newTexture.level = this.level;
  49920. // Refraction Texture
  49921. newTexture.refractionPlane = this.refractionPlane.clone();
  49922. if (this.renderList) {
  49923. newTexture.renderList = this.renderList.slice(0);
  49924. }
  49925. newTexture.depth = this.depth;
  49926. return newTexture;
  49927. };
  49928. RefractionTexture.prototype.serialize = function () {
  49929. if (!this.name) {
  49930. return null;
  49931. }
  49932. var serializationObject = _super.prototype.serialize.call(this);
  49933. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  49934. serializationObject.depth = this.depth;
  49935. return serializationObject;
  49936. };
  49937. return RefractionTexture;
  49938. }(BABYLON.RenderTargetTexture));
  49939. BABYLON.RefractionTexture = RefractionTexture;
  49940. })(BABYLON || (BABYLON = {}));
  49941. //# sourceMappingURL=babylon.refractionTexture.js.map
  49942. var BABYLON;
  49943. (function (BABYLON) {
  49944. var DynamicTexture = /** @class */ (function (_super) {
  49945. __extends(DynamicTexture, _super);
  49946. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  49947. if (scene === void 0) { scene = null; }
  49948. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49949. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49950. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  49951. _this.name = name;
  49952. _this._engine = _this.getScene().getEngine();
  49953. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49954. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49955. _this._generateMipMaps = generateMipMaps;
  49956. if (options.getContext) {
  49957. _this._canvas = options;
  49958. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  49959. }
  49960. else {
  49961. _this._canvas = document.createElement("canvas");
  49962. if (options.width) {
  49963. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  49964. }
  49965. else {
  49966. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  49967. }
  49968. }
  49969. var textureSize = _this.getSize();
  49970. _this._canvas.width = textureSize.width;
  49971. _this._canvas.height = textureSize.height;
  49972. _this._context = _this._canvas.getContext("2d");
  49973. return _this;
  49974. }
  49975. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  49976. get: function () {
  49977. return true;
  49978. },
  49979. enumerable: true,
  49980. configurable: true
  49981. });
  49982. DynamicTexture.prototype._recreate = function (textureSize) {
  49983. this._canvas.width = textureSize.width;
  49984. this._canvas.height = textureSize.height;
  49985. this.releaseInternalTexture();
  49986. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  49987. };
  49988. DynamicTexture.prototype.scale = function (ratio) {
  49989. var textureSize = this.getSize();
  49990. textureSize.width *= ratio;
  49991. textureSize.height *= ratio;
  49992. this._recreate(textureSize);
  49993. };
  49994. DynamicTexture.prototype.scaleTo = function (width, height) {
  49995. var textureSize = this.getSize();
  49996. textureSize.width = width;
  49997. textureSize.height = height;
  49998. this._recreate(textureSize);
  49999. };
  50000. DynamicTexture.prototype.getContext = function () {
  50001. return this._context;
  50002. };
  50003. DynamicTexture.prototype.clear = function () {
  50004. var size = this.getSize();
  50005. this._context.fillRect(0, 0, size.width, size.height);
  50006. };
  50007. DynamicTexture.prototype.update = function (invertY) {
  50008. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50009. };
  50010. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50011. if (update === void 0) { update = true; }
  50012. var size = this.getSize();
  50013. if (clearColor) {
  50014. this._context.fillStyle = clearColor;
  50015. this._context.fillRect(0, 0, size.width, size.height);
  50016. }
  50017. this._context.font = font;
  50018. if (x === null || x === undefined) {
  50019. var textSize = this._context.measureText(text);
  50020. x = (size.width - textSize.width) / 2;
  50021. }
  50022. if (y === null || y === undefined) {
  50023. var fontSize = parseInt((font.replace(/\D/g, '')));
  50024. ;
  50025. y = (size.height / 2) + (fontSize / 3.65);
  50026. }
  50027. this._context.fillStyle = color;
  50028. this._context.fillText(text, x, y);
  50029. if (update) {
  50030. this.update(invertY);
  50031. }
  50032. };
  50033. DynamicTexture.prototype.clone = function () {
  50034. var scene = this.getScene();
  50035. if (!scene) {
  50036. return this;
  50037. }
  50038. var textureSize = this.getSize();
  50039. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50040. // Base texture
  50041. newTexture.hasAlpha = this.hasAlpha;
  50042. newTexture.level = this.level;
  50043. // Dynamic Texture
  50044. newTexture.wrapU = this.wrapU;
  50045. newTexture.wrapV = this.wrapV;
  50046. return newTexture;
  50047. };
  50048. DynamicTexture.prototype._rebuild = function () {
  50049. this.update();
  50050. };
  50051. return DynamicTexture;
  50052. }(BABYLON.Texture));
  50053. BABYLON.DynamicTexture = DynamicTexture;
  50054. })(BABYLON || (BABYLON = {}));
  50055. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50056. var BABYLON;
  50057. (function (BABYLON) {
  50058. var VideoTexture = /** @class */ (function (_super) {
  50059. __extends(VideoTexture, _super);
  50060. /**
  50061. * Creates a video texture.
  50062. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50063. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50064. * @param {BABYLON.Scene} scene is obviously the current scene.
  50065. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50066. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50067. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50068. */
  50069. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50070. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50071. if (invertY === void 0) { invertY = false; }
  50072. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50073. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50074. _this._autoLaunch = true;
  50075. var urls = null;
  50076. _this.name = name;
  50077. if (urlsOrVideo instanceof HTMLVideoElement) {
  50078. _this.video = urlsOrVideo;
  50079. }
  50080. else {
  50081. urls = urlsOrVideo;
  50082. _this.video = document.createElement("video");
  50083. _this.video.autoplay = false;
  50084. _this.video.loop = true;
  50085. }
  50086. _this._engine = _this.getScene().getEngine();
  50087. _this._generateMipMaps = generateMipMaps;
  50088. _this._samplingMode = samplingMode;
  50089. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  50090. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50091. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50092. }
  50093. else {
  50094. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50095. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50096. _this._generateMipMaps = false;
  50097. }
  50098. if (urls) {
  50099. _this.video.addEventListener("canplay", function () {
  50100. _this._createTexture();
  50101. });
  50102. urls.forEach(function (url) {
  50103. var source = document.createElement("source");
  50104. source.src = url;
  50105. _this.video.appendChild(source);
  50106. });
  50107. }
  50108. else {
  50109. _this._createTexture();
  50110. }
  50111. _this._lastUpdate = BABYLON.Tools.Now;
  50112. return _this;
  50113. }
  50114. VideoTexture.prototype.__setTextureReady = function () {
  50115. if (this._texture) {
  50116. this._texture.isReady = true;
  50117. }
  50118. };
  50119. VideoTexture.prototype._createTexture = function () {
  50120. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  50121. if (this._autoLaunch) {
  50122. this._autoLaunch = false;
  50123. this.video.play();
  50124. }
  50125. this._setTextureReady = this.__setTextureReady.bind(this);
  50126. this.video.addEventListener("playing", this._setTextureReady);
  50127. };
  50128. VideoTexture.prototype._rebuild = function () {
  50129. this.update();
  50130. };
  50131. VideoTexture.prototype.update = function () {
  50132. var now = BABYLON.Tools.Now;
  50133. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  50134. return false;
  50135. }
  50136. this._lastUpdate = now;
  50137. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  50138. return true;
  50139. };
  50140. VideoTexture.prototype.dispose = function () {
  50141. _super.prototype.dispose.call(this);
  50142. this.video.removeEventListener("playing", this._setTextureReady);
  50143. };
  50144. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  50145. var video = document.createElement("video");
  50146. var constraintsDeviceId;
  50147. if (constraints && constraints.deviceId) {
  50148. constraintsDeviceId = {
  50149. exact: constraints.deviceId
  50150. };
  50151. }
  50152. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  50153. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  50154. if (navigator.getUserMedia) {
  50155. navigator.getUserMedia({
  50156. video: {
  50157. deviceId: constraintsDeviceId,
  50158. width: {
  50159. min: (constraints && constraints.minWidth) || 256,
  50160. max: (constraints && constraints.maxWidth) || 640
  50161. },
  50162. height: {
  50163. min: (constraints && constraints.minHeight) || 256,
  50164. max: (constraints && constraints.maxHeight) || 480
  50165. }
  50166. }
  50167. }, function (stream) {
  50168. if (video.mozSrcObject !== undefined) {
  50169. video.mozSrcObject = stream;
  50170. }
  50171. else {
  50172. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  50173. }
  50174. video.play();
  50175. if (onReady) {
  50176. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  50177. }
  50178. }, function (e) {
  50179. BABYLON.Tools.Error(e.name);
  50180. });
  50181. }
  50182. };
  50183. return VideoTexture;
  50184. }(BABYLON.Texture));
  50185. BABYLON.VideoTexture = VideoTexture;
  50186. })(BABYLON || (BABYLON = {}));
  50187. //# sourceMappingURL=babylon.videoTexture.js.map
  50188. var BABYLON;
  50189. (function (BABYLON) {
  50190. var RawTexture = /** @class */ (function (_super) {
  50191. __extends(RawTexture, _super);
  50192. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50193. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50194. if (invertY === void 0) { invertY = false; }
  50195. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50196. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50197. _this.format = format;
  50198. _this._engine = scene.getEngine();
  50199. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50200. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50201. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50202. return _this;
  50203. }
  50204. RawTexture.prototype.update = function (data) {
  50205. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  50206. };
  50207. // Statics
  50208. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50209. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50210. if (invertY === void 0) { invertY = false; }
  50211. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50212. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50213. };
  50214. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50215. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50216. if (invertY === void 0) { invertY = false; }
  50217. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50218. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50219. };
  50220. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50221. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50222. if (invertY === void 0) { invertY = false; }
  50223. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50224. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50225. };
  50226. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50227. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50228. if (invertY === void 0) { invertY = false; }
  50229. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50230. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50231. };
  50232. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50233. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50234. if (invertY === void 0) { invertY = false; }
  50235. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50236. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50237. };
  50238. return RawTexture;
  50239. }(BABYLON.Texture));
  50240. BABYLON.RawTexture = RawTexture;
  50241. })(BABYLON || (BABYLON = {}));
  50242. //# sourceMappingURL=babylon.rawTexture.js.map
  50243. var BABYLON;
  50244. (function (BABYLON) {
  50245. var PostProcess = /** @class */ (function () {
  50246. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  50247. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  50248. if (defines === void 0) { defines = null; }
  50249. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50250. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  50251. if (blockCompilation === void 0) { blockCompilation = false; }
  50252. this.name = name;
  50253. this.width = -1;
  50254. this.height = -1;
  50255. this.autoClear = true;
  50256. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  50257. /*
  50258. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  50259. Can only be used on a single postprocess or on the last one of a chain.
  50260. */
  50261. this.enablePixelPerfectMode = false;
  50262. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  50263. this.alwaysForcePOT = false;
  50264. this.samples = 1;
  50265. this.adaptScaleToCurrentViewport = false;
  50266. this._reusable = false;
  50267. this._textures = new BABYLON.SmartArray(2);
  50268. this._currentRenderTextureInd = 0;
  50269. this._scaleRatio = new BABYLON.Vector2(1, 1);
  50270. this._texelSize = BABYLON.Vector2.Zero();
  50271. // Events
  50272. /**
  50273. * An event triggered when the postprocess is activated.
  50274. * @type {BABYLON.Observable}
  50275. */
  50276. this.onActivateObservable = new BABYLON.Observable();
  50277. /**
  50278. * An event triggered when the postprocess changes its size.
  50279. * @type {BABYLON.Observable}
  50280. */
  50281. this.onSizeChangedObservable = new BABYLON.Observable();
  50282. /**
  50283. * An event triggered when the postprocess applies its effect.
  50284. * @type {BABYLON.Observable}
  50285. */
  50286. this.onApplyObservable = new BABYLON.Observable();
  50287. /**
  50288. * An event triggered before rendering the postprocess
  50289. * @type {BABYLON.Observable}
  50290. */
  50291. this.onBeforeRenderObservable = new BABYLON.Observable();
  50292. /**
  50293. * An event triggered after rendering the postprocess
  50294. * @type {BABYLON.Observable}
  50295. */
  50296. this.onAfterRenderObservable = new BABYLON.Observable();
  50297. if (camera != null) {
  50298. this._camera = camera;
  50299. this._scene = camera.getScene();
  50300. camera.attachPostProcess(this);
  50301. this._engine = this._scene.getEngine();
  50302. this._scene.postProcesses.push(this);
  50303. }
  50304. else if (engine) {
  50305. this._engine = engine;
  50306. this._engine.postProcesses.push(this);
  50307. }
  50308. this._options = options;
  50309. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  50310. this._reusable = reusable || false;
  50311. this._textureType = textureType;
  50312. this._samplers = samplers || [];
  50313. this._samplers.push("textureSampler");
  50314. this._fragmentUrl = fragmentUrl;
  50315. this._vertexUrl = vertexUrl;
  50316. this._parameters = parameters || [];
  50317. this._parameters.push("scale");
  50318. this._indexParameters = indexParameters;
  50319. if (!blockCompilation) {
  50320. this.updateEffect(defines);
  50321. }
  50322. }
  50323. Object.defineProperty(PostProcess.prototype, "onActivate", {
  50324. set: function (callback) {
  50325. if (this._onActivateObserver) {
  50326. this.onActivateObservable.remove(this._onActivateObserver);
  50327. }
  50328. if (callback) {
  50329. this._onActivateObserver = this.onActivateObservable.add(callback);
  50330. }
  50331. },
  50332. enumerable: true,
  50333. configurable: true
  50334. });
  50335. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  50336. set: function (callback) {
  50337. if (this._onSizeChangedObserver) {
  50338. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  50339. }
  50340. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  50341. },
  50342. enumerable: true,
  50343. configurable: true
  50344. });
  50345. Object.defineProperty(PostProcess.prototype, "onApply", {
  50346. set: function (callback) {
  50347. if (this._onApplyObserver) {
  50348. this.onApplyObservable.remove(this._onApplyObserver);
  50349. }
  50350. this._onApplyObserver = this.onApplyObservable.add(callback);
  50351. },
  50352. enumerable: true,
  50353. configurable: true
  50354. });
  50355. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  50356. set: function (callback) {
  50357. if (this._onBeforeRenderObserver) {
  50358. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50359. }
  50360. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50361. },
  50362. enumerable: true,
  50363. configurable: true
  50364. });
  50365. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  50366. set: function (callback) {
  50367. if (this._onAfterRenderObserver) {
  50368. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50369. }
  50370. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50371. },
  50372. enumerable: true,
  50373. configurable: true
  50374. });
  50375. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  50376. get: function () {
  50377. return this._textures.data[this._currentRenderTextureInd];
  50378. },
  50379. set: function (value) {
  50380. this._forcedOutputTexture = value;
  50381. },
  50382. enumerable: true,
  50383. configurable: true
  50384. });
  50385. PostProcess.prototype.getCamera = function () {
  50386. return this._camera;
  50387. };
  50388. Object.defineProperty(PostProcess.prototype, "texelSize", {
  50389. get: function () {
  50390. if (this._shareOutputWithPostProcess) {
  50391. return this._shareOutputWithPostProcess.texelSize;
  50392. }
  50393. if (this._forcedOutputTexture) {
  50394. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  50395. }
  50396. return this._texelSize;
  50397. },
  50398. enumerable: true,
  50399. configurable: true
  50400. });
  50401. PostProcess.prototype.getEngine = function () {
  50402. return this._engine;
  50403. };
  50404. PostProcess.prototype.getEffect = function () {
  50405. return this._effect;
  50406. };
  50407. PostProcess.prototype.shareOutputWith = function (postProcess) {
  50408. this._disposeTextures();
  50409. this._shareOutputWithPostProcess = postProcess;
  50410. return this;
  50411. };
  50412. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  50413. if (defines === void 0) { defines = null; }
  50414. if (uniforms === void 0) { uniforms = null; }
  50415. if (samplers === void 0) { samplers = null; }
  50416. 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);
  50417. };
  50418. PostProcess.prototype.isReusable = function () {
  50419. return this._reusable;
  50420. };
  50421. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  50422. PostProcess.prototype.markTextureDirty = function () {
  50423. this.width = -1;
  50424. };
  50425. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  50426. var _this = this;
  50427. if (sourceTexture === void 0) { sourceTexture = null; }
  50428. camera = camera || this._camera;
  50429. var scene = camera.getScene();
  50430. var engine = scene.getEngine();
  50431. var maxSize = engine.getCaps().maxTextureSize;
  50432. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  50433. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  50434. var desiredWidth = (this._options.width || requiredWidth);
  50435. var desiredHeight = this._options.height || requiredHeight;
  50436. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  50437. if (this.adaptScaleToCurrentViewport) {
  50438. var currentViewport = engine.currentViewport;
  50439. if (currentViewport) {
  50440. desiredWidth *= currentViewport.width;
  50441. desiredHeight *= currentViewport.height;
  50442. }
  50443. }
  50444. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  50445. if (!this._options.width) {
  50446. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  50447. }
  50448. if (!this._options.height) {
  50449. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  50450. }
  50451. }
  50452. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  50453. if (this._textures.length > 0) {
  50454. for (var i = 0; i < this._textures.length; i++) {
  50455. this._engine._releaseTexture(this._textures.data[i]);
  50456. }
  50457. this._textures.reset();
  50458. }
  50459. this.width = desiredWidth;
  50460. this.height = desiredHeight;
  50461. var textureSize = { width: this.width, height: this.height };
  50462. var textureOptions = {
  50463. generateMipMaps: false,
  50464. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  50465. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  50466. samplingMode: this.renderTargetSamplingMode,
  50467. type: this._textureType
  50468. };
  50469. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50470. if (this._reusable) {
  50471. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50472. }
  50473. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  50474. this.onSizeChangedObservable.notifyObservers(this);
  50475. }
  50476. this._textures.forEach(function (texture) {
  50477. if (texture.samples !== _this.samples) {
  50478. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  50479. }
  50480. });
  50481. }
  50482. var target;
  50483. if (this._shareOutputWithPostProcess) {
  50484. target = this._shareOutputWithPostProcess.outputTexture;
  50485. }
  50486. else if (this._forcedOutputTexture) {
  50487. target = this._forcedOutputTexture;
  50488. this.width = this._forcedOutputTexture.width;
  50489. this.height = this._forcedOutputTexture.height;
  50490. }
  50491. else {
  50492. target = this.outputTexture;
  50493. }
  50494. if (this.enablePixelPerfectMode) {
  50495. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  50496. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  50497. }
  50498. else {
  50499. this._scaleRatio.copyFromFloats(1, 1);
  50500. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  50501. }
  50502. this.onActivateObservable.notifyObservers(camera);
  50503. // Clear
  50504. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  50505. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  50506. }
  50507. if (this._reusable) {
  50508. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  50509. }
  50510. };
  50511. Object.defineProperty(PostProcess.prototype, "isSupported", {
  50512. get: function () {
  50513. return this._effect.isSupported;
  50514. },
  50515. enumerable: true,
  50516. configurable: true
  50517. });
  50518. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  50519. get: function () {
  50520. if (this._shareOutputWithPostProcess) {
  50521. return this._shareOutputWithPostProcess.aspectRatio;
  50522. }
  50523. if (this._forcedOutputTexture) {
  50524. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  50525. }
  50526. return this.width / this.height;
  50527. },
  50528. enumerable: true,
  50529. configurable: true
  50530. });
  50531. PostProcess.prototype.apply = function () {
  50532. // Check
  50533. if (!this._effect || !this._effect.isReady())
  50534. return null;
  50535. // States
  50536. this._engine.enableEffect(this._effect);
  50537. this._engine.setState(false);
  50538. this._engine.setDepthBuffer(false);
  50539. this._engine.setDepthWrite(false);
  50540. // Alpha
  50541. this._engine.setAlphaMode(this.alphaMode);
  50542. if (this.alphaConstants) {
  50543. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  50544. }
  50545. // Texture
  50546. var source;
  50547. if (this._shareOutputWithPostProcess) {
  50548. source = this._shareOutputWithPostProcess.outputTexture;
  50549. }
  50550. else if (this._forcedOutputTexture) {
  50551. source = this._forcedOutputTexture;
  50552. }
  50553. else {
  50554. source = this.outputTexture;
  50555. }
  50556. this._effect._bindTexture("textureSampler", source);
  50557. // Parameters
  50558. this._effect.setVector2("scale", this._scaleRatio);
  50559. this.onApplyObservable.notifyObservers(this._effect);
  50560. return this._effect;
  50561. };
  50562. PostProcess.prototype._disposeTextures = function () {
  50563. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  50564. return;
  50565. }
  50566. if (this._textures.length > 0) {
  50567. for (var i = 0; i < this._textures.length; i++) {
  50568. this._engine._releaseTexture(this._textures.data[i]);
  50569. }
  50570. }
  50571. this._textures.dispose();
  50572. };
  50573. PostProcess.prototype.dispose = function (camera) {
  50574. camera = camera || this._camera;
  50575. this._disposeTextures();
  50576. if (this._scene) {
  50577. var index_1 = this._scene.postProcesses.indexOf(this);
  50578. if (index_1 !== -1) {
  50579. this._scene.postProcesses.splice(index_1, 1);
  50580. }
  50581. }
  50582. else {
  50583. var index_2 = this._engine.postProcesses.indexOf(this);
  50584. if (index_2 !== -1) {
  50585. this._engine.postProcesses.splice(index_2, 1);
  50586. }
  50587. }
  50588. if (!camera) {
  50589. return;
  50590. }
  50591. camera.detachPostProcess(this);
  50592. var index = camera._postProcesses.indexOf(this);
  50593. if (index === 0 && camera._postProcesses.length > 0) {
  50594. this._camera._postProcesses[0].markTextureDirty();
  50595. }
  50596. this.onActivateObservable.clear();
  50597. this.onAfterRenderObservable.clear();
  50598. this.onApplyObservable.clear();
  50599. this.onBeforeRenderObservable.clear();
  50600. this.onSizeChangedObservable.clear();
  50601. };
  50602. return PostProcess;
  50603. }());
  50604. BABYLON.PostProcess = PostProcess;
  50605. })(BABYLON || (BABYLON = {}));
  50606. //# sourceMappingURL=babylon.postProcess.js.map
  50607. var BABYLON;
  50608. (function (BABYLON) {
  50609. var PassPostProcess = /** @class */ (function (_super) {
  50610. __extends(PassPostProcess, _super);
  50611. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50612. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50613. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  50614. }
  50615. return PassPostProcess;
  50616. }(BABYLON.PostProcess));
  50617. BABYLON.PassPostProcess = PassPostProcess;
  50618. })(BABYLON || (BABYLON = {}));
  50619. //# sourceMappingURL=babylon.passPostProcess.js.map
  50620. var BABYLON;
  50621. (function (BABYLON) {
  50622. var ShadowGenerator = /** @class */ (function () {
  50623. /**
  50624. * Creates a ShadowGenerator object.
  50625. * A ShadowGenerator is the required tool to use the shadows.
  50626. * Each light casting shadows needs to use its own ShadowGenerator.
  50627. * Required parameters :
  50628. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  50629. * - `light`: the light object generating the shadows.
  50630. * - `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.
  50631. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  50632. */
  50633. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  50634. // Members
  50635. this._bias = 0.00005;
  50636. this._blurBoxOffset = 1;
  50637. this._blurScale = 2;
  50638. this._blurKernel = 1;
  50639. this._useKernelBlur = false;
  50640. this._filter = ShadowGenerator.FILTER_NONE;
  50641. this._darkness = 0;
  50642. this._transparencyShadow = false;
  50643. /**
  50644. * Controls the extent to which the shadows fade out at the edge of the frustum
  50645. * Used only by directionals and spots
  50646. */
  50647. this.frustumEdgeFalloff = 0;
  50648. this.forceBackFacesOnly = false;
  50649. this._lightDirection = BABYLON.Vector3.Zero();
  50650. this._viewMatrix = BABYLON.Matrix.Zero();
  50651. this._projectionMatrix = BABYLON.Matrix.Zero();
  50652. this._transformMatrix = BABYLON.Matrix.Zero();
  50653. this._currentFaceIndex = 0;
  50654. this._currentFaceIndexCache = 0;
  50655. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  50656. this._mapSize = mapSize;
  50657. this._light = light;
  50658. this._scene = light.getScene();
  50659. light._shadowGenerator = this;
  50660. // Texture type fallback from float to int if not supported.
  50661. var caps = this._scene.getEngine().getCaps();
  50662. if (!useFullFloatFirst) {
  50663. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50664. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50665. }
  50666. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50667. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50668. }
  50669. else {
  50670. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50671. }
  50672. }
  50673. else {
  50674. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50675. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50676. }
  50677. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50678. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50679. }
  50680. else {
  50681. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50682. }
  50683. }
  50684. this._initializeGenerator();
  50685. }
  50686. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  50687. // Static
  50688. get: function () {
  50689. return ShadowGenerator._FILTER_NONE;
  50690. },
  50691. enumerable: true,
  50692. configurable: true
  50693. });
  50694. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  50695. get: function () {
  50696. return ShadowGenerator._FILTER_POISSONSAMPLING;
  50697. },
  50698. enumerable: true,
  50699. configurable: true
  50700. });
  50701. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  50702. get: function () {
  50703. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  50704. },
  50705. enumerable: true,
  50706. configurable: true
  50707. });
  50708. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  50709. get: function () {
  50710. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  50711. },
  50712. enumerable: true,
  50713. configurable: true
  50714. });
  50715. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  50716. get: function () {
  50717. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50718. },
  50719. enumerable: true,
  50720. configurable: true
  50721. });
  50722. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  50723. get: function () {
  50724. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50725. },
  50726. enumerable: true,
  50727. configurable: true
  50728. });
  50729. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  50730. get: function () {
  50731. return this._bias;
  50732. },
  50733. set: function (bias) {
  50734. this._bias = bias;
  50735. },
  50736. enumerable: true,
  50737. configurable: true
  50738. });
  50739. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  50740. get: function () {
  50741. return this._blurBoxOffset;
  50742. },
  50743. set: function (value) {
  50744. if (this._blurBoxOffset === value) {
  50745. return;
  50746. }
  50747. this._blurBoxOffset = value;
  50748. this._disposeBlurPostProcesses();
  50749. },
  50750. enumerable: true,
  50751. configurable: true
  50752. });
  50753. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  50754. get: function () {
  50755. return this._blurScale;
  50756. },
  50757. set: function (value) {
  50758. if (this._blurScale === value) {
  50759. return;
  50760. }
  50761. this._blurScale = value;
  50762. this._disposeBlurPostProcesses();
  50763. },
  50764. enumerable: true,
  50765. configurable: true
  50766. });
  50767. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  50768. get: function () {
  50769. return this._blurKernel;
  50770. },
  50771. set: function (value) {
  50772. if (this._blurKernel === value) {
  50773. return;
  50774. }
  50775. this._blurKernel = value;
  50776. this._disposeBlurPostProcesses();
  50777. },
  50778. enumerable: true,
  50779. configurable: true
  50780. });
  50781. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  50782. get: function () {
  50783. return this._useKernelBlur;
  50784. },
  50785. set: function (value) {
  50786. if (this._useKernelBlur === value) {
  50787. return;
  50788. }
  50789. this._useKernelBlur = value;
  50790. this._disposeBlurPostProcesses();
  50791. },
  50792. enumerable: true,
  50793. configurable: true
  50794. });
  50795. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  50796. get: function () {
  50797. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  50798. },
  50799. set: function (value) {
  50800. this._depthScale = value;
  50801. },
  50802. enumerable: true,
  50803. configurable: true
  50804. });
  50805. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  50806. get: function () {
  50807. return this._filter;
  50808. },
  50809. set: function (value) {
  50810. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  50811. if (this._light.needCube()) {
  50812. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50813. this.useExponentialShadowMap = true;
  50814. return;
  50815. }
  50816. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50817. this.useCloseExponentialShadowMap = true;
  50818. return;
  50819. }
  50820. }
  50821. if (this._filter === value) {
  50822. return;
  50823. }
  50824. this._filter = value;
  50825. this._disposeBlurPostProcesses();
  50826. this._applyFilterValues();
  50827. this._light._markMeshesAsLightDirty();
  50828. },
  50829. enumerable: true,
  50830. configurable: true
  50831. });
  50832. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  50833. get: function () {
  50834. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  50835. },
  50836. set: function (value) {
  50837. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  50838. return;
  50839. }
  50840. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  50841. },
  50842. enumerable: true,
  50843. configurable: true
  50844. });
  50845. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  50846. get: function () {
  50847. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  50848. return this.useExponentialShadowMap;
  50849. },
  50850. set: function (value) {
  50851. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  50852. this.useExponentialShadowMap = value;
  50853. },
  50854. enumerable: true,
  50855. configurable: true
  50856. });
  50857. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  50858. get: function () {
  50859. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  50860. return this.useBlurExponentialShadowMap;
  50861. },
  50862. set: function (value) {
  50863. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  50864. this.useBlurExponentialShadowMap = value;
  50865. },
  50866. enumerable: true,
  50867. configurable: true
  50868. });
  50869. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  50870. get: function () {
  50871. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  50872. },
  50873. set: function (value) {
  50874. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  50875. return;
  50876. }
  50877. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50878. },
  50879. enumerable: true,
  50880. configurable: true
  50881. });
  50882. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  50883. get: function () {
  50884. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  50885. },
  50886. set: function (value) {
  50887. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50888. return;
  50889. }
  50890. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50891. },
  50892. enumerable: true,
  50893. configurable: true
  50894. });
  50895. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  50896. get: function () {
  50897. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50898. },
  50899. set: function (value) {
  50900. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  50901. return;
  50902. }
  50903. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50904. },
  50905. enumerable: true,
  50906. configurable: true
  50907. });
  50908. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  50909. get: function () {
  50910. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50911. },
  50912. set: function (value) {
  50913. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50914. return;
  50915. }
  50916. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50917. },
  50918. enumerable: true,
  50919. configurable: true
  50920. });
  50921. /**
  50922. * Returns the darkness value (float).
  50923. */
  50924. ShadowGenerator.prototype.getDarkness = function () {
  50925. return this._darkness;
  50926. };
  50927. /**
  50928. * Sets the ShadowGenerator darkness value (float <= 1.0).
  50929. * Returns the ShadowGenerator.
  50930. */
  50931. ShadowGenerator.prototype.setDarkness = function (darkness) {
  50932. if (darkness >= 1.0)
  50933. this._darkness = 1.0;
  50934. else if (darkness <= 0.0)
  50935. this._darkness = 0.0;
  50936. else
  50937. this._darkness = darkness;
  50938. return this;
  50939. };
  50940. /**
  50941. * Sets the ability to have transparent shadow (boolean).
  50942. * Returns the ShadowGenerator.
  50943. */
  50944. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  50945. this._transparencyShadow = hasShadow;
  50946. return this;
  50947. };
  50948. /**
  50949. * Returns a RenderTargetTexture object : the shadow map texture.
  50950. */
  50951. ShadowGenerator.prototype.getShadowMap = function () {
  50952. return this._shadowMap;
  50953. };
  50954. /**
  50955. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  50956. */
  50957. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  50958. if (this._shadowMap2) {
  50959. return this._shadowMap2;
  50960. }
  50961. return this._shadowMap;
  50962. };
  50963. /**
  50964. * Helper function to add a mesh and its descendants to the list of shadow casters
  50965. * @param mesh Mesh to add
  50966. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  50967. */
  50968. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  50969. if (includeDescendants === void 0) { includeDescendants = true; }
  50970. if (!this._shadowMap) {
  50971. return this;
  50972. }
  50973. if (!this._shadowMap.renderList) {
  50974. this._shadowMap.renderList = [];
  50975. }
  50976. this._shadowMap.renderList.push(mesh);
  50977. if (includeDescendants) {
  50978. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  50979. }
  50980. return this;
  50981. var _a;
  50982. };
  50983. /**
  50984. * Helper function to remove a mesh and its descendants from the list of shadow casters
  50985. * @param mesh Mesh to remove
  50986. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  50987. */
  50988. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  50989. if (includeDescendants === void 0) { includeDescendants = true; }
  50990. if (!this._shadowMap || !this._shadowMap.renderList) {
  50991. return this;
  50992. }
  50993. var index = this._shadowMap.renderList.indexOf(mesh);
  50994. if (index !== -1) {
  50995. this._shadowMap.renderList.splice(index, 1);
  50996. }
  50997. if (includeDescendants) {
  50998. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  50999. var child = _a[_i];
  51000. this.removeShadowCaster(child);
  51001. }
  51002. }
  51003. return this;
  51004. };
  51005. /**
  51006. * Returns the associated light object.
  51007. */
  51008. ShadowGenerator.prototype.getLight = function () {
  51009. return this._light;
  51010. };
  51011. ShadowGenerator.prototype._initializeGenerator = function () {
  51012. this._light._markMeshesAsLightDirty();
  51013. this._initializeShadowMap();
  51014. };
  51015. ShadowGenerator.prototype._initializeShadowMap = function () {
  51016. var _this = this;
  51017. // Render target
  51018. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51019. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51020. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51021. this._shadowMap.anisotropicFilteringLevel = 1;
  51022. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51023. this._shadowMap.renderParticles = false;
  51024. this._shadowMap.ignoreCameraViewport = true;
  51025. // Record Face Index before render.
  51026. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51027. _this._currentFaceIndex = faceIndex;
  51028. });
  51029. // Custom render function.
  51030. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51031. // Blur if required afer render.
  51032. this._shadowMap.onAfterUnbindObservable.add(function () {
  51033. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51034. return;
  51035. }
  51036. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51037. _this._initializeBlurRTTAndPostProcesses();
  51038. }
  51039. var shadowMap = _this.getShadowMapForRendering();
  51040. if (shadowMap) {
  51041. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51042. }
  51043. });
  51044. // Clear according to the chosen filter.
  51045. this._shadowMap.onClearObservable.add(function (engine) {
  51046. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51047. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51048. }
  51049. else {
  51050. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51051. }
  51052. });
  51053. };
  51054. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51055. var _this = this;
  51056. var engine = this._scene.getEngine();
  51057. var targetSize = this._mapSize / this.blurScale;
  51058. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51059. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51060. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51061. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51062. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51063. }
  51064. if (this.useKernelBlur) {
  51065. 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);
  51066. this._kernelBlurXPostprocess.width = targetSize;
  51067. this._kernelBlurXPostprocess.height = targetSize;
  51068. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51069. effect.setTexture("textureSampler", _this._shadowMap);
  51070. });
  51071. 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);
  51072. this._kernelBlurXPostprocess.autoClear = false;
  51073. this._kernelBlurYPostprocess.autoClear = false;
  51074. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51075. this._kernelBlurXPostprocess.packedFloat = true;
  51076. this._kernelBlurYPostprocess.packedFloat = true;
  51077. }
  51078. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51079. }
  51080. else {
  51081. 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);
  51082. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51083. effect.setFloat2("screenSize", targetSize, targetSize);
  51084. effect.setTexture("textureSampler", _this._shadowMap);
  51085. });
  51086. this._boxBlurPostprocess.autoClear = false;
  51087. this._blurPostProcesses = [this._boxBlurPostprocess];
  51088. }
  51089. };
  51090. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  51091. var index;
  51092. var engine = this._scene.getEngine();
  51093. if (depthOnlySubMeshes.length) {
  51094. engine.setColorWrite(false);
  51095. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  51096. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  51097. }
  51098. engine.setColorWrite(true);
  51099. }
  51100. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51101. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  51102. }
  51103. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51104. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  51105. }
  51106. if (this._transparencyShadow) {
  51107. for (index = 0; index < transparentSubMeshes.length; index++) {
  51108. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  51109. }
  51110. }
  51111. };
  51112. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  51113. var _this = this;
  51114. var mesh = subMesh.getRenderingMesh();
  51115. var scene = this._scene;
  51116. var engine = scene.getEngine();
  51117. var material = subMesh.getMaterial();
  51118. if (!material) {
  51119. return;
  51120. }
  51121. // Culling
  51122. engine.setState(material.backFaceCulling);
  51123. // Managing instances
  51124. var batch = mesh._getInstancesRenderList(subMesh._id);
  51125. if (batch.mustReturn) {
  51126. return;
  51127. }
  51128. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  51129. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  51130. engine.enableEffect(this._effect);
  51131. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  51132. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  51133. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  51134. this._effect.setVector3("lightPosition", this.getLight().position);
  51135. if (scene.activeCamera) {
  51136. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  51137. }
  51138. // Alpha test
  51139. if (material && material.needAlphaTesting()) {
  51140. var alphaTexture = material.getAlphaTestTexture();
  51141. if (alphaTexture) {
  51142. this._effect.setTexture("diffuseSampler", alphaTexture);
  51143. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  51144. }
  51145. }
  51146. // Bones
  51147. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51148. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  51149. }
  51150. if (this.forceBackFacesOnly) {
  51151. engine.setState(true, 0, false, true);
  51152. }
  51153. // Draw
  51154. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51155. if (this.forceBackFacesOnly) {
  51156. engine.setState(true, 0, false, false);
  51157. }
  51158. }
  51159. else {
  51160. // Need to reset refresh rate of the shadowMap
  51161. if (this._shadowMap) {
  51162. this._shadowMap.resetRefreshCounter();
  51163. }
  51164. }
  51165. };
  51166. ShadowGenerator.prototype._applyFilterValues = function () {
  51167. if (!this._shadowMap) {
  51168. return;
  51169. }
  51170. if (this.filter === ShadowGenerator.FILTER_NONE) {
  51171. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  51172. }
  51173. else {
  51174. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51175. }
  51176. };
  51177. /**
  51178. * Force shader compilation including textures ready check
  51179. */
  51180. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  51181. var _this = this;
  51182. var shadowMap = this.getShadowMap();
  51183. if (!shadowMap) {
  51184. return;
  51185. }
  51186. var subMeshes = new Array();
  51187. var currentIndex = 0;
  51188. var renderList = shadowMap.renderList;
  51189. if (!renderList) {
  51190. return;
  51191. }
  51192. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  51193. var mesh = renderList_1[_i];
  51194. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  51195. }
  51196. var checkReady = function () {
  51197. if (!_this._scene || !_this._scene.getEngine()) {
  51198. return;
  51199. }
  51200. var subMesh = subMeshes[currentIndex];
  51201. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  51202. currentIndex++;
  51203. if (currentIndex >= subMeshes.length) {
  51204. if (onCompiled) {
  51205. onCompiled(_this);
  51206. }
  51207. return;
  51208. }
  51209. }
  51210. setTimeout(checkReady, 16);
  51211. };
  51212. if (subMeshes.length > 0) {
  51213. checkReady();
  51214. }
  51215. };
  51216. /**
  51217. * Boolean : true when the ShadowGenerator is finally computed.
  51218. */
  51219. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  51220. var defines = [];
  51221. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51222. defines.push("#define FLOAT");
  51223. }
  51224. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51225. defines.push("#define ESM");
  51226. }
  51227. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51228. var mesh = subMesh.getMesh();
  51229. var material = subMesh.getMaterial();
  51230. // Alpha test
  51231. if (material && material.needAlphaTesting()) {
  51232. var alphaTexture = material.getAlphaTestTexture();
  51233. if (alphaTexture) {
  51234. defines.push("#define ALPHATEST");
  51235. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51236. attribs.push(BABYLON.VertexBuffer.UVKind);
  51237. defines.push("#define UV1");
  51238. }
  51239. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51240. if (alphaTexture.coordinatesIndex === 1) {
  51241. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51242. defines.push("#define UV2");
  51243. }
  51244. }
  51245. }
  51246. }
  51247. // Bones
  51248. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51249. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51250. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51251. if (mesh.numBoneInfluencers > 4) {
  51252. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51253. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51254. }
  51255. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51256. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51257. }
  51258. else {
  51259. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51260. }
  51261. // Instances
  51262. if (useInstances) {
  51263. defines.push("#define INSTANCES");
  51264. attribs.push("world0");
  51265. attribs.push("world1");
  51266. attribs.push("world2");
  51267. attribs.push("world3");
  51268. }
  51269. // Get correct effect
  51270. var join = defines.join("\n");
  51271. if (this._cachedDefines !== join) {
  51272. this._cachedDefines = join;
  51273. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  51274. }
  51275. return this._effect.isReady();
  51276. };
  51277. /**
  51278. * This creates the defines related to the standard BJS materials.
  51279. */
  51280. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  51281. var scene = this._scene;
  51282. var light = this._light;
  51283. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51284. return;
  51285. }
  51286. defines["SHADOW" + lightIndex] = true;
  51287. if (this.usePoissonSampling) {
  51288. defines["SHADOWPCF" + lightIndex] = true;
  51289. }
  51290. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51291. defines["SHADOWESM" + lightIndex] = true;
  51292. }
  51293. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  51294. defines["SHADOWCLOSEESM" + lightIndex] = true;
  51295. }
  51296. if (light.needCube()) {
  51297. defines["SHADOWCUBE" + lightIndex] = true;
  51298. }
  51299. };
  51300. /**
  51301. * This binds shadow lights related to the standard BJS materials.
  51302. * It implies the unifroms available on the materials are the standard BJS ones.
  51303. */
  51304. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  51305. var light = this._light;
  51306. var scene = this._scene;
  51307. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51308. return;
  51309. }
  51310. var camera = scene.activeCamera;
  51311. if (!camera) {
  51312. return;
  51313. }
  51314. var shadowMap = this.getShadowMap();
  51315. if (!shadowMap) {
  51316. return;
  51317. }
  51318. if (!light.needCube()) {
  51319. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  51320. }
  51321. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  51322. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  51323. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  51324. };
  51325. // Methods
  51326. /**
  51327. * Returns a Matrix object : the updated transformation matrix.
  51328. */
  51329. ShadowGenerator.prototype.getTransformMatrix = function () {
  51330. var scene = this._scene;
  51331. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  51332. return this._transformMatrix;
  51333. }
  51334. this._currentRenderID = scene.getRenderId();
  51335. this._currentFaceIndexCache = this._currentFaceIndex;
  51336. var lightPosition = this._light.position;
  51337. if (this._light.computeTransformedInformation()) {
  51338. lightPosition = this._light.transformedPosition;
  51339. }
  51340. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  51341. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  51342. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  51343. }
  51344. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  51345. this._cachedPosition = lightPosition.clone();
  51346. this._cachedDirection = this._lightDirection.clone();
  51347. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  51348. var shadowMap = this.getShadowMap();
  51349. if (shadowMap) {
  51350. var renderList = shadowMap.renderList;
  51351. if (renderList) {
  51352. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  51353. }
  51354. }
  51355. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  51356. }
  51357. return this._transformMatrix;
  51358. };
  51359. ShadowGenerator.prototype.recreateShadowMap = function () {
  51360. var shadowMap = this._shadowMap;
  51361. if (!shadowMap) {
  51362. return;
  51363. }
  51364. // Track render list.
  51365. var renderList = shadowMap.renderList;
  51366. // Clean up existing data.
  51367. this._disposeRTTandPostProcesses();
  51368. // Reinitializes.
  51369. this._initializeGenerator();
  51370. // Reaffect the filter to ensure a correct fallback if necessary.
  51371. this.filter = this.filter;
  51372. // Reaffect the filter.
  51373. this._applyFilterValues();
  51374. // Reaffect Render List.
  51375. shadowMap.renderList = renderList;
  51376. };
  51377. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  51378. if (this._shadowMap2) {
  51379. this._shadowMap2.dispose();
  51380. this._shadowMap2 = null;
  51381. }
  51382. if (this._downSamplePostprocess) {
  51383. this._downSamplePostprocess.dispose();
  51384. this._downSamplePostprocess = null;
  51385. }
  51386. if (this._boxBlurPostprocess) {
  51387. this._boxBlurPostprocess.dispose();
  51388. this._boxBlurPostprocess = null;
  51389. }
  51390. if (this._kernelBlurXPostprocess) {
  51391. this._kernelBlurXPostprocess.dispose();
  51392. this._kernelBlurXPostprocess = null;
  51393. }
  51394. if (this._kernelBlurYPostprocess) {
  51395. this._kernelBlurYPostprocess.dispose();
  51396. this._kernelBlurYPostprocess = null;
  51397. }
  51398. this._blurPostProcesses = [];
  51399. };
  51400. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  51401. if (this._shadowMap) {
  51402. this._shadowMap.dispose();
  51403. this._shadowMap = null;
  51404. }
  51405. this._disposeBlurPostProcesses();
  51406. };
  51407. /**
  51408. * Disposes the ShadowGenerator.
  51409. * Returns nothing.
  51410. */
  51411. ShadowGenerator.prototype.dispose = function () {
  51412. this._disposeRTTandPostProcesses();
  51413. if (this._light) {
  51414. this._light._shadowGenerator = null;
  51415. this._light._markMeshesAsLightDirty();
  51416. }
  51417. };
  51418. /**
  51419. * Serializes the ShadowGenerator and returns a serializationObject.
  51420. */
  51421. ShadowGenerator.prototype.serialize = function () {
  51422. var serializationObject = {};
  51423. var shadowMap = this.getShadowMap();
  51424. if (!shadowMap) {
  51425. return serializationObject;
  51426. }
  51427. serializationObject.lightId = this._light.id;
  51428. serializationObject.mapSize = shadowMap.getRenderSize();
  51429. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  51430. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  51431. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51432. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51433. serializationObject.usePoissonSampling = this.usePoissonSampling;
  51434. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  51435. serializationObject.depthScale = this.depthScale;
  51436. serializationObject.darkness = this.getDarkness();
  51437. serializationObject.blurBoxOffset = this.blurBoxOffset;
  51438. serializationObject.blurKernel = this.blurKernel;
  51439. serializationObject.blurScale = this.blurScale;
  51440. serializationObject.useKernelBlur = this.useKernelBlur;
  51441. serializationObject.transparencyShadow = this._transparencyShadow;
  51442. serializationObject.renderList = [];
  51443. if (shadowMap.renderList) {
  51444. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  51445. var mesh = shadowMap.renderList[meshIndex];
  51446. serializationObject.renderList.push(mesh.id);
  51447. }
  51448. }
  51449. return serializationObject;
  51450. };
  51451. /**
  51452. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  51453. */
  51454. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  51455. //casting to point light, as light is missing the position attr and typescript complains.
  51456. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  51457. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  51458. var shadowMap = shadowGenerator.getShadowMap();
  51459. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  51460. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  51461. meshes.forEach(function (mesh) {
  51462. if (!shadowMap) {
  51463. return;
  51464. }
  51465. if (!shadowMap.renderList) {
  51466. shadowMap.renderList = [];
  51467. }
  51468. shadowMap.renderList.push(mesh);
  51469. });
  51470. }
  51471. if (parsedShadowGenerator.usePoissonSampling) {
  51472. shadowGenerator.usePoissonSampling = true;
  51473. }
  51474. else if (parsedShadowGenerator.useExponentialShadowMap) {
  51475. shadowGenerator.useExponentialShadowMap = true;
  51476. }
  51477. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  51478. shadowGenerator.useBlurExponentialShadowMap = true;
  51479. }
  51480. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  51481. shadowGenerator.useCloseExponentialShadowMap = true;
  51482. }
  51483. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  51484. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  51485. }
  51486. else if (parsedShadowGenerator.useVarianceShadowMap) {
  51487. shadowGenerator.useExponentialShadowMap = true;
  51488. }
  51489. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  51490. shadowGenerator.useBlurExponentialShadowMap = true;
  51491. }
  51492. if (parsedShadowGenerator.depthScale) {
  51493. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  51494. }
  51495. if (parsedShadowGenerator.blurScale) {
  51496. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  51497. }
  51498. if (parsedShadowGenerator.blurBoxOffset) {
  51499. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  51500. }
  51501. if (parsedShadowGenerator.useKernelBlur) {
  51502. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  51503. }
  51504. if (parsedShadowGenerator.blurKernel) {
  51505. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  51506. }
  51507. if (parsedShadowGenerator.bias !== undefined) {
  51508. shadowGenerator.bias = parsedShadowGenerator.bias;
  51509. }
  51510. if (parsedShadowGenerator.darkness) {
  51511. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  51512. }
  51513. if (parsedShadowGenerator.transparencyShadow) {
  51514. shadowGenerator.setTransparencyShadow(true);
  51515. }
  51516. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  51517. return shadowGenerator;
  51518. };
  51519. ShadowGenerator._FILTER_NONE = 0;
  51520. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  51521. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  51522. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  51523. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  51524. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  51525. return ShadowGenerator;
  51526. }());
  51527. BABYLON.ShadowGenerator = ShadowGenerator;
  51528. })(BABYLON || (BABYLON = {}));
  51529. //# sourceMappingURL=babylon.shadowGenerator.js.map
  51530. var BABYLON;
  51531. (function (BABYLON) {
  51532. var DefaultLoadingScreen = /** @class */ (function () {
  51533. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  51534. if (_loadingText === void 0) { _loadingText = ""; }
  51535. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  51536. var _this = this;
  51537. this._renderingCanvas = _renderingCanvas;
  51538. this._loadingText = _loadingText;
  51539. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  51540. // Resize
  51541. this._resizeLoadingUI = function () {
  51542. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  51543. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  51544. if (!_this._loadingDiv) {
  51545. return;
  51546. }
  51547. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  51548. _this._loadingDiv.style.left = canvasRect.left + "px";
  51549. _this._loadingDiv.style.top = canvasRect.top + "px";
  51550. _this._loadingDiv.style.width = canvasRect.width + "px";
  51551. _this._loadingDiv.style.height = canvasRect.height + "px";
  51552. };
  51553. }
  51554. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  51555. if (this._loadingDiv) {
  51556. // Do not add a loading screen if there is already one
  51557. return;
  51558. }
  51559. this._loadingDiv = document.createElement("div");
  51560. this._loadingDiv.id = "babylonjsLoadingDiv";
  51561. this._loadingDiv.style.opacity = "0";
  51562. this._loadingDiv.style.transition = "opacity 1.5s ease";
  51563. this._loadingDiv.style.pointerEvents = "none";
  51564. // Loading text
  51565. this._loadingTextDiv = document.createElement("div");
  51566. this._loadingTextDiv.style.position = "absolute";
  51567. this._loadingTextDiv.style.left = "0";
  51568. this._loadingTextDiv.style.top = "50%";
  51569. this._loadingTextDiv.style.marginTop = "80px";
  51570. this._loadingTextDiv.style.width = "100%";
  51571. this._loadingTextDiv.style.height = "20px";
  51572. this._loadingTextDiv.style.fontFamily = "Arial";
  51573. this._loadingTextDiv.style.fontSize = "14px";
  51574. this._loadingTextDiv.style.color = "white";
  51575. this._loadingTextDiv.style.textAlign = "center";
  51576. this._loadingTextDiv.innerHTML = "Loading";
  51577. this._loadingDiv.appendChild(this._loadingTextDiv);
  51578. //set the predefined text
  51579. this._loadingTextDiv.innerHTML = this._loadingText;
  51580. // Generating keyframes
  51581. var style = document.createElement('style');
  51582. style.type = 'text/css';
  51583. 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 }";
  51584. style.innerHTML = keyFrames;
  51585. document.getElementsByTagName('head')[0].appendChild(style);
  51586. // Loading img
  51587. var imgBack = new Image();
  51588. 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";
  51589. imgBack.style.position = "absolute";
  51590. imgBack.style.left = "50%";
  51591. imgBack.style.top = "50%";
  51592. imgBack.style.marginLeft = "-60px";
  51593. imgBack.style.marginTop = "-60px";
  51594. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  51595. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  51596. imgBack.style.transformOrigin = "50% 50%";
  51597. imgBack.style.webkitTransformOrigin = "50% 50%";
  51598. this._loadingDiv.appendChild(imgBack);
  51599. this._resizeLoadingUI();
  51600. window.addEventListener("resize", this._resizeLoadingUI);
  51601. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51602. document.body.appendChild(this._loadingDiv);
  51603. this._loadingDiv.style.opacity = "1";
  51604. };
  51605. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  51606. var _this = this;
  51607. if (!this._loadingDiv) {
  51608. return;
  51609. }
  51610. var onTransitionEnd = function () {
  51611. if (!_this._loadingDiv) {
  51612. return;
  51613. }
  51614. document.body.removeChild(_this._loadingDiv);
  51615. window.removeEventListener("resize", _this._resizeLoadingUI);
  51616. _this._loadingDiv = null;
  51617. };
  51618. this._loadingDiv.style.opacity = "0";
  51619. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  51620. };
  51621. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  51622. set: function (text) {
  51623. this._loadingText = text;
  51624. if (this._loadingTextDiv) {
  51625. this._loadingTextDiv.innerHTML = this._loadingText;
  51626. }
  51627. },
  51628. enumerable: true,
  51629. configurable: true
  51630. });
  51631. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  51632. get: function () {
  51633. return this._loadingDivBackgroundColor;
  51634. },
  51635. set: function (color) {
  51636. this._loadingDivBackgroundColor = color;
  51637. if (!this._loadingDiv) {
  51638. return;
  51639. }
  51640. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51641. },
  51642. enumerable: true,
  51643. configurable: true
  51644. });
  51645. return DefaultLoadingScreen;
  51646. }());
  51647. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  51648. })(BABYLON || (BABYLON = {}));
  51649. //# sourceMappingURL=babylon.loadingScreen.js.map
  51650. var BABYLON;
  51651. (function (BABYLON) {
  51652. var SceneLoader = /** @class */ (function () {
  51653. function SceneLoader() {
  51654. }
  51655. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  51656. get: function () {
  51657. return 0;
  51658. },
  51659. enumerable: true,
  51660. configurable: true
  51661. });
  51662. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  51663. get: function () {
  51664. return 1;
  51665. },
  51666. enumerable: true,
  51667. configurable: true
  51668. });
  51669. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  51670. get: function () {
  51671. return 2;
  51672. },
  51673. enumerable: true,
  51674. configurable: true
  51675. });
  51676. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  51677. get: function () {
  51678. return 3;
  51679. },
  51680. enumerable: true,
  51681. configurable: true
  51682. });
  51683. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  51684. get: function () {
  51685. return SceneLoader._ForceFullSceneLoadingForIncremental;
  51686. },
  51687. set: function (value) {
  51688. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  51689. },
  51690. enumerable: true,
  51691. configurable: true
  51692. });
  51693. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  51694. get: function () {
  51695. return SceneLoader._ShowLoadingScreen;
  51696. },
  51697. set: function (value) {
  51698. SceneLoader._ShowLoadingScreen = value;
  51699. },
  51700. enumerable: true,
  51701. configurable: true
  51702. });
  51703. Object.defineProperty(SceneLoader, "loggingLevel", {
  51704. get: function () {
  51705. return SceneLoader._loggingLevel;
  51706. },
  51707. set: function (value) {
  51708. SceneLoader._loggingLevel = value;
  51709. },
  51710. enumerable: true,
  51711. configurable: true
  51712. });
  51713. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  51714. get: function () {
  51715. return SceneLoader._CleanBoneMatrixWeights;
  51716. },
  51717. set: function (value) {
  51718. SceneLoader._CleanBoneMatrixWeights = value;
  51719. },
  51720. enumerable: true,
  51721. configurable: true
  51722. });
  51723. SceneLoader._getDefaultPlugin = function () {
  51724. return SceneLoader._registeredPlugins[".babylon"];
  51725. };
  51726. SceneLoader._getPluginForExtension = function (extension) {
  51727. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  51728. if (registeredPlugin) {
  51729. return registeredPlugin;
  51730. }
  51731. return SceneLoader._getDefaultPlugin();
  51732. };
  51733. SceneLoader._getPluginForDirectLoad = function (data) {
  51734. for (var extension in SceneLoader._registeredPlugins) {
  51735. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  51736. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  51737. return SceneLoader._registeredPlugins[extension];
  51738. }
  51739. }
  51740. return SceneLoader._getDefaultPlugin();
  51741. };
  51742. SceneLoader._getPluginForFilename = function (sceneFilename) {
  51743. if (sceneFilename.name) {
  51744. sceneFilename = sceneFilename.name;
  51745. }
  51746. var dotPosition = sceneFilename.lastIndexOf(".");
  51747. var queryStringPosition = sceneFilename.indexOf("?");
  51748. if (queryStringPosition === -1) {
  51749. queryStringPosition = sceneFilename.length;
  51750. }
  51751. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  51752. return SceneLoader._getPluginForExtension(extension);
  51753. };
  51754. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  51755. SceneLoader._getDirectLoad = function (sceneFilename) {
  51756. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  51757. return sceneFilename.substr(5);
  51758. }
  51759. return null;
  51760. };
  51761. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51762. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  51763. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  51764. var plugin = registeredPlugin.plugin;
  51765. var useArrayBuffer = registeredPlugin.isBinary;
  51766. var database;
  51767. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  51768. var dataCallback = function (data) {
  51769. if (scene.isDisposed) {
  51770. onError("Scene has been disposed");
  51771. return;
  51772. }
  51773. scene.database = database;
  51774. try {
  51775. onSuccess(plugin, data);
  51776. }
  51777. catch (e) {
  51778. onError(null, e);
  51779. }
  51780. };
  51781. var manifestChecked = function (success) {
  51782. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  51783. if (request) {
  51784. onError(request.status + " " + request.statusText);
  51785. }
  51786. });
  51787. };
  51788. if (directLoad) {
  51789. dataCallback(directLoad);
  51790. return;
  51791. }
  51792. if (rootUrl.indexOf("file:") === -1) {
  51793. if (scene.getEngine().enableOfflineSupport) {
  51794. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  51795. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  51796. }
  51797. else {
  51798. manifestChecked(true);
  51799. }
  51800. }
  51801. else {
  51802. var fileOrString = sceneFilename;
  51803. if (fileOrString.name) {
  51804. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  51805. }
  51806. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  51807. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  51808. }
  51809. else {
  51810. onError("Unable to find file named " + sceneFilename);
  51811. return;
  51812. }
  51813. }
  51814. };
  51815. // Public functions
  51816. SceneLoader.GetPluginForExtension = function (extension) {
  51817. return SceneLoader._getPluginForExtension(extension).plugin;
  51818. };
  51819. SceneLoader.RegisterPlugin = function (plugin) {
  51820. if (typeof plugin.extensions === "string") {
  51821. var extension = plugin.extensions;
  51822. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51823. plugin: plugin,
  51824. isBinary: false
  51825. };
  51826. }
  51827. else {
  51828. var extensions = plugin.extensions;
  51829. Object.keys(extensions).forEach(function (extension) {
  51830. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51831. plugin: plugin,
  51832. isBinary: extensions[extension].isBinary
  51833. };
  51834. });
  51835. }
  51836. };
  51837. /**
  51838. * Import meshes into a scene
  51839. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  51840. * @param rootUrl a string that defines the root url for scene and resources
  51841. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51842. * @param scene the instance of BABYLON.Scene to append to
  51843. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  51844. * @param onProgress a callback with a progress event for each file being loaded
  51845. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51846. */
  51847. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51848. if (onSuccess === void 0) { onSuccess = null; }
  51849. if (onProgress === void 0) { onProgress = null; }
  51850. if (onError === void 0) { onError = null; }
  51851. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  51852. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  51853. return;
  51854. }
  51855. var loadingToken = {};
  51856. scene._addPendingData(loadingToken);
  51857. var errorHandler = function (message, exception) {
  51858. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  51859. if (onError) {
  51860. onError(scene, errorMessage, exception);
  51861. }
  51862. else {
  51863. BABYLON.Tools.Error(errorMessage);
  51864. // should the exception be thrown?
  51865. }
  51866. scene._removePendingData(loadingToken);
  51867. };
  51868. var progressHandler = function (event) {
  51869. if (onProgress) {
  51870. onProgress(event);
  51871. }
  51872. };
  51873. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  51874. if (plugin.importMesh) {
  51875. var syncedPlugin = plugin;
  51876. var meshes = new Array();
  51877. var particleSystems = new Array();
  51878. var skeletons = new Array();
  51879. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  51880. return;
  51881. }
  51882. if (onSuccess) {
  51883. // wrap onSuccess with try-catch to know if something went wrong.
  51884. try {
  51885. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  51886. onSuccess(meshes, particleSystems, skeletons);
  51887. scene._removePendingData(loadingToken);
  51888. }
  51889. catch (e) {
  51890. var message = 'Error in onSuccess callback.';
  51891. errorHandler(message, e);
  51892. }
  51893. }
  51894. }
  51895. else {
  51896. var asyncedPlugin = plugin;
  51897. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  51898. if (onSuccess) {
  51899. try {
  51900. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  51901. onSuccess(meshes, particleSystems, skeletons);
  51902. scene._removePendingData(loadingToken);
  51903. }
  51904. catch (e) {
  51905. var message = 'Error in onSuccess callback.';
  51906. errorHandler(message, e);
  51907. }
  51908. }
  51909. }, progressHandler, errorHandler);
  51910. }
  51911. }, progressHandler, errorHandler);
  51912. };
  51913. /**
  51914. * Load a scene
  51915. * @param rootUrl a string that defines the root url for scene and resources
  51916. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51917. * @param engine is the instance of BABYLON.Engine to use to create the scene
  51918. * @param onSuccess a callback with the scene when import succeeds
  51919. * @param onProgress a callback with a progress event for each file being loaded
  51920. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51921. */
  51922. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  51923. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  51924. };
  51925. /**
  51926. * Append a scene
  51927. * @param rootUrl a string that defines the root url for scene and resources
  51928. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51929. * @param scene is the instance of BABYLON.Scene to append to
  51930. * @param onSuccess a callback with the scene when import succeeds
  51931. * @param onProgress a callback with a progress event for each file being loaded
  51932. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51933. */
  51934. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51935. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  51936. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  51937. return;
  51938. }
  51939. if (SceneLoader.ShowLoadingScreen) {
  51940. scene.getEngine().displayLoadingUI();
  51941. }
  51942. var loadingToken = {};
  51943. scene._addPendingData(loadingToken);
  51944. var errorHandler = function (message, exception) {
  51945. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  51946. if (onError) {
  51947. onError(scene, errorMessage, exception);
  51948. }
  51949. else {
  51950. BABYLON.Tools.Error(errorMessage);
  51951. // should the exception be thrown?
  51952. }
  51953. scene._removePendingData(loadingToken);
  51954. scene.getEngine().hideLoadingUI();
  51955. };
  51956. var progressHandler = function (event) {
  51957. if (onProgress) {
  51958. onProgress(event);
  51959. }
  51960. };
  51961. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  51962. if (plugin.load) {
  51963. var syncedPlugin = plugin;
  51964. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  51965. return;
  51966. }
  51967. if (onSuccess) {
  51968. try {
  51969. onSuccess(scene);
  51970. }
  51971. catch (e) {
  51972. errorHandler("Error in onSuccess callback", e);
  51973. }
  51974. }
  51975. scene.loadingPluginName = plugin.name;
  51976. scene._removePendingData(loadingToken);
  51977. }
  51978. else {
  51979. var asyncedPlugin = plugin;
  51980. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  51981. if (onSuccess) {
  51982. onSuccess(scene);
  51983. }
  51984. scene.loadingPluginName = plugin.name;
  51985. scene._removePendingData(loadingToken);
  51986. }, progressHandler, errorHandler);
  51987. }
  51988. if (SceneLoader.ShowLoadingScreen) {
  51989. scene.executeWhenReady(function () {
  51990. scene.getEngine().hideLoadingUI();
  51991. });
  51992. }
  51993. }, progressHandler, errorHandler);
  51994. };
  51995. // Flags
  51996. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  51997. SceneLoader._ShowLoadingScreen = true;
  51998. SceneLoader._CleanBoneMatrixWeights = false;
  51999. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  52000. // Members
  52001. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  52002. SceneLoader._registeredPlugins = {};
  52003. return SceneLoader;
  52004. }());
  52005. BABYLON.SceneLoader = SceneLoader;
  52006. ;
  52007. })(BABYLON || (BABYLON = {}));
  52008. //# sourceMappingURL=babylon.sceneLoader.js.map
  52009. var BABYLON;
  52010. (function (BABYLON) {
  52011. var Internals;
  52012. (function (Internals) {
  52013. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52014. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52015. var parsedMaterial = parsedData.materials[index];
  52016. if (parsedMaterial.id === id) {
  52017. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52018. }
  52019. }
  52020. return null;
  52021. };
  52022. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52023. for (var i in names) {
  52024. if (mesh.name === names[i]) {
  52025. hierarchyIds.push(mesh.id);
  52026. return true;
  52027. }
  52028. }
  52029. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52030. hierarchyIds.push(mesh.id);
  52031. return true;
  52032. }
  52033. return false;
  52034. };
  52035. var logOperation = function (operation, producer) {
  52036. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52037. };
  52038. BABYLON.SceneLoader.RegisterPlugin({
  52039. name: "babylon.js",
  52040. extensions: ".babylon",
  52041. canDirectLoad: function (data) {
  52042. if (data.indexOf("babylon") !== -1) {
  52043. return true;
  52044. }
  52045. return false;
  52046. },
  52047. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52048. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52049. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52050. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52051. // and avoid problems with multiple concurrent .babylon loads.
  52052. var log = "importMesh has failed JSON parse";
  52053. try {
  52054. var parsedData = JSON.parse(data);
  52055. log = "";
  52056. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52057. if (!meshesNames) {
  52058. meshesNames = null;
  52059. }
  52060. else if (!Array.isArray(meshesNames)) {
  52061. meshesNames = [meshesNames];
  52062. }
  52063. var hierarchyIds = new Array();
  52064. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52065. var loadedSkeletonsIds = [];
  52066. var loadedMaterialsIds = [];
  52067. var index;
  52068. var cache;
  52069. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52070. var parsedMesh = parsedData.meshes[index];
  52071. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52072. if (meshesNames !== null) {
  52073. // Remove found mesh name from list.
  52074. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52075. }
  52076. //Geometry?
  52077. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  52078. //does the file contain geometries?
  52079. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  52080. //find the correct geometry and add it to the scene
  52081. var found = false;
  52082. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  52083. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  52084. return;
  52085. }
  52086. else {
  52087. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  52088. if (parsedGeometryData.id === parsedMesh.geometryId) {
  52089. switch (geometryType) {
  52090. case "boxes":
  52091. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  52092. break;
  52093. case "spheres":
  52094. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  52095. break;
  52096. case "cylinders":
  52097. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  52098. break;
  52099. case "toruses":
  52100. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  52101. break;
  52102. case "grounds":
  52103. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  52104. break;
  52105. case "planes":
  52106. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  52107. break;
  52108. case "torusKnots":
  52109. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  52110. break;
  52111. case "vertexData":
  52112. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  52113. break;
  52114. }
  52115. found = true;
  52116. }
  52117. });
  52118. }
  52119. });
  52120. if (found === false) {
  52121. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  52122. }
  52123. }
  52124. }
  52125. // Material ?
  52126. if (parsedMesh.materialId) {
  52127. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  52128. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52129. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  52130. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  52131. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  52132. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  52133. var subMatId = parsedMultiMaterial.materials[matIndex];
  52134. loadedMaterialsIds.push(subMatId);
  52135. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  52136. log += "\n\tMaterial " + mat.toString(fullDetails);
  52137. }
  52138. loadedMaterialsIds.push(parsedMultiMaterial.id);
  52139. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52140. materialFound = true;
  52141. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  52142. break;
  52143. }
  52144. }
  52145. }
  52146. if (materialFound === false) {
  52147. loadedMaterialsIds.push(parsedMesh.materialId);
  52148. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  52149. if (!mat) {
  52150. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  52151. }
  52152. else {
  52153. log += "\n\tMaterial " + mat.toString(fullDetails);
  52154. }
  52155. }
  52156. }
  52157. // Skeleton ?
  52158. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52159. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  52160. if (skeletonAlreadyLoaded === false) {
  52161. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  52162. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  52163. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  52164. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52165. skeletons.push(skeleton);
  52166. loadedSkeletonsIds.push(parsedSkeleton.id);
  52167. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  52168. }
  52169. }
  52170. }
  52171. }
  52172. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52173. meshes.push(mesh);
  52174. log += "\n\tMesh " + mesh.toString(fullDetails);
  52175. }
  52176. }
  52177. // Connecting parents
  52178. var currentMesh;
  52179. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52180. currentMesh = scene.meshes[index];
  52181. if (currentMesh._waitingParentId) {
  52182. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  52183. currentMesh._waitingParentId = null;
  52184. }
  52185. }
  52186. // freeze and compute world matrix application
  52187. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52188. currentMesh = scene.meshes[index];
  52189. if (currentMesh._waitingFreezeWorldMatrix) {
  52190. currentMesh.freezeWorldMatrix();
  52191. currentMesh._waitingFreezeWorldMatrix = null;
  52192. }
  52193. else {
  52194. currentMesh.computeWorldMatrix(true);
  52195. }
  52196. }
  52197. }
  52198. // Particles
  52199. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52200. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52201. var parsedParticleSystem = parsedData.particleSystems[index];
  52202. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  52203. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  52204. }
  52205. }
  52206. }
  52207. return true;
  52208. }
  52209. catch (err) {
  52210. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  52211. if (onError) {
  52212. onError(msg, err);
  52213. }
  52214. else {
  52215. BABYLON.Tools.Log(msg);
  52216. throw err;
  52217. }
  52218. }
  52219. finally {
  52220. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52221. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52222. }
  52223. }
  52224. return false;
  52225. },
  52226. load: function (scene, data, rootUrl, onError) {
  52227. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52228. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52229. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52230. // and avoid problems with multiple concurrent .babylon loads.
  52231. var log = "importScene has failed JSON parse";
  52232. try {
  52233. var parsedData = JSON.parse(data);
  52234. log = "";
  52235. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52236. // Scene
  52237. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  52238. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  52239. }
  52240. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  52241. scene.autoClear = parsedData.autoClear;
  52242. }
  52243. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  52244. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  52245. }
  52246. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  52247. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  52248. }
  52249. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  52250. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  52251. }
  52252. // Fog
  52253. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  52254. scene.fogMode = parsedData.fogMode;
  52255. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  52256. scene.fogStart = parsedData.fogStart;
  52257. scene.fogEnd = parsedData.fogEnd;
  52258. scene.fogDensity = parsedData.fogDensity;
  52259. log += "\tFog mode for scene: ";
  52260. switch (scene.fogMode) {
  52261. // getters not compiling, so using hardcoded
  52262. case 1:
  52263. log += "exp\n";
  52264. break;
  52265. case 2:
  52266. log += "exp2\n";
  52267. break;
  52268. case 3:
  52269. log += "linear\n";
  52270. break;
  52271. }
  52272. }
  52273. //Physics
  52274. if (parsedData.physicsEnabled) {
  52275. var physicsPlugin;
  52276. if (parsedData.physicsEngine === "cannon") {
  52277. physicsPlugin = new BABYLON.CannonJSPlugin();
  52278. }
  52279. else if (parsedData.physicsEngine === "oimo") {
  52280. physicsPlugin = new BABYLON.OimoJSPlugin();
  52281. }
  52282. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  52283. //else - default engine, which is currently oimo
  52284. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  52285. scene.enablePhysics(physicsGravity, physicsPlugin);
  52286. }
  52287. // Metadata
  52288. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  52289. scene.metadata = parsedData.metadata;
  52290. }
  52291. //collisions, if defined. otherwise, default is true
  52292. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  52293. scene.collisionsEnabled = parsedData.collisionsEnabled;
  52294. }
  52295. scene.workerCollisions = !!parsedData.workerCollisions;
  52296. var index;
  52297. var cache;
  52298. // Lights
  52299. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  52300. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  52301. var parsedLight = parsedData.lights[index];
  52302. var light = BABYLON.Light.Parse(parsedLight, scene);
  52303. if (light) {
  52304. log += (index === 0 ? "\n\tLights:" : "");
  52305. log += "\n\t\t" + light.toString(fullDetails);
  52306. }
  52307. }
  52308. }
  52309. // Animations
  52310. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  52311. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  52312. var parsedAnimation = parsedData.animations[index];
  52313. var animation = BABYLON.Animation.Parse(parsedAnimation);
  52314. scene.animations.push(animation);
  52315. log += (index === 0 ? "\n\tAnimations:" : "");
  52316. log += "\n\t\t" + animation.toString(fullDetails);
  52317. }
  52318. }
  52319. if (parsedData.autoAnimate) {
  52320. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  52321. }
  52322. // Materials
  52323. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  52324. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52325. var parsedMaterial = parsedData.materials[index];
  52326. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52327. log += (index === 0 ? "\n\tMaterials:" : "");
  52328. log += "\n\t\t" + mat.toString(fullDetails);
  52329. }
  52330. }
  52331. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52332. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  52333. var parsedMultiMaterial = parsedData.multiMaterials[index];
  52334. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52335. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  52336. log += "\n\t\t" + mmat.toString(fullDetails);
  52337. }
  52338. }
  52339. // Morph targets
  52340. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  52341. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  52342. var managerData = _a[_i];
  52343. BABYLON.MorphTargetManager.Parse(managerData, scene);
  52344. }
  52345. }
  52346. // Skeletons
  52347. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52348. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  52349. var parsedSkeleton = parsedData.skeletons[index];
  52350. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52351. log += (index === 0 ? "\n\tSkeletons:" : "");
  52352. log += "\n\t\t" + skeleton.toString(fullDetails);
  52353. }
  52354. }
  52355. // Geometries
  52356. var geometries = parsedData.geometries;
  52357. if (geometries !== undefined && geometries !== null) {
  52358. // Boxes
  52359. var boxes = geometries.boxes;
  52360. if (boxes !== undefined && boxes !== null) {
  52361. for (index = 0, cache = boxes.length; index < cache; index++) {
  52362. var parsedBox = boxes[index];
  52363. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  52364. }
  52365. }
  52366. // Spheres
  52367. var spheres = geometries.spheres;
  52368. if (spheres !== undefined && spheres !== null) {
  52369. for (index = 0, cache = spheres.length; index < cache; index++) {
  52370. var parsedSphere = spheres[index];
  52371. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  52372. }
  52373. }
  52374. // Cylinders
  52375. var cylinders = geometries.cylinders;
  52376. if (cylinders !== undefined && cylinders !== null) {
  52377. for (index = 0, cache = cylinders.length; index < cache; index++) {
  52378. var parsedCylinder = cylinders[index];
  52379. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  52380. }
  52381. }
  52382. // Toruses
  52383. var toruses = geometries.toruses;
  52384. if (toruses !== undefined && toruses !== null) {
  52385. for (index = 0, cache = toruses.length; index < cache; index++) {
  52386. var parsedTorus = toruses[index];
  52387. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  52388. }
  52389. }
  52390. // Grounds
  52391. var grounds = geometries.grounds;
  52392. if (grounds !== undefined && grounds !== null) {
  52393. for (index = 0, cache = grounds.length; index < cache; index++) {
  52394. var parsedGround = grounds[index];
  52395. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  52396. }
  52397. }
  52398. // Planes
  52399. var planes = geometries.planes;
  52400. if (planes !== undefined && planes !== null) {
  52401. for (index = 0, cache = planes.length; index < cache; index++) {
  52402. var parsedPlane = planes[index];
  52403. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  52404. }
  52405. }
  52406. // TorusKnots
  52407. var torusKnots = geometries.torusKnots;
  52408. if (torusKnots !== undefined && torusKnots !== null) {
  52409. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  52410. var parsedTorusKnot = torusKnots[index];
  52411. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  52412. }
  52413. }
  52414. // VertexData
  52415. var vertexData = geometries.vertexData;
  52416. if (vertexData !== undefined && vertexData !== null) {
  52417. for (index = 0, cache = vertexData.length; index < cache; index++) {
  52418. var parsedVertexData = vertexData[index];
  52419. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  52420. }
  52421. }
  52422. }
  52423. // Meshes
  52424. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52425. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52426. var parsedMesh = parsedData.meshes[index];
  52427. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52428. log += (index === 0 ? "\n\tMeshes:" : "");
  52429. log += "\n\t\t" + mesh.toString(fullDetails);
  52430. }
  52431. }
  52432. // Cameras
  52433. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  52434. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  52435. var parsedCamera = parsedData.cameras[index];
  52436. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  52437. log += (index === 0 ? "\n\tCameras:" : "");
  52438. log += "\n\t\t" + camera.toString(fullDetails);
  52439. }
  52440. }
  52441. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  52442. scene.setActiveCameraByID(parsedData.activeCameraID);
  52443. }
  52444. // Browsing all the graph to connect the dots
  52445. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  52446. var camera = scene.cameras[index];
  52447. if (camera._waitingParentId) {
  52448. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  52449. camera._waitingParentId = null;
  52450. }
  52451. }
  52452. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52453. var light_1 = scene.lights[index];
  52454. if (light_1 && light_1._waitingParentId) {
  52455. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  52456. light_1._waitingParentId = null;
  52457. }
  52458. }
  52459. // Sounds
  52460. var loadedSounds = [];
  52461. var loadedSound;
  52462. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  52463. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  52464. var parsedSound = parsedData.sounds[index];
  52465. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52466. if (!parsedSound.url)
  52467. parsedSound.url = parsedSound.name;
  52468. if (!loadedSounds[parsedSound.url]) {
  52469. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  52470. loadedSounds[parsedSound.url] = loadedSound;
  52471. }
  52472. else {
  52473. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  52474. }
  52475. }
  52476. else {
  52477. new BABYLON.Sound(parsedSound.name, null, scene);
  52478. }
  52479. }
  52480. }
  52481. loadedSounds = [];
  52482. // Connect parents & children and parse actions
  52483. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52484. var mesh = scene.meshes[index];
  52485. if (mesh._waitingParentId) {
  52486. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  52487. mesh._waitingParentId = null;
  52488. }
  52489. if (mesh._waitingActions) {
  52490. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  52491. mesh._waitingActions = null;
  52492. }
  52493. }
  52494. // freeze world matrix application
  52495. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52496. var currentMesh = scene.meshes[index];
  52497. if (currentMesh._waitingFreezeWorldMatrix) {
  52498. currentMesh.freezeWorldMatrix();
  52499. currentMesh._waitingFreezeWorldMatrix = null;
  52500. }
  52501. else {
  52502. currentMesh.computeWorldMatrix(true);
  52503. }
  52504. }
  52505. // Particles Systems
  52506. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52507. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52508. var parsedParticleSystem = parsedData.particleSystems[index];
  52509. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  52510. }
  52511. }
  52512. // Environment texture
  52513. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  52514. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  52515. if (parsedData.createDefaultSkybox === true) {
  52516. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  52517. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  52518. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  52519. }
  52520. }
  52521. // Lens flares
  52522. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  52523. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  52524. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  52525. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  52526. }
  52527. }
  52528. // Shadows
  52529. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  52530. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  52531. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  52532. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  52533. }
  52534. }
  52535. // Lights exclusions / inclusions
  52536. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52537. var light_2 = scene.lights[index];
  52538. // Excluded check
  52539. if (light_2._excludedMeshesIds.length > 0) {
  52540. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  52541. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  52542. if (excludedMesh) {
  52543. light_2.excludedMeshes.push(excludedMesh);
  52544. }
  52545. }
  52546. light_2._excludedMeshesIds = [];
  52547. }
  52548. // Included check
  52549. if (light_2._includedOnlyMeshesIds.length > 0) {
  52550. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  52551. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  52552. if (includedOnlyMesh) {
  52553. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  52554. }
  52555. }
  52556. light_2._includedOnlyMeshesIds = [];
  52557. }
  52558. }
  52559. // Actions (scene)
  52560. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  52561. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  52562. }
  52563. // Finish
  52564. return true;
  52565. }
  52566. catch (err) {
  52567. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  52568. if (onError) {
  52569. onError(msg, err);
  52570. }
  52571. else {
  52572. BABYLON.Tools.Log(msg);
  52573. throw err;
  52574. }
  52575. }
  52576. finally {
  52577. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52578. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52579. }
  52580. }
  52581. return false;
  52582. }
  52583. });
  52584. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52585. })(BABYLON || (BABYLON = {}));
  52586. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  52587. var BABYLON;
  52588. (function (BABYLON) {
  52589. var FilesInput = /** @class */ (function () {
  52590. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  52591. this.onProcessFileCallback = function () { return true; };
  52592. this._engine = engine;
  52593. this._currentScene = scene;
  52594. this._sceneLoadedCallback = sceneLoadedCallback;
  52595. this._progressCallback = progressCallback;
  52596. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  52597. this._textureLoadingCallback = textureLoadingCallback;
  52598. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  52599. this._onReloadCallback = onReloadCallback;
  52600. this._errorCallback = errorCallback;
  52601. }
  52602. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  52603. var _this = this;
  52604. if (elementToMonitor) {
  52605. this._elementToMonitor = elementToMonitor;
  52606. this._dragEnterHandler = function (e) { _this.drag(e); };
  52607. this._dragOverHandler = function (e) { _this.drag(e); };
  52608. this._dropHandler = function (e) { _this.drop(e); };
  52609. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  52610. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  52611. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  52612. }
  52613. };
  52614. FilesInput.prototype.dispose = function () {
  52615. if (!this._elementToMonitor) {
  52616. return;
  52617. }
  52618. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  52619. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  52620. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  52621. };
  52622. FilesInput.prototype.renderFunction = function () {
  52623. if (this._additionalRenderLoopLogicCallback) {
  52624. this._additionalRenderLoopLogicCallback();
  52625. }
  52626. if (this._currentScene) {
  52627. if (this._textureLoadingCallback) {
  52628. var remaining = this._currentScene.getWaitingItemsCount();
  52629. if (remaining > 0) {
  52630. this._textureLoadingCallback(remaining);
  52631. }
  52632. }
  52633. this._currentScene.render();
  52634. }
  52635. };
  52636. FilesInput.prototype.drag = function (e) {
  52637. e.stopPropagation();
  52638. e.preventDefault();
  52639. };
  52640. FilesInput.prototype.drop = function (eventDrop) {
  52641. eventDrop.stopPropagation();
  52642. eventDrop.preventDefault();
  52643. this.loadFiles(eventDrop);
  52644. };
  52645. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  52646. var _this = this;
  52647. var reader = folder.createReader();
  52648. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  52649. reader.readEntries(function (entries) {
  52650. remaining.count += entries.length;
  52651. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  52652. var entry = entries_1[_i];
  52653. if (entry.isFile) {
  52654. entry.file(function (file) {
  52655. file.correctName = relativePath + file.name;
  52656. files.push(file);
  52657. if (--remaining.count === 0) {
  52658. callback();
  52659. }
  52660. });
  52661. }
  52662. else if (entry.isDirectory) {
  52663. _this._traverseFolder(entry, files, remaining, callback);
  52664. }
  52665. }
  52666. if (--remaining.count) {
  52667. callback();
  52668. }
  52669. });
  52670. };
  52671. FilesInput.prototype._processFiles = function (files) {
  52672. var skippedFiles = 0;
  52673. for (var i = 0; i < files.length; i++) {
  52674. var name = files[i].correctName.toLowerCase();
  52675. var extension = name.split('.').pop();
  52676. if (!this.onProcessFileCallback(files[i], name, extension)) {
  52677. skippedFiles++;
  52678. continue;
  52679. }
  52680. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  52681. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  52682. this._sceneFileToLoad = files[i];
  52683. }
  52684. else {
  52685. FilesInput.FilesToLoad[name] = files[i];
  52686. }
  52687. }
  52688. if (this._onReloadCallback) {
  52689. this._onReloadCallback(this._sceneFileToLoad);
  52690. }
  52691. else if (skippedFiles < files.length) {
  52692. this.reload();
  52693. }
  52694. };
  52695. FilesInput.prototype.loadFiles = function (event) {
  52696. var _this = this;
  52697. if (this._startingProcessingFilesCallback)
  52698. this._startingProcessingFilesCallback();
  52699. // Handling data transfer via drag'n'drop
  52700. if (event && event.dataTransfer && event.dataTransfer.files) {
  52701. this._filesToLoad = event.dataTransfer.files;
  52702. }
  52703. // Handling files from input files
  52704. if (event && event.target && event.target.files) {
  52705. this._filesToLoad = event.target.files;
  52706. }
  52707. if (this._filesToLoad && this._filesToLoad.length > 0) {
  52708. var files_1 = new Array();
  52709. var folders = [];
  52710. var items = event.dataTransfer ? event.dataTransfer.items : null;
  52711. for (var i = 0; i < this._filesToLoad.length; i++) {
  52712. var fileToLoad = this._filesToLoad[i];
  52713. var name_1 = fileToLoad.name.toLowerCase();
  52714. var entry = void 0;
  52715. fileToLoad.correctName = name_1;
  52716. if (items) {
  52717. var item = items[i];
  52718. if (item.getAsEntry) {
  52719. entry = item.getAsEntry();
  52720. }
  52721. else if (item.webkitGetAsEntry) {
  52722. entry = item.webkitGetAsEntry();
  52723. }
  52724. }
  52725. if (!entry) {
  52726. files_1.push(fileToLoad);
  52727. }
  52728. else {
  52729. if (entry.isDirectory) {
  52730. folders.push(entry);
  52731. }
  52732. else {
  52733. files_1.push(fileToLoad);
  52734. }
  52735. }
  52736. }
  52737. if (folders.length === 0) {
  52738. this._processFiles(files_1);
  52739. }
  52740. else {
  52741. var remaining = { count: folders.length };
  52742. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  52743. var folder = folders_1[_i];
  52744. this._traverseFolder(folder, files_1, remaining, function () {
  52745. _this._processFiles(files_1);
  52746. });
  52747. }
  52748. }
  52749. }
  52750. };
  52751. FilesInput.prototype.reload = function () {
  52752. var _this = this;
  52753. // If a ".babylon" file has been provided
  52754. if (this._sceneFileToLoad) {
  52755. if (this._currentScene) {
  52756. if (BABYLON.Tools.errorsCount > 0) {
  52757. BABYLON.Tools.ClearLogCache();
  52758. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  52759. }
  52760. this._engine.stopRenderLoop();
  52761. this._currentScene.dispose();
  52762. }
  52763. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  52764. _this._currentScene = newScene;
  52765. if (_this._sceneLoadedCallback) {
  52766. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  52767. }
  52768. // Wait for textures and shaders to be ready
  52769. _this._currentScene.executeWhenReady(function () {
  52770. _this._engine.runRenderLoop(function () {
  52771. _this.renderFunction();
  52772. });
  52773. });
  52774. }, function (progress) {
  52775. if (_this._progressCallback) {
  52776. _this._progressCallback(progress);
  52777. }
  52778. }, function (scene, message) {
  52779. _this._currentScene = scene;
  52780. if (_this._errorCallback) {
  52781. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  52782. }
  52783. });
  52784. }
  52785. else {
  52786. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  52787. }
  52788. };
  52789. FilesInput.FilesToLoad = {};
  52790. return FilesInput;
  52791. }());
  52792. BABYLON.FilesInput = FilesInput;
  52793. })(BABYLON || (BABYLON = {}));
  52794. //# sourceMappingURL=babylon.filesInput.js.map
  52795. var BABYLON;
  52796. (function (BABYLON) {
  52797. /**
  52798. * This class implement a typical dictionary using a string as key and the generic type T as value.
  52799. * The underlying implementation relies on an associative array to ensure the best performances.
  52800. * The value can be anything including 'null' but except 'undefined'
  52801. */
  52802. var StringDictionary = /** @class */ (function () {
  52803. function StringDictionary() {
  52804. this._count = 0;
  52805. this._data = {};
  52806. }
  52807. /**
  52808. * This will clear this dictionary and copy the content from the 'source' one.
  52809. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  52810. * @param source the dictionary to take the content from and copy to this dictionary
  52811. */
  52812. StringDictionary.prototype.copyFrom = function (source) {
  52813. var _this = this;
  52814. this.clear();
  52815. source.forEach(function (t, v) { return _this.add(t, v); });
  52816. };
  52817. /**
  52818. * Get a value based from its key
  52819. * @param key the given key to get the matching value from
  52820. * @return the value if found, otherwise undefined is returned
  52821. */
  52822. StringDictionary.prototype.get = function (key) {
  52823. var val = this._data[key];
  52824. if (val !== undefined) {
  52825. return val;
  52826. }
  52827. return undefined;
  52828. };
  52829. /**
  52830. * Get a value from its key or add it if it doesn't exist.
  52831. * This method will ensure you that a given key/data will be present in the dictionary.
  52832. * @param key the given key to get the matching value from
  52833. * @param factory the factory that will create the value if the key is not present in the dictionary.
  52834. * The factory will only be invoked if there's no data for the given key.
  52835. * @return the value corresponding to the key.
  52836. */
  52837. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  52838. var val = this.get(key);
  52839. if (val !== undefined) {
  52840. return val;
  52841. }
  52842. val = factory(key);
  52843. if (val) {
  52844. this.add(key, val);
  52845. }
  52846. return val;
  52847. };
  52848. /**
  52849. * Get a value from its key if present in the dictionary otherwise add it
  52850. * @param key the key to get the value from
  52851. * @param val if there's no such key/value pair in the dictionary add it with this value
  52852. * @return the value corresponding to the key
  52853. */
  52854. StringDictionary.prototype.getOrAdd = function (key, val) {
  52855. var curVal = this.get(key);
  52856. if (curVal !== undefined) {
  52857. return curVal;
  52858. }
  52859. this.add(key, val);
  52860. return val;
  52861. };
  52862. /**
  52863. * Check if there's a given key in the dictionary
  52864. * @param key the key to check for
  52865. * @return true if the key is present, false otherwise
  52866. */
  52867. StringDictionary.prototype.contains = function (key) {
  52868. return this._data[key] !== undefined;
  52869. };
  52870. /**
  52871. * Add a new key and its corresponding value
  52872. * @param key the key to add
  52873. * @param value the value corresponding to the key
  52874. * @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
  52875. */
  52876. StringDictionary.prototype.add = function (key, value) {
  52877. if (this._data[key] !== undefined) {
  52878. return false;
  52879. }
  52880. this._data[key] = value;
  52881. ++this._count;
  52882. return true;
  52883. };
  52884. StringDictionary.prototype.set = function (key, value) {
  52885. if (this._data[key] === undefined) {
  52886. return false;
  52887. }
  52888. this._data[key] = value;
  52889. return true;
  52890. };
  52891. /**
  52892. * Get the element of the given key and remove it from the dictionary
  52893. * @param key
  52894. */
  52895. StringDictionary.prototype.getAndRemove = function (key) {
  52896. var val = this.get(key);
  52897. if (val !== undefined) {
  52898. delete this._data[key];
  52899. --this._count;
  52900. return val;
  52901. }
  52902. return null;
  52903. };
  52904. /**
  52905. * Remove a key/value from the dictionary.
  52906. * @param key the key to remove
  52907. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  52908. */
  52909. StringDictionary.prototype.remove = function (key) {
  52910. if (this.contains(key)) {
  52911. delete this._data[key];
  52912. --this._count;
  52913. return true;
  52914. }
  52915. return false;
  52916. };
  52917. /**
  52918. * Clear the whole content of the dictionary
  52919. */
  52920. StringDictionary.prototype.clear = function () {
  52921. this._data = {};
  52922. this._count = 0;
  52923. };
  52924. Object.defineProperty(StringDictionary.prototype, "count", {
  52925. get: function () {
  52926. return this._count;
  52927. },
  52928. enumerable: true,
  52929. configurable: true
  52930. });
  52931. /**
  52932. * Execute a callback on each key/val of the dictionary.
  52933. * Note that you can remove any element in this dictionary in the callback implementation
  52934. * @param callback the callback to execute on a given key/value pair
  52935. */
  52936. StringDictionary.prototype.forEach = function (callback) {
  52937. for (var cur in this._data) {
  52938. var val = this._data[cur];
  52939. callback(cur, val);
  52940. }
  52941. };
  52942. /**
  52943. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  52944. * If the callback returns null or undefined the method will iterate to the next key/value pair
  52945. * Note that you can remove any element in this dictionary in the callback implementation
  52946. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  52947. */
  52948. StringDictionary.prototype.first = function (callback) {
  52949. for (var cur in this._data) {
  52950. var val = this._data[cur];
  52951. var res = callback(cur, val);
  52952. if (res) {
  52953. return res;
  52954. }
  52955. }
  52956. return null;
  52957. };
  52958. return StringDictionary;
  52959. }());
  52960. BABYLON.StringDictionary = StringDictionary;
  52961. })(BABYLON || (BABYLON = {}));
  52962. //# sourceMappingURL=babylon.stringDictionary.js.map
  52963. var BABYLON;
  52964. (function (BABYLON) {
  52965. var Tags = /** @class */ (function () {
  52966. function Tags() {
  52967. }
  52968. Tags.EnableFor = function (obj) {
  52969. obj._tags = obj._tags || {};
  52970. obj.hasTags = function () {
  52971. return Tags.HasTags(obj);
  52972. };
  52973. obj.addTags = function (tagsString) {
  52974. return Tags.AddTagsTo(obj, tagsString);
  52975. };
  52976. obj.removeTags = function (tagsString) {
  52977. return Tags.RemoveTagsFrom(obj, tagsString);
  52978. };
  52979. obj.matchesTagsQuery = function (tagsQuery) {
  52980. return Tags.MatchesQuery(obj, tagsQuery);
  52981. };
  52982. };
  52983. Tags.DisableFor = function (obj) {
  52984. delete obj._tags;
  52985. delete obj.hasTags;
  52986. delete obj.addTags;
  52987. delete obj.removeTags;
  52988. delete obj.matchesTagsQuery;
  52989. };
  52990. Tags.HasTags = function (obj) {
  52991. if (!obj._tags) {
  52992. return false;
  52993. }
  52994. return !BABYLON.Tools.IsEmpty(obj._tags);
  52995. };
  52996. Tags.GetTags = function (obj, asString) {
  52997. if (asString === void 0) { asString = true; }
  52998. if (!obj._tags) {
  52999. return null;
  53000. }
  53001. if (asString) {
  53002. var tagsArray = [];
  53003. for (var tag in obj._tags) {
  53004. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53005. tagsArray.push(tag);
  53006. }
  53007. }
  53008. return tagsArray.join(" ");
  53009. }
  53010. else {
  53011. return obj._tags;
  53012. }
  53013. };
  53014. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53015. // a tag cannot start with '||', '&&', and '!'
  53016. // it cannot contain whitespaces
  53017. Tags.AddTagsTo = function (obj, tagsString) {
  53018. if (!tagsString) {
  53019. return;
  53020. }
  53021. if (typeof tagsString !== "string") {
  53022. return;
  53023. }
  53024. var tags = tagsString.split(" ");
  53025. tags.forEach(function (tag, index, array) {
  53026. Tags._AddTagTo(obj, tag);
  53027. });
  53028. };
  53029. Tags._AddTagTo = function (obj, tag) {
  53030. tag = tag.trim();
  53031. if (tag === "" || tag === "true" || tag === "false") {
  53032. return;
  53033. }
  53034. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53035. return;
  53036. }
  53037. Tags.EnableFor(obj);
  53038. obj._tags[tag] = true;
  53039. };
  53040. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53041. if (!Tags.HasTags(obj)) {
  53042. return;
  53043. }
  53044. var tags = tagsString.split(" ");
  53045. for (var t in tags) {
  53046. Tags._RemoveTagFrom(obj, tags[t]);
  53047. }
  53048. };
  53049. Tags._RemoveTagFrom = function (obj, tag) {
  53050. delete obj._tags[tag];
  53051. };
  53052. Tags.MatchesQuery = function (obj, tagsQuery) {
  53053. if (tagsQuery === undefined) {
  53054. return true;
  53055. }
  53056. if (tagsQuery === "") {
  53057. return Tags.HasTags(obj);
  53058. }
  53059. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53060. };
  53061. return Tags;
  53062. }());
  53063. BABYLON.Tags = Tags;
  53064. })(BABYLON || (BABYLON = {}));
  53065. //# sourceMappingURL=babylon.tags.js.map
  53066. var BABYLON;
  53067. (function (BABYLON) {
  53068. var Internals;
  53069. (function (Internals) {
  53070. var AndOrNotEvaluator = /** @class */ (function () {
  53071. function AndOrNotEvaluator() {
  53072. }
  53073. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  53074. if (!query.match(/\([^\(\)]*\)/g)) {
  53075. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  53076. }
  53077. else {
  53078. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  53079. // remove parenthesis
  53080. r = r.slice(1, r.length - 1);
  53081. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  53082. });
  53083. }
  53084. if (query === "true") {
  53085. return true;
  53086. }
  53087. if (query === "false") {
  53088. return false;
  53089. }
  53090. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  53091. };
  53092. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  53093. evaluateCallback = evaluateCallback || (function (r) {
  53094. return r === "true" ? true : false;
  53095. });
  53096. var result;
  53097. var or = parenthesisContent.split("||");
  53098. for (var i in or) {
  53099. if (or.hasOwnProperty(i)) {
  53100. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  53101. var and = ori.split("&&");
  53102. if (and.length > 1) {
  53103. for (var j = 0; j < and.length; ++j) {
  53104. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  53105. if (andj !== "true" && andj !== "false") {
  53106. if (andj[0] === "!") {
  53107. result = !evaluateCallback(andj.substring(1));
  53108. }
  53109. else {
  53110. result = evaluateCallback(andj);
  53111. }
  53112. }
  53113. else {
  53114. result = andj === "true" ? true : false;
  53115. }
  53116. if (!result) {
  53117. ori = "false";
  53118. break;
  53119. }
  53120. }
  53121. }
  53122. if (result || ori === "true") {
  53123. result = true;
  53124. break;
  53125. }
  53126. // result equals false (or undefined)
  53127. if (ori !== "true" && ori !== "false") {
  53128. if (ori[0] === "!") {
  53129. result = !evaluateCallback(ori.substring(1));
  53130. }
  53131. else {
  53132. result = evaluateCallback(ori);
  53133. }
  53134. }
  53135. else {
  53136. result = ori === "true" ? true : false;
  53137. }
  53138. }
  53139. }
  53140. // the whole parenthesis scope is replaced by 'true' or 'false'
  53141. return result ? "true" : "false";
  53142. };
  53143. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  53144. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  53145. // remove whitespaces
  53146. r = r.replace(/[\s]/g, function () { return ""; });
  53147. return r.length % 2 ? "!" : "";
  53148. });
  53149. booleanString = booleanString.trim();
  53150. if (booleanString === "!true") {
  53151. booleanString = "false";
  53152. }
  53153. else if (booleanString === "!false") {
  53154. booleanString = "true";
  53155. }
  53156. return booleanString;
  53157. };
  53158. return AndOrNotEvaluator;
  53159. }());
  53160. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  53161. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53162. })(BABYLON || (BABYLON = {}));
  53163. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  53164. var BABYLON;
  53165. (function (BABYLON) {
  53166. var Database = /** @class */ (function () {
  53167. function Database(urlToScene, callbackManifestChecked) {
  53168. // Handling various flavors of prefixed version of IndexedDB
  53169. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  53170. this.callbackManifestChecked = callbackManifestChecked;
  53171. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  53172. this.db = null;
  53173. this._enableSceneOffline = false;
  53174. this._enableTexturesOffline = false;
  53175. this.manifestVersionFound = 0;
  53176. this.mustUpdateRessources = false;
  53177. this.hasReachedQuota = false;
  53178. if (!Database.IDBStorageEnabled) {
  53179. this.callbackManifestChecked(true);
  53180. }
  53181. else {
  53182. this.checkManifestFile();
  53183. }
  53184. }
  53185. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  53186. get: function () {
  53187. return this._enableSceneOffline;
  53188. },
  53189. enumerable: true,
  53190. configurable: true
  53191. });
  53192. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  53193. get: function () {
  53194. return this._enableTexturesOffline;
  53195. },
  53196. enumerable: true,
  53197. configurable: true
  53198. });
  53199. Database.prototype.checkManifestFile = function () {
  53200. var _this = this;
  53201. var noManifestFile = function () {
  53202. _this._enableSceneOffline = false;
  53203. _this._enableTexturesOffline = false;
  53204. _this.callbackManifestChecked(false);
  53205. };
  53206. var timeStampUsed = false;
  53207. var manifestURL = this.currentSceneUrl + ".manifest";
  53208. var xhr = new XMLHttpRequest();
  53209. if (navigator.onLine) {
  53210. // Adding a timestamp to by-pass browsers' cache
  53211. timeStampUsed = true;
  53212. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  53213. }
  53214. xhr.open("GET", manifestURL, true);
  53215. xhr.addEventListener("load", function () {
  53216. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53217. try {
  53218. var manifestFile = JSON.parse(xhr.response);
  53219. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  53220. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  53221. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  53222. _this.manifestVersionFound = manifestFile.version;
  53223. }
  53224. if (_this.callbackManifestChecked) {
  53225. _this.callbackManifestChecked(true);
  53226. }
  53227. }
  53228. catch (ex) {
  53229. noManifestFile();
  53230. }
  53231. }
  53232. else {
  53233. noManifestFile();
  53234. }
  53235. }, false);
  53236. xhr.addEventListener("error", function (event) {
  53237. if (timeStampUsed) {
  53238. timeStampUsed = false;
  53239. // Let's retry without the timeStamp
  53240. // It could fail when coupled with HTML5 Offline API
  53241. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  53242. xhr.open("GET", retryManifestURL, true);
  53243. xhr.send();
  53244. }
  53245. else {
  53246. noManifestFile();
  53247. }
  53248. }, false);
  53249. try {
  53250. xhr.send();
  53251. }
  53252. catch (ex) {
  53253. BABYLON.Tools.Error("Error on XHR send request.");
  53254. this.callbackManifestChecked(false);
  53255. }
  53256. };
  53257. Database.prototype.openAsync = function (successCallback, errorCallback) {
  53258. var _this = this;
  53259. var handleError = function () {
  53260. _this.isSupported = false;
  53261. if (errorCallback)
  53262. errorCallback();
  53263. };
  53264. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  53265. // Your browser doesn't support IndexedDB
  53266. this.isSupported = false;
  53267. if (errorCallback)
  53268. errorCallback();
  53269. }
  53270. else {
  53271. // If the DB hasn't been opened or created yet
  53272. if (!this.db) {
  53273. this.hasReachedQuota = false;
  53274. this.isSupported = true;
  53275. var request = this.idbFactory.open("babylonjs", 1);
  53276. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  53277. request.onerror = function (event) {
  53278. handleError();
  53279. };
  53280. // executes when a version change transaction cannot complete due to other active transactions
  53281. request.onblocked = function (event) {
  53282. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  53283. handleError();
  53284. };
  53285. // DB has been opened successfully
  53286. request.onsuccess = function (event) {
  53287. _this.db = request.result;
  53288. successCallback();
  53289. };
  53290. // Initialization of the DB. Creating Scenes & Textures stores
  53291. request.onupgradeneeded = function (event) {
  53292. _this.db = (event.target).result;
  53293. if (_this.db) {
  53294. try {
  53295. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  53296. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  53297. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  53298. }
  53299. catch (ex) {
  53300. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  53301. handleError();
  53302. }
  53303. }
  53304. };
  53305. }
  53306. else {
  53307. if (successCallback)
  53308. successCallback();
  53309. }
  53310. }
  53311. };
  53312. Database.prototype.loadImageFromDB = function (url, image) {
  53313. var _this = this;
  53314. var completeURL = Database.ReturnFullUrlLocation(url);
  53315. var saveAndLoadImage = function () {
  53316. if (!_this.hasReachedQuota && _this.db !== null) {
  53317. // the texture is not yet in the DB, let's try to save it
  53318. _this._saveImageIntoDBAsync(completeURL, image);
  53319. }
  53320. else {
  53321. image.src = url;
  53322. }
  53323. };
  53324. if (!this.mustUpdateRessources) {
  53325. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  53326. }
  53327. else {
  53328. saveAndLoadImage();
  53329. }
  53330. };
  53331. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  53332. if (this.isSupported && this.db !== null) {
  53333. var texture;
  53334. var transaction = this.db.transaction(["textures"]);
  53335. transaction.onabort = function (event) {
  53336. image.src = url;
  53337. };
  53338. transaction.oncomplete = function (event) {
  53339. var blobTextureURL;
  53340. if (texture) {
  53341. var URL = window.URL || window.webkitURL;
  53342. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  53343. image.onerror = function () {
  53344. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  53345. image.src = url;
  53346. };
  53347. image.src = blobTextureURL;
  53348. }
  53349. else {
  53350. notInDBCallback();
  53351. }
  53352. };
  53353. var getRequest = transaction.objectStore("textures").get(url);
  53354. getRequest.onsuccess = function (event) {
  53355. texture = (event.target).result;
  53356. };
  53357. getRequest.onerror = function (event) {
  53358. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  53359. image.src = url;
  53360. };
  53361. }
  53362. else {
  53363. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53364. image.src = url;
  53365. }
  53366. };
  53367. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  53368. var _this = this;
  53369. if (this.isSupported) {
  53370. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  53371. var generateBlobUrl = function () {
  53372. var blobTextureURL;
  53373. if (blob) {
  53374. var URL = window.URL || window.webkitURL;
  53375. try {
  53376. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  53377. }
  53378. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  53379. catch (ex) {
  53380. blobTextureURL = URL.createObjectURL(blob);
  53381. }
  53382. }
  53383. if (blobTextureURL) {
  53384. image.src = blobTextureURL;
  53385. }
  53386. };
  53387. if (Database.IsUASupportingBlobStorage) {
  53388. var xhr = new XMLHttpRequest(), blob;
  53389. xhr.open("GET", url, true);
  53390. xhr.responseType = "blob";
  53391. xhr.addEventListener("load", function () {
  53392. if (xhr.status === 200 && _this.db) {
  53393. // Blob as response (XHR2)
  53394. blob = xhr.response;
  53395. var transaction = _this.db.transaction(["textures"], "readwrite");
  53396. // the transaction could abort because of a QuotaExceededError error
  53397. transaction.onabort = function (event) {
  53398. try {
  53399. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53400. var srcElement = (event.srcElement || event.target);
  53401. var error = srcElement.error;
  53402. if (error && error.name === "QuotaExceededError") {
  53403. _this.hasReachedQuota = true;
  53404. }
  53405. }
  53406. catch (ex) { }
  53407. generateBlobUrl();
  53408. };
  53409. transaction.oncomplete = function (event) {
  53410. generateBlobUrl();
  53411. };
  53412. var newTexture = { textureUrl: url, data: blob };
  53413. try {
  53414. // Put the blob into the dabase
  53415. var addRequest = transaction.objectStore("textures").put(newTexture);
  53416. addRequest.onsuccess = function (event) {
  53417. };
  53418. addRequest.onerror = function (event) {
  53419. generateBlobUrl();
  53420. };
  53421. }
  53422. catch (ex) {
  53423. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  53424. if (ex.code === 25) {
  53425. Database.IsUASupportingBlobStorage = false;
  53426. }
  53427. image.src = url;
  53428. }
  53429. }
  53430. else {
  53431. image.src = url;
  53432. }
  53433. }, false);
  53434. xhr.addEventListener("error", function (event) {
  53435. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  53436. image.src = url;
  53437. }, false);
  53438. xhr.send();
  53439. }
  53440. else {
  53441. image.src = url;
  53442. }
  53443. }
  53444. else {
  53445. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53446. image.src = url;
  53447. }
  53448. };
  53449. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  53450. var _this = this;
  53451. var updateVersion = function () {
  53452. // the version is not yet in the DB or we need to update it
  53453. _this._saveVersionIntoDBAsync(url, versionLoaded);
  53454. };
  53455. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  53456. };
  53457. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  53458. var _this = this;
  53459. if (this.isSupported && this.db) {
  53460. var version;
  53461. try {
  53462. var transaction = this.db.transaction(["versions"]);
  53463. transaction.oncomplete = function (event) {
  53464. if (version) {
  53465. // If the version in the JSON file is > than the version in DB
  53466. if (_this.manifestVersionFound > version.data) {
  53467. _this.mustUpdateRessources = true;
  53468. updateInDBCallback();
  53469. }
  53470. else {
  53471. callback(version.data);
  53472. }
  53473. }
  53474. else {
  53475. _this.mustUpdateRessources = true;
  53476. updateInDBCallback();
  53477. }
  53478. };
  53479. transaction.onabort = function (event) {
  53480. callback(-1);
  53481. };
  53482. var getRequest = transaction.objectStore("versions").get(url);
  53483. getRequest.onsuccess = function (event) {
  53484. version = (event.target).result;
  53485. };
  53486. getRequest.onerror = function (event) {
  53487. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  53488. callback(-1);
  53489. };
  53490. }
  53491. catch (ex) {
  53492. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  53493. callback(-1);
  53494. }
  53495. }
  53496. else {
  53497. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53498. callback(-1);
  53499. }
  53500. };
  53501. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  53502. var _this = this;
  53503. if (this.isSupported && !this.hasReachedQuota && this.db) {
  53504. try {
  53505. // Open a transaction to the database
  53506. var transaction = this.db.transaction(["versions"], "readwrite");
  53507. // the transaction could abort because of a QuotaExceededError error
  53508. transaction.onabort = function (event) {
  53509. try {
  53510. var error = event.srcElement['error'];
  53511. if (error && error.name === "QuotaExceededError") {
  53512. _this.hasReachedQuota = true;
  53513. }
  53514. }
  53515. catch (ex) { }
  53516. callback(-1);
  53517. };
  53518. transaction.oncomplete = function (event) {
  53519. callback(_this.manifestVersionFound);
  53520. };
  53521. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  53522. // Put the scene into the database
  53523. var addRequest = transaction.objectStore("versions").put(newVersion);
  53524. addRequest.onsuccess = function (event) {
  53525. };
  53526. addRequest.onerror = function (event) {
  53527. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  53528. };
  53529. }
  53530. catch (ex) {
  53531. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  53532. callback(-1);
  53533. }
  53534. }
  53535. else {
  53536. callback(-1);
  53537. }
  53538. };
  53539. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  53540. var _this = this;
  53541. var completeUrl = Database.ReturnFullUrlLocation(url);
  53542. var saveAndLoadFile = function () {
  53543. // the scene is not yet in the DB, let's try to save it
  53544. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  53545. };
  53546. this._checkVersionFromDB(completeUrl, function (version) {
  53547. if (version !== -1) {
  53548. if (!_this.mustUpdateRessources) {
  53549. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  53550. }
  53551. else {
  53552. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  53553. }
  53554. }
  53555. else {
  53556. if (errorCallback) {
  53557. errorCallback();
  53558. }
  53559. }
  53560. });
  53561. };
  53562. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  53563. if (this.isSupported && this.db) {
  53564. var targetStore;
  53565. if (url.indexOf(".babylon") !== -1) {
  53566. targetStore = "scenes";
  53567. }
  53568. else {
  53569. targetStore = "textures";
  53570. }
  53571. var file;
  53572. var transaction = this.db.transaction([targetStore]);
  53573. transaction.oncomplete = function (event) {
  53574. if (file) {
  53575. callback(file.data);
  53576. }
  53577. else {
  53578. notInDBCallback();
  53579. }
  53580. };
  53581. transaction.onabort = function (event) {
  53582. notInDBCallback();
  53583. };
  53584. var getRequest = transaction.objectStore(targetStore).get(url);
  53585. getRequest.onsuccess = function (event) {
  53586. file = (event.target).result;
  53587. };
  53588. getRequest.onerror = function (event) {
  53589. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  53590. notInDBCallback();
  53591. };
  53592. }
  53593. else {
  53594. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53595. callback();
  53596. }
  53597. };
  53598. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  53599. var _this = this;
  53600. if (this.isSupported) {
  53601. var targetStore;
  53602. if (url.indexOf(".babylon") !== -1) {
  53603. targetStore = "scenes";
  53604. }
  53605. else {
  53606. targetStore = "textures";
  53607. }
  53608. // Create XHR
  53609. var xhr = new XMLHttpRequest();
  53610. var fileData;
  53611. xhr.open("GET", url, true);
  53612. if (useArrayBuffer) {
  53613. xhr.responseType = "arraybuffer";
  53614. }
  53615. if (progressCallback) {
  53616. xhr.onprogress = progressCallback;
  53617. }
  53618. xhr.addEventListener("load", function () {
  53619. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  53620. // Blob as response (XHR2)
  53621. //fileData = xhr.responseText;
  53622. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  53623. if (!_this.hasReachedQuota && _this.db) {
  53624. // Open a transaction to the database
  53625. var transaction = _this.db.transaction([targetStore], "readwrite");
  53626. // the transaction could abort because of a QuotaExceededError error
  53627. transaction.onabort = function (event) {
  53628. try {
  53629. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53630. var error = event.srcElement['error'];
  53631. if (error && error.name === "QuotaExceededError") {
  53632. _this.hasReachedQuota = true;
  53633. }
  53634. }
  53635. catch (ex) { }
  53636. callback(fileData);
  53637. };
  53638. transaction.oncomplete = function (event) {
  53639. callback(fileData);
  53640. };
  53641. var newFile;
  53642. if (targetStore === "scenes") {
  53643. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  53644. }
  53645. else {
  53646. newFile = { textureUrl: url, data: fileData };
  53647. }
  53648. try {
  53649. // Put the scene into the database
  53650. var addRequest = transaction.objectStore(targetStore).put(newFile);
  53651. addRequest.onsuccess = function (event) {
  53652. };
  53653. addRequest.onerror = function (event) {
  53654. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  53655. };
  53656. }
  53657. catch (ex) {
  53658. callback(fileData);
  53659. }
  53660. }
  53661. else {
  53662. callback(fileData);
  53663. }
  53664. }
  53665. else {
  53666. callback();
  53667. }
  53668. }, false);
  53669. xhr.addEventListener("error", function (event) {
  53670. BABYLON.Tools.Error("error on XHR request.");
  53671. callback();
  53672. }, false);
  53673. xhr.send();
  53674. }
  53675. else {
  53676. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53677. callback();
  53678. }
  53679. };
  53680. Database.IsUASupportingBlobStorage = true;
  53681. Database.IDBStorageEnabled = true;
  53682. Database.parseURL = function (url) {
  53683. var a = document.createElement('a');
  53684. a.href = url;
  53685. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  53686. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  53687. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  53688. return absLocation;
  53689. };
  53690. Database.ReturnFullUrlLocation = function (url) {
  53691. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  53692. return (Database.parseURL(window.location.href) + url);
  53693. }
  53694. else {
  53695. return url;
  53696. }
  53697. };
  53698. return Database;
  53699. }());
  53700. BABYLON.Database = Database;
  53701. })(BABYLON || (BABYLON = {}));
  53702. //# sourceMappingURL=babylon.database.js.map
  53703. var BABYLON;
  53704. (function (BABYLON) {
  53705. var FresnelParameters = /** @class */ (function () {
  53706. function FresnelParameters() {
  53707. this._isEnabled = true;
  53708. this.leftColor = BABYLON.Color3.White();
  53709. this.rightColor = BABYLON.Color3.Black();
  53710. this.bias = 0;
  53711. this.power = 1;
  53712. }
  53713. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  53714. get: function () {
  53715. return this._isEnabled;
  53716. },
  53717. set: function (value) {
  53718. if (this._isEnabled === value) {
  53719. return;
  53720. }
  53721. this._isEnabled = value;
  53722. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  53723. },
  53724. enumerable: true,
  53725. configurable: true
  53726. });
  53727. FresnelParameters.prototype.clone = function () {
  53728. var newFresnelParameters = new FresnelParameters();
  53729. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  53730. return newFresnelParameters;
  53731. };
  53732. FresnelParameters.prototype.serialize = function () {
  53733. var serializationObject = {};
  53734. serializationObject.isEnabled = this.isEnabled;
  53735. serializationObject.leftColor = this.leftColor;
  53736. serializationObject.rightColor = this.rightColor;
  53737. serializationObject.bias = this.bias;
  53738. serializationObject.power = this.power;
  53739. return serializationObject;
  53740. };
  53741. FresnelParameters.Parse = function (parsedFresnelParameters) {
  53742. var fresnelParameters = new FresnelParameters();
  53743. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  53744. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  53745. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  53746. fresnelParameters.bias = parsedFresnelParameters.bias;
  53747. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  53748. return fresnelParameters;
  53749. };
  53750. return FresnelParameters;
  53751. }());
  53752. BABYLON.FresnelParameters = FresnelParameters;
  53753. })(BABYLON || (BABYLON = {}));
  53754. //# sourceMappingURL=babylon.fresnelParameters.js.map
  53755. var BABYLON;
  53756. (function (BABYLON) {
  53757. var MultiMaterial = /** @class */ (function (_super) {
  53758. __extends(MultiMaterial, _super);
  53759. function MultiMaterial(name, scene) {
  53760. var _this = _super.call(this, name, scene, true) || this;
  53761. scene.multiMaterials.push(_this);
  53762. _this.subMaterials = new Array();
  53763. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  53764. return _this;
  53765. }
  53766. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  53767. get: function () {
  53768. return this._subMaterials;
  53769. },
  53770. set: function (value) {
  53771. this._subMaterials = value;
  53772. this._hookArray(value);
  53773. },
  53774. enumerable: true,
  53775. configurable: true
  53776. });
  53777. MultiMaterial.prototype._hookArray = function (array) {
  53778. var _this = this;
  53779. var oldPush = array.push;
  53780. array.push = function () {
  53781. var items = [];
  53782. for (var _i = 0; _i < arguments.length; _i++) {
  53783. items[_i] = arguments[_i];
  53784. }
  53785. var result = oldPush.apply(array, items);
  53786. _this._markAllSubMeshesAsTexturesDirty();
  53787. return result;
  53788. };
  53789. var oldSplice = array.splice;
  53790. array.splice = function (index, deleteCount) {
  53791. var deleted = oldSplice.apply(array, [index, deleteCount]);
  53792. _this._markAllSubMeshesAsTexturesDirty();
  53793. return deleted;
  53794. };
  53795. };
  53796. // Properties
  53797. MultiMaterial.prototype.getSubMaterial = function (index) {
  53798. if (index < 0 || index >= this.subMaterials.length) {
  53799. return this.getScene().defaultMaterial;
  53800. }
  53801. return this.subMaterials[index];
  53802. };
  53803. MultiMaterial.prototype.getActiveTextures = function () {
  53804. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  53805. if (subMaterial) {
  53806. return subMaterial.getActiveTextures();
  53807. }
  53808. else {
  53809. return [];
  53810. }
  53811. }));
  53812. var _a;
  53813. };
  53814. // Methods
  53815. MultiMaterial.prototype.getClassName = function () {
  53816. return "MultiMaterial";
  53817. };
  53818. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  53819. for (var index = 0; index < this.subMaterials.length; index++) {
  53820. var subMaterial = this.subMaterials[index];
  53821. if (subMaterial) {
  53822. if (subMaterial.storeEffectOnSubMeshes) {
  53823. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  53824. return false;
  53825. }
  53826. continue;
  53827. }
  53828. if (!subMaterial.isReady(mesh)) {
  53829. return false;
  53830. }
  53831. }
  53832. }
  53833. return true;
  53834. };
  53835. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  53836. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  53837. for (var index = 0; index < this.subMaterials.length; index++) {
  53838. var subMaterial = null;
  53839. var current = this.subMaterials[index];
  53840. if (cloneChildren && current) {
  53841. subMaterial = current.clone(name + "-" + current.name);
  53842. }
  53843. else {
  53844. subMaterial = this.subMaterials[index];
  53845. }
  53846. newMultiMaterial.subMaterials.push(subMaterial);
  53847. }
  53848. return newMultiMaterial;
  53849. };
  53850. MultiMaterial.prototype.serialize = function () {
  53851. var serializationObject = {};
  53852. serializationObject.name = this.name;
  53853. serializationObject.id = this.id;
  53854. serializationObject.tags = BABYLON.Tags.GetTags(this);
  53855. serializationObject.materials = [];
  53856. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  53857. var subMat = this.subMaterials[matIndex];
  53858. if (subMat) {
  53859. serializationObject.materials.push(subMat.id);
  53860. }
  53861. else {
  53862. serializationObject.materials.push(null);
  53863. }
  53864. }
  53865. return serializationObject;
  53866. };
  53867. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53868. var scene = this.getScene();
  53869. if (!scene) {
  53870. return;
  53871. }
  53872. var index = scene.multiMaterials.indexOf(this);
  53873. if (index >= 0) {
  53874. scene.multiMaterials.splice(index, 1);
  53875. }
  53876. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53877. };
  53878. return MultiMaterial;
  53879. }(BABYLON.Material));
  53880. BABYLON.MultiMaterial = MultiMaterial;
  53881. })(BABYLON || (BABYLON = {}));
  53882. //# sourceMappingURL=babylon.multiMaterial.js.map
  53883. var BABYLON;
  53884. (function (BABYLON) {
  53885. var FreeCameraTouchInput = /** @class */ (function () {
  53886. function FreeCameraTouchInput() {
  53887. this._offsetX = null;
  53888. this._offsetY = null;
  53889. this._pointerCount = 0;
  53890. this._pointerPressed = new Array();
  53891. this.touchAngularSensibility = 200000.0;
  53892. this.touchMoveSensibility = 250.0;
  53893. }
  53894. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  53895. var _this = this;
  53896. var previousPosition = null;
  53897. if (this._pointerInput === undefined) {
  53898. this._onLostFocus = function (evt) {
  53899. _this._offsetX = null;
  53900. _this._offsetY = null;
  53901. };
  53902. this._pointerInput = function (p, s) {
  53903. var evt = p.event;
  53904. if (evt.pointerType === "mouse") {
  53905. return;
  53906. }
  53907. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  53908. if (!noPreventDefault) {
  53909. evt.preventDefault();
  53910. }
  53911. _this._pointerPressed.push(evt.pointerId);
  53912. if (_this._pointerPressed.length !== 1) {
  53913. return;
  53914. }
  53915. previousPosition = {
  53916. x: evt.clientX,
  53917. y: evt.clientY
  53918. };
  53919. }
  53920. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  53921. if (!noPreventDefault) {
  53922. evt.preventDefault();
  53923. }
  53924. var index = _this._pointerPressed.indexOf(evt.pointerId);
  53925. if (index === -1) {
  53926. return;
  53927. }
  53928. _this._pointerPressed.splice(index, 1);
  53929. if (index != 0) {
  53930. return;
  53931. }
  53932. previousPosition = null;
  53933. _this._offsetX = null;
  53934. _this._offsetY = null;
  53935. }
  53936. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  53937. if (!noPreventDefault) {
  53938. evt.preventDefault();
  53939. }
  53940. if (!previousPosition) {
  53941. return;
  53942. }
  53943. var index = _this._pointerPressed.indexOf(evt.pointerId);
  53944. if (index != 0) {
  53945. return;
  53946. }
  53947. _this._offsetX = evt.clientX - previousPosition.x;
  53948. _this._offsetY = -(evt.clientY - previousPosition.y);
  53949. }
  53950. };
  53951. }
  53952. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  53953. if (this._onLostFocus) {
  53954. element.addEventListener("blur", this._onLostFocus);
  53955. }
  53956. };
  53957. FreeCameraTouchInput.prototype.detachControl = function (element) {
  53958. if (this._pointerInput && element) {
  53959. if (this._observer) {
  53960. this.camera.getScene().onPointerObservable.remove(this._observer);
  53961. this._observer = null;
  53962. }
  53963. if (this._onLostFocus) {
  53964. element.removeEventListener("blur", this._onLostFocus);
  53965. this._onLostFocus = null;
  53966. }
  53967. this._pointerPressed = [];
  53968. this._offsetX = null;
  53969. this._offsetY = null;
  53970. this._pointerCount = 0;
  53971. }
  53972. };
  53973. FreeCameraTouchInput.prototype.checkInputs = function () {
  53974. if (this._offsetX && this._offsetY) {
  53975. var camera = this.camera;
  53976. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  53977. if (this._pointerPressed.length > 1) {
  53978. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  53979. }
  53980. else {
  53981. var speed = camera._computeLocalCameraSpeed();
  53982. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  53983. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  53984. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  53985. }
  53986. }
  53987. };
  53988. FreeCameraTouchInput.prototype.getClassName = function () {
  53989. return "FreeCameraTouchInput";
  53990. };
  53991. FreeCameraTouchInput.prototype.getSimpleName = function () {
  53992. return "touch";
  53993. };
  53994. __decorate([
  53995. BABYLON.serialize()
  53996. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  53997. __decorate([
  53998. BABYLON.serialize()
  53999. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  54000. return FreeCameraTouchInput;
  54001. }());
  54002. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  54003. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54004. })(BABYLON || (BABYLON = {}));
  54005. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54006. var BABYLON;
  54007. (function (BABYLON) {
  54008. // We're mainly based on the logic defined into the FreeCamera code
  54009. var TouchCamera = /** @class */ (function (_super) {
  54010. __extends(TouchCamera, _super);
  54011. //-- end properties for backward compatibility for inputs
  54012. function TouchCamera(name, position, scene) {
  54013. var _this = _super.call(this, name, position, scene) || this;
  54014. _this.inputs.addTouch();
  54015. _this._setupInputs();
  54016. return _this;
  54017. }
  54018. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54019. //-- Begin properties for backward compatibility for inputs
  54020. get: function () {
  54021. var touch = this.inputs.attached["touch"];
  54022. if (touch)
  54023. return touch.touchAngularSensibility;
  54024. return 0;
  54025. },
  54026. set: function (value) {
  54027. var touch = this.inputs.attached["touch"];
  54028. if (touch)
  54029. touch.touchAngularSensibility = value;
  54030. },
  54031. enumerable: true,
  54032. configurable: true
  54033. });
  54034. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54035. get: function () {
  54036. var touch = this.inputs.attached["touch"];
  54037. if (touch)
  54038. return touch.touchMoveSensibility;
  54039. return 0;
  54040. },
  54041. set: function (value) {
  54042. var touch = this.inputs.attached["touch"];
  54043. if (touch)
  54044. touch.touchMoveSensibility = value;
  54045. },
  54046. enumerable: true,
  54047. configurable: true
  54048. });
  54049. TouchCamera.prototype.getClassName = function () {
  54050. return "TouchCamera";
  54051. };
  54052. TouchCamera.prototype._setupInputs = function () {
  54053. var mouse = this.inputs.attached["mouse"];
  54054. if (mouse) {
  54055. mouse.touchEnabled = false;
  54056. }
  54057. };
  54058. return TouchCamera;
  54059. }(BABYLON.FreeCamera));
  54060. BABYLON.TouchCamera = TouchCamera;
  54061. })(BABYLON || (BABYLON = {}));
  54062. //# sourceMappingURL=babylon.touchCamera.js.map
  54063. var BABYLON;
  54064. (function (BABYLON) {
  54065. var ProceduralTexture = /** @class */ (function (_super) {
  54066. __extends(ProceduralTexture, _super);
  54067. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  54068. if (fallbackTexture === void 0) { fallbackTexture = null; }
  54069. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54070. if (isCube === void 0) { isCube = false; }
  54071. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54072. _this.isCube = isCube;
  54073. _this.isEnabled = true;
  54074. _this._currentRefreshId = -1;
  54075. _this._refreshRate = 1;
  54076. _this._vertexBuffers = {};
  54077. _this._uniforms = new Array();
  54078. _this._samplers = new Array();
  54079. _this._textures = {};
  54080. _this._floats = {};
  54081. _this._floatsArrays = {};
  54082. _this._colors3 = {};
  54083. _this._colors4 = {};
  54084. _this._vectors2 = {};
  54085. _this._vectors3 = {};
  54086. _this._matrices = {};
  54087. _this._fallbackTextureUsed = false;
  54088. scene._proceduralTextures.push(_this);
  54089. _this._engine = scene.getEngine();
  54090. _this.name = name;
  54091. _this.isRenderTarget = true;
  54092. _this._size = size;
  54093. _this._generateMipMaps = generateMipMaps;
  54094. _this.setFragment(fragment);
  54095. _this._fallbackTexture = fallbackTexture;
  54096. if (isCube) {
  54097. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  54098. _this.setFloat("face", 0);
  54099. }
  54100. else {
  54101. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  54102. }
  54103. // VBO
  54104. var vertices = [];
  54105. vertices.push(1, 1);
  54106. vertices.push(-1, 1);
  54107. vertices.push(-1, -1);
  54108. vertices.push(1, -1);
  54109. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54110. _this._createIndexBuffer();
  54111. return _this;
  54112. }
  54113. ProceduralTexture.prototype._createIndexBuffer = function () {
  54114. var engine = this._engine;
  54115. // Indices
  54116. var indices = [];
  54117. indices.push(0);
  54118. indices.push(1);
  54119. indices.push(2);
  54120. indices.push(0);
  54121. indices.push(2);
  54122. indices.push(3);
  54123. this._indexBuffer = engine.createIndexBuffer(indices);
  54124. };
  54125. ProceduralTexture.prototype._rebuild = function () {
  54126. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54127. if (vb) {
  54128. vb._rebuild();
  54129. }
  54130. this._createIndexBuffer();
  54131. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54132. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54133. }
  54134. };
  54135. ProceduralTexture.prototype.reset = function () {
  54136. if (this._effect === undefined) {
  54137. return;
  54138. }
  54139. var engine = this._engine;
  54140. engine._releaseEffect(this._effect);
  54141. };
  54142. ProceduralTexture.prototype.isReady = function () {
  54143. var _this = this;
  54144. var engine = this._engine;
  54145. var shaders;
  54146. if (!this._fragment) {
  54147. return false;
  54148. }
  54149. if (this._fallbackTextureUsed) {
  54150. return true;
  54151. }
  54152. if (this._fragment.fragmentElement !== undefined) {
  54153. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  54154. }
  54155. else {
  54156. shaders = { vertex: "procedural", fragment: this._fragment };
  54157. }
  54158. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  54159. _this.releaseInternalTexture();
  54160. if (_this._fallbackTexture) {
  54161. _this._texture = _this._fallbackTexture._texture;
  54162. if (_this._texture) {
  54163. _this._texture.incrementReferences();
  54164. }
  54165. }
  54166. _this._fallbackTextureUsed = true;
  54167. });
  54168. return this._effect.isReady();
  54169. };
  54170. ProceduralTexture.prototype.resetRefreshCounter = function () {
  54171. this._currentRefreshId = -1;
  54172. };
  54173. ProceduralTexture.prototype.setFragment = function (fragment) {
  54174. this._fragment = fragment;
  54175. };
  54176. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  54177. get: function () {
  54178. return this._refreshRate;
  54179. },
  54180. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54181. set: function (value) {
  54182. this._refreshRate = value;
  54183. this.resetRefreshCounter();
  54184. },
  54185. enumerable: true,
  54186. configurable: true
  54187. });
  54188. ProceduralTexture.prototype._shouldRender = function () {
  54189. if (!this.isEnabled || !this.isReady() || !this._texture) {
  54190. return false;
  54191. }
  54192. if (this._fallbackTextureUsed) {
  54193. return false;
  54194. }
  54195. if (this._currentRefreshId === -1) {
  54196. this._currentRefreshId = 1;
  54197. return true;
  54198. }
  54199. if (this.refreshRate === this._currentRefreshId) {
  54200. this._currentRefreshId = 1;
  54201. return true;
  54202. }
  54203. this._currentRefreshId++;
  54204. return false;
  54205. };
  54206. ProceduralTexture.prototype.getRenderSize = function () {
  54207. return this._size;
  54208. };
  54209. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  54210. if (this._fallbackTextureUsed) {
  54211. return;
  54212. }
  54213. this.releaseInternalTexture();
  54214. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  54215. };
  54216. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  54217. if (this._uniforms.indexOf(uniformName) === -1) {
  54218. this._uniforms.push(uniformName);
  54219. }
  54220. };
  54221. ProceduralTexture.prototype.setTexture = function (name, texture) {
  54222. if (this._samplers.indexOf(name) === -1) {
  54223. this._samplers.push(name);
  54224. }
  54225. this._textures[name] = texture;
  54226. return this;
  54227. };
  54228. ProceduralTexture.prototype.setFloat = function (name, value) {
  54229. this._checkUniform(name);
  54230. this._floats[name] = value;
  54231. return this;
  54232. };
  54233. ProceduralTexture.prototype.setFloats = function (name, value) {
  54234. this._checkUniform(name);
  54235. this._floatsArrays[name] = value;
  54236. return this;
  54237. };
  54238. ProceduralTexture.prototype.setColor3 = function (name, value) {
  54239. this._checkUniform(name);
  54240. this._colors3[name] = value;
  54241. return this;
  54242. };
  54243. ProceduralTexture.prototype.setColor4 = function (name, value) {
  54244. this._checkUniform(name);
  54245. this._colors4[name] = value;
  54246. return this;
  54247. };
  54248. ProceduralTexture.prototype.setVector2 = function (name, value) {
  54249. this._checkUniform(name);
  54250. this._vectors2[name] = value;
  54251. return this;
  54252. };
  54253. ProceduralTexture.prototype.setVector3 = function (name, value) {
  54254. this._checkUniform(name);
  54255. this._vectors3[name] = value;
  54256. return this;
  54257. };
  54258. ProceduralTexture.prototype.setMatrix = function (name, value) {
  54259. this._checkUniform(name);
  54260. this._matrices[name] = value;
  54261. return this;
  54262. };
  54263. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54264. var scene = this.getScene();
  54265. if (!scene) {
  54266. return;
  54267. }
  54268. var engine = this._engine;
  54269. // Render
  54270. engine.enableEffect(this._effect);
  54271. engine.setState(false);
  54272. // Texture
  54273. for (var name in this._textures) {
  54274. this._effect.setTexture(name, this._textures[name]);
  54275. }
  54276. // Float
  54277. for (name in this._floats) {
  54278. this._effect.setFloat(name, this._floats[name]);
  54279. }
  54280. // Floats
  54281. for (name in this._floatsArrays) {
  54282. this._effect.setArray(name, this._floatsArrays[name]);
  54283. }
  54284. // Color3
  54285. for (name in this._colors3) {
  54286. this._effect.setColor3(name, this._colors3[name]);
  54287. }
  54288. // Color4
  54289. for (name in this._colors4) {
  54290. var color = this._colors4[name];
  54291. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54292. }
  54293. // Vector2
  54294. for (name in this._vectors2) {
  54295. this._effect.setVector2(name, this._vectors2[name]);
  54296. }
  54297. // Vector3
  54298. for (name in this._vectors3) {
  54299. this._effect.setVector3(name, this._vectors3[name]);
  54300. }
  54301. // Matrix
  54302. for (name in this._matrices) {
  54303. this._effect.setMatrix(name, this._matrices[name]);
  54304. }
  54305. if (!this._texture) {
  54306. return;
  54307. }
  54308. if (this.isCube) {
  54309. for (var face = 0; face < 6; face++) {
  54310. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  54311. // VBOs
  54312. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54313. this._effect.setFloat("face", face);
  54314. // Clear
  54315. engine.clear(scene.clearColor, true, true, true);
  54316. // Draw order
  54317. engine.draw(true, 0, 6);
  54318. // Mipmaps
  54319. if (face === 5) {
  54320. engine.generateMipMapsForCubemap(this._texture);
  54321. }
  54322. }
  54323. }
  54324. else {
  54325. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  54326. // VBOs
  54327. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54328. // Clear
  54329. engine.clear(scene.clearColor, true, true, true);
  54330. // Draw order
  54331. engine.draw(true, 0, 6);
  54332. }
  54333. // Unbind
  54334. engine.unBindFramebuffer(this._texture, this.isCube);
  54335. if (this.onGenerated) {
  54336. this.onGenerated();
  54337. }
  54338. };
  54339. ProceduralTexture.prototype.clone = function () {
  54340. var textureSize = this.getSize();
  54341. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  54342. // Base texture
  54343. newTexture.hasAlpha = this.hasAlpha;
  54344. newTexture.level = this.level;
  54345. // RenderTarget Texture
  54346. newTexture.coordinatesMode = this.coordinatesMode;
  54347. return newTexture;
  54348. };
  54349. ProceduralTexture.prototype.dispose = function () {
  54350. var scene = this.getScene();
  54351. if (!scene) {
  54352. return;
  54353. }
  54354. var index = scene._proceduralTextures.indexOf(this);
  54355. if (index >= 0) {
  54356. scene._proceduralTextures.splice(index, 1);
  54357. }
  54358. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54359. if (vertexBuffer) {
  54360. vertexBuffer.dispose();
  54361. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54362. }
  54363. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  54364. this._indexBuffer = null;
  54365. }
  54366. _super.prototype.dispose.call(this);
  54367. };
  54368. return ProceduralTexture;
  54369. }(BABYLON.Texture));
  54370. BABYLON.ProceduralTexture = ProceduralTexture;
  54371. })(BABYLON || (BABYLON = {}));
  54372. //# sourceMappingURL=babylon.proceduralTexture.js.map
  54373. var BABYLON;
  54374. (function (BABYLON) {
  54375. var CustomProceduralTexture = /** @class */ (function (_super) {
  54376. __extends(CustomProceduralTexture, _super);
  54377. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  54378. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  54379. _this._animate = true;
  54380. _this._time = 0;
  54381. _this._texturePath = texturePath;
  54382. //Try to load json
  54383. _this.loadJson(texturePath);
  54384. _this.refreshRate = 1;
  54385. return _this;
  54386. }
  54387. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  54388. var _this = this;
  54389. var noConfigFile = function () {
  54390. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  54391. try {
  54392. _this.setFragment(_this._texturePath);
  54393. }
  54394. catch (ex) {
  54395. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  54396. }
  54397. };
  54398. var configFileUrl = jsonUrl + "/config.json";
  54399. var xhr = new XMLHttpRequest();
  54400. xhr.open("GET", configFileUrl, true);
  54401. xhr.addEventListener("load", function () {
  54402. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54403. try {
  54404. _this._config = JSON.parse(xhr.response);
  54405. _this.updateShaderUniforms();
  54406. _this.updateTextures();
  54407. _this.setFragment(_this._texturePath + "/custom");
  54408. _this._animate = _this._config.animate;
  54409. _this.refreshRate = _this._config.refreshrate;
  54410. }
  54411. catch (ex) {
  54412. noConfigFile();
  54413. }
  54414. }
  54415. else {
  54416. noConfigFile();
  54417. }
  54418. }, false);
  54419. xhr.addEventListener("error", function () {
  54420. noConfigFile();
  54421. }, false);
  54422. try {
  54423. xhr.send();
  54424. }
  54425. catch (ex) {
  54426. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  54427. }
  54428. };
  54429. CustomProceduralTexture.prototype.isReady = function () {
  54430. if (!_super.prototype.isReady.call(this)) {
  54431. return false;
  54432. }
  54433. for (var name in this._textures) {
  54434. var texture = this._textures[name];
  54435. if (!texture.isReady()) {
  54436. return false;
  54437. }
  54438. }
  54439. return true;
  54440. };
  54441. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54442. var scene = this.getScene();
  54443. if (this._animate && scene) {
  54444. this._time += scene.getAnimationRatio() * 0.03;
  54445. this.updateShaderUniforms();
  54446. }
  54447. _super.prototype.render.call(this, useCameraPostProcess);
  54448. };
  54449. CustomProceduralTexture.prototype.updateTextures = function () {
  54450. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  54451. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  54452. }
  54453. };
  54454. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  54455. if (this._config) {
  54456. for (var j = 0; j < this._config.uniforms.length; j++) {
  54457. var uniform = this._config.uniforms[j];
  54458. switch (uniform.type) {
  54459. case "float":
  54460. this.setFloat(uniform.name, uniform.value);
  54461. break;
  54462. case "color3":
  54463. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  54464. break;
  54465. case "color4":
  54466. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  54467. break;
  54468. case "vector2":
  54469. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  54470. break;
  54471. case "vector3":
  54472. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  54473. break;
  54474. }
  54475. }
  54476. }
  54477. this.setFloat("time", this._time);
  54478. };
  54479. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  54480. get: function () {
  54481. return this._animate;
  54482. },
  54483. set: function (value) {
  54484. this._animate = value;
  54485. },
  54486. enumerable: true,
  54487. configurable: true
  54488. });
  54489. return CustomProceduralTexture;
  54490. }(BABYLON.ProceduralTexture));
  54491. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  54492. })(BABYLON || (BABYLON = {}));
  54493. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  54494. var BABYLON;
  54495. (function (BABYLON) {
  54496. var FreeCameraGamepadInput = /** @class */ (function () {
  54497. function FreeCameraGamepadInput() {
  54498. this.gamepadAngularSensibility = 200;
  54499. this.gamepadMoveSensibility = 40;
  54500. // private members
  54501. this._cameraTransform = BABYLON.Matrix.Identity();
  54502. this._deltaTransform = BABYLON.Vector3.Zero();
  54503. this._vector3 = BABYLON.Vector3.Zero();
  54504. this._vector2 = BABYLON.Vector2.Zero();
  54505. }
  54506. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54507. var _this = this;
  54508. var manager = this.camera.getScene().gamepadManager;
  54509. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54510. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54511. // prioritize XBOX gamepads.
  54512. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54513. _this.gamepad = gamepad;
  54514. }
  54515. }
  54516. });
  54517. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54518. if (_this.gamepad === gamepad) {
  54519. _this.gamepad = null;
  54520. }
  54521. });
  54522. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54523. };
  54524. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  54525. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54526. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54527. this.gamepad = null;
  54528. };
  54529. FreeCameraGamepadInput.prototype.checkInputs = function () {
  54530. if (this.gamepad && this.gamepad.leftStick) {
  54531. var camera = this.camera;
  54532. var LSValues = this.gamepad.leftStick;
  54533. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  54534. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54535. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  54536. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  54537. var RSValues = this.gamepad.rightStick;
  54538. if (RSValues) {
  54539. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  54540. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  54541. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  54542. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  54543. }
  54544. else {
  54545. RSValues = { x: 0, y: 0 };
  54546. }
  54547. if (!camera.rotationQuaternion) {
  54548. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  54549. }
  54550. else {
  54551. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  54552. }
  54553. var speed = camera._computeLocalCameraSpeed() * 50.0;
  54554. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  54555. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  54556. camera.cameraDirection.addInPlace(this._deltaTransform);
  54557. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  54558. camera.cameraRotation.addInPlace(this._vector2);
  54559. }
  54560. };
  54561. FreeCameraGamepadInput.prototype.getClassName = function () {
  54562. return "FreeCameraGamepadInput";
  54563. };
  54564. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  54565. return "gamepad";
  54566. };
  54567. __decorate([
  54568. BABYLON.serialize()
  54569. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  54570. __decorate([
  54571. BABYLON.serialize()
  54572. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54573. return FreeCameraGamepadInput;
  54574. }());
  54575. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  54576. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  54577. })(BABYLON || (BABYLON = {}));
  54578. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  54579. var BABYLON;
  54580. (function (BABYLON) {
  54581. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  54582. function ArcRotateCameraGamepadInput() {
  54583. this.gamepadRotationSensibility = 80;
  54584. this.gamepadMoveSensibility = 40;
  54585. }
  54586. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54587. var _this = this;
  54588. var manager = this.camera.getScene().gamepadManager;
  54589. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54590. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54591. // prioritize XBOX gamepads.
  54592. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54593. _this.gamepad = gamepad;
  54594. }
  54595. }
  54596. });
  54597. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54598. if (_this.gamepad === gamepad) {
  54599. _this.gamepad = null;
  54600. }
  54601. });
  54602. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54603. };
  54604. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  54605. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54606. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54607. this.gamepad = null;
  54608. };
  54609. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  54610. if (this.gamepad) {
  54611. var camera = this.camera;
  54612. var RSValues = this.gamepad.rightStick;
  54613. if (RSValues) {
  54614. if (RSValues.x != 0) {
  54615. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  54616. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  54617. camera.inertialAlphaOffset += normalizedRX;
  54618. }
  54619. }
  54620. if (RSValues.y != 0) {
  54621. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  54622. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  54623. camera.inertialBetaOffset += normalizedRY;
  54624. }
  54625. }
  54626. }
  54627. var LSValues = this.gamepad.leftStick;
  54628. if (LSValues && LSValues.y != 0) {
  54629. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54630. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  54631. this.camera.inertialRadiusOffset -= normalizedLY;
  54632. }
  54633. }
  54634. }
  54635. };
  54636. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  54637. return "ArcRotateCameraGamepadInput";
  54638. };
  54639. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  54640. return "gamepad";
  54641. };
  54642. __decorate([
  54643. BABYLON.serialize()
  54644. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  54645. __decorate([
  54646. BABYLON.serialize()
  54647. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54648. return ArcRotateCameraGamepadInput;
  54649. }());
  54650. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  54651. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  54652. })(BABYLON || (BABYLON = {}));
  54653. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  54654. var BABYLON;
  54655. (function (BABYLON) {
  54656. var GamepadManager = /** @class */ (function () {
  54657. function GamepadManager() {
  54658. var _this = this;
  54659. this._babylonGamepads = [];
  54660. this._oneGamepadConnected = false;
  54661. this._isMonitoring = false;
  54662. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  54663. if (!BABYLON.Tools.IsWindowObjectExist()) {
  54664. this._gamepadEventSupported = false;
  54665. }
  54666. else {
  54667. this._gamepadEventSupported = 'GamepadEvent' in window;
  54668. this._gamepadSupport = (navigator.getGamepads ||
  54669. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  54670. }
  54671. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  54672. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  54673. for (var i in _this._babylonGamepads) {
  54674. var gamepad = _this._babylonGamepads[i];
  54675. if (gamepad && gamepad._isConnected) {
  54676. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  54677. }
  54678. }
  54679. });
  54680. this._onGamepadConnectedEvent = function (evt) {
  54681. var gamepad = evt.gamepad;
  54682. if (gamepad.index in _this._babylonGamepads) {
  54683. if (_this._babylonGamepads[gamepad.index].isConnected) {
  54684. return;
  54685. }
  54686. }
  54687. var newGamepad;
  54688. if (_this._babylonGamepads[gamepad.index]) {
  54689. newGamepad = _this._babylonGamepads[gamepad.index];
  54690. newGamepad.browserGamepad = gamepad;
  54691. newGamepad._isConnected = true;
  54692. }
  54693. else {
  54694. newGamepad = _this._addNewGamepad(gamepad);
  54695. }
  54696. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54697. _this._startMonitoringGamepads();
  54698. };
  54699. this._onGamepadDisconnectedEvent = function (evt) {
  54700. var gamepad = evt.gamepad;
  54701. // Remove the gamepad from the list of gamepads to monitor.
  54702. for (var i in _this._babylonGamepads) {
  54703. if (_this._babylonGamepads[i].index === gamepad.index) {
  54704. var disconnectedGamepad = _this._babylonGamepads[i];
  54705. disconnectedGamepad._isConnected = false;
  54706. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  54707. break;
  54708. }
  54709. }
  54710. };
  54711. if (this._gamepadSupport) {
  54712. //first add already-connected gamepads
  54713. this._updateGamepadObjects();
  54714. if (this._babylonGamepads.length) {
  54715. this._startMonitoringGamepads();
  54716. }
  54717. // Checking if the gamepad connected event is supported (like in Firefox)
  54718. if (this._gamepadEventSupported) {
  54719. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54720. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  54721. }
  54722. else {
  54723. this._startMonitoringGamepads();
  54724. }
  54725. }
  54726. }
  54727. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  54728. get: function () {
  54729. return this._babylonGamepads;
  54730. },
  54731. enumerable: true,
  54732. configurable: true
  54733. });
  54734. GamepadManager.prototype.getGamepadByType = function (type) {
  54735. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  54736. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  54737. var gamepad = _a[_i];
  54738. if (gamepad && gamepad.type === type) {
  54739. return gamepad;
  54740. }
  54741. }
  54742. return null;
  54743. };
  54744. GamepadManager.prototype.dispose = function () {
  54745. if (this._gamepadEventSupported) {
  54746. if (this._onGamepadConnectedEvent) {
  54747. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  54748. }
  54749. if (this._onGamepadDisconnectedEvent) {
  54750. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  54751. }
  54752. this._onGamepadConnectedEvent = null;
  54753. this._onGamepadDisconnectedEvent = null;
  54754. }
  54755. this._babylonGamepads.forEach(function (gamepad) {
  54756. gamepad.dispose();
  54757. });
  54758. this.onGamepadConnectedObservable.clear();
  54759. this.onGamepadDisconnectedObservable.clear();
  54760. this._oneGamepadConnected = false;
  54761. this._stopMonitoringGamepads();
  54762. this._babylonGamepads = [];
  54763. };
  54764. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  54765. if (!this._oneGamepadConnected) {
  54766. this._oneGamepadConnected = true;
  54767. }
  54768. var newGamepad;
  54769. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  54770. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54771. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  54772. }
  54773. else if (gamepad.pose) {
  54774. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  54775. }
  54776. else {
  54777. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  54778. }
  54779. this._babylonGamepads[newGamepad.index] = newGamepad;
  54780. return newGamepad;
  54781. };
  54782. GamepadManager.prototype._startMonitoringGamepads = function () {
  54783. if (!this._isMonitoring) {
  54784. this._isMonitoring = true;
  54785. this._checkGamepadsStatus();
  54786. }
  54787. };
  54788. GamepadManager.prototype._stopMonitoringGamepads = function () {
  54789. this._isMonitoring = false;
  54790. };
  54791. GamepadManager.prototype._checkGamepadsStatus = function () {
  54792. var _this = this;
  54793. // Hack to be compatible Chrome
  54794. this._updateGamepadObjects();
  54795. for (var i in this._babylonGamepads) {
  54796. var gamepad = this._babylonGamepads[i];
  54797. if (!gamepad || !gamepad.isConnected) {
  54798. continue;
  54799. }
  54800. gamepad.update();
  54801. }
  54802. if (this._isMonitoring) {
  54803. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  54804. }
  54805. };
  54806. // This function is called only on Chrome, which does not properly support
  54807. // connection/disconnection events and forces you to recopy again the gamepad object
  54808. GamepadManager.prototype._updateGamepadObjects = function () {
  54809. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54810. for (var i = 0; i < gamepads.length; i++) {
  54811. if (gamepads[i]) {
  54812. if (!this._babylonGamepads[gamepads[i].index]) {
  54813. var newGamepad = this._addNewGamepad(gamepads[i]);
  54814. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54815. }
  54816. else {
  54817. // Forced to copy again this object for Chrome for unknown reason
  54818. this._babylonGamepads[i].browserGamepad = gamepads[i];
  54819. if (!this._babylonGamepads[i].isConnected) {
  54820. this._babylonGamepads[i]._isConnected = true;
  54821. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  54822. }
  54823. }
  54824. }
  54825. }
  54826. };
  54827. return GamepadManager;
  54828. }());
  54829. BABYLON.GamepadManager = GamepadManager;
  54830. })(BABYLON || (BABYLON = {}));
  54831. //# sourceMappingURL=babylon.gamepadManager.js.map
  54832. var BABYLON;
  54833. (function (BABYLON) {
  54834. var StickValues = /** @class */ (function () {
  54835. function StickValues(x, y) {
  54836. this.x = x;
  54837. this.y = y;
  54838. }
  54839. return StickValues;
  54840. }());
  54841. BABYLON.StickValues = StickValues;
  54842. var Gamepad = /** @class */ (function () {
  54843. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  54844. if (leftStickX === void 0) { leftStickX = 0; }
  54845. if (leftStickY === void 0) { leftStickY = 1; }
  54846. if (rightStickX === void 0) { rightStickX = 2; }
  54847. if (rightStickY === void 0) { rightStickY = 3; }
  54848. this.id = id;
  54849. this.index = index;
  54850. this.browserGamepad = browserGamepad;
  54851. this._isConnected = true;
  54852. this.type = Gamepad.GAMEPAD;
  54853. this._leftStickAxisX = leftStickX;
  54854. this._leftStickAxisY = leftStickY;
  54855. this._rightStickAxisX = rightStickX;
  54856. this._rightStickAxisY = rightStickY;
  54857. if (this.browserGamepad.axes.length >= 2) {
  54858. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  54859. }
  54860. if (this.browserGamepad.axes.length >= 4) {
  54861. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  54862. }
  54863. }
  54864. Object.defineProperty(Gamepad.prototype, "isConnected", {
  54865. get: function () {
  54866. return this._isConnected;
  54867. },
  54868. enumerable: true,
  54869. configurable: true
  54870. });
  54871. Gamepad.prototype.onleftstickchanged = function (callback) {
  54872. this._onleftstickchanged = callback;
  54873. };
  54874. Gamepad.prototype.onrightstickchanged = function (callback) {
  54875. this._onrightstickchanged = callback;
  54876. };
  54877. Object.defineProperty(Gamepad.prototype, "leftStick", {
  54878. get: function () {
  54879. return this._leftStick;
  54880. },
  54881. set: function (newValues) {
  54882. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  54883. this._onleftstickchanged(newValues);
  54884. }
  54885. this._leftStick = newValues;
  54886. },
  54887. enumerable: true,
  54888. configurable: true
  54889. });
  54890. Object.defineProperty(Gamepad.prototype, "rightStick", {
  54891. get: function () {
  54892. return this._rightStick;
  54893. },
  54894. set: function (newValues) {
  54895. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  54896. this._onrightstickchanged(newValues);
  54897. }
  54898. this._rightStick = newValues;
  54899. },
  54900. enumerable: true,
  54901. configurable: true
  54902. });
  54903. Gamepad.prototype.update = function () {
  54904. if (this._leftStick) {
  54905. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  54906. }
  54907. if (this._rightStick) {
  54908. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  54909. }
  54910. };
  54911. Gamepad.prototype.dispose = function () {
  54912. };
  54913. Gamepad.GAMEPAD = 0;
  54914. Gamepad.GENERIC = 1;
  54915. Gamepad.XBOX = 2;
  54916. Gamepad.POSE_ENABLED = 3;
  54917. return Gamepad;
  54918. }());
  54919. BABYLON.Gamepad = Gamepad;
  54920. var GenericPad = /** @class */ (function (_super) {
  54921. __extends(GenericPad, _super);
  54922. function GenericPad(id, index, browserGamepad) {
  54923. var _this = _super.call(this, id, index, browserGamepad) || this;
  54924. _this.onButtonDownObservable = new BABYLON.Observable();
  54925. _this.onButtonUpObservable = new BABYLON.Observable();
  54926. _this.type = Gamepad.GENERIC;
  54927. _this._buttons = new Array(browserGamepad.buttons.length);
  54928. return _this;
  54929. }
  54930. GenericPad.prototype.onbuttondown = function (callback) {
  54931. this._onbuttondown = callback;
  54932. };
  54933. GenericPad.prototype.onbuttonup = function (callback) {
  54934. this._onbuttonup = callback;
  54935. };
  54936. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  54937. if (newValue !== currentValue) {
  54938. if (newValue === 1) {
  54939. if (this._onbuttondown) {
  54940. this._onbuttondown(buttonIndex);
  54941. }
  54942. this.onButtonDownObservable.notifyObservers(buttonIndex);
  54943. }
  54944. if (newValue === 0) {
  54945. if (this._onbuttonup) {
  54946. this._onbuttonup(buttonIndex);
  54947. }
  54948. this.onButtonUpObservable.notifyObservers(buttonIndex);
  54949. }
  54950. }
  54951. return newValue;
  54952. };
  54953. GenericPad.prototype.update = function () {
  54954. _super.prototype.update.call(this);
  54955. for (var index = 0; index < this._buttons.length; index++) {
  54956. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  54957. }
  54958. };
  54959. return GenericPad;
  54960. }(Gamepad));
  54961. BABYLON.GenericPad = GenericPad;
  54962. })(BABYLON || (BABYLON = {}));
  54963. //# sourceMappingURL=babylon.gamepad.js.map
  54964. var BABYLON;
  54965. (function (BABYLON) {
  54966. var Xbox360Button;
  54967. (function (Xbox360Button) {
  54968. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  54969. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  54970. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  54971. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  54972. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  54973. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  54974. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  54975. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  54976. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  54977. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  54978. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  54979. var Xbox360Dpad;
  54980. (function (Xbox360Dpad) {
  54981. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  54982. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  54983. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  54984. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  54985. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  54986. var Xbox360Pad = /** @class */ (function (_super) {
  54987. __extends(Xbox360Pad, _super);
  54988. function Xbox360Pad(id, index, gamepad, xboxOne) {
  54989. if (xboxOne === void 0) { xboxOne = false; }
  54990. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  54991. _this._leftTrigger = 0;
  54992. _this._rightTrigger = 0;
  54993. _this.onButtonDownObservable = new BABYLON.Observable();
  54994. _this.onButtonUpObservable = new BABYLON.Observable();
  54995. _this.onPadDownObservable = new BABYLON.Observable();
  54996. _this.onPadUpObservable = new BABYLON.Observable();
  54997. _this._buttonA = 0;
  54998. _this._buttonB = 0;
  54999. _this._buttonX = 0;
  55000. _this._buttonY = 0;
  55001. _this._buttonBack = 0;
  55002. _this._buttonStart = 0;
  55003. _this._buttonLB = 0;
  55004. _this._buttonRB = 0;
  55005. _this._buttonLeftStick = 0;
  55006. _this._buttonRightStick = 0;
  55007. _this._dPadUp = 0;
  55008. _this._dPadDown = 0;
  55009. _this._dPadLeft = 0;
  55010. _this._dPadRight = 0;
  55011. _this._isXboxOnePad = false;
  55012. _this.type = BABYLON.Gamepad.XBOX;
  55013. _this._isXboxOnePad = xboxOne;
  55014. return _this;
  55015. }
  55016. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55017. this._onlefttriggerchanged = callback;
  55018. };
  55019. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55020. this._onrighttriggerchanged = callback;
  55021. };
  55022. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55023. get: function () {
  55024. return this._leftTrigger;
  55025. },
  55026. set: function (newValue) {
  55027. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55028. this._onlefttriggerchanged(newValue);
  55029. }
  55030. this._leftTrigger = newValue;
  55031. },
  55032. enumerable: true,
  55033. configurable: true
  55034. });
  55035. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55036. get: function () {
  55037. return this._rightTrigger;
  55038. },
  55039. set: function (newValue) {
  55040. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55041. this._onrighttriggerchanged(newValue);
  55042. }
  55043. this._rightTrigger = newValue;
  55044. },
  55045. enumerable: true,
  55046. configurable: true
  55047. });
  55048. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55049. this._onbuttondown = callback;
  55050. };
  55051. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55052. this._onbuttonup = callback;
  55053. };
  55054. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55055. this._ondpaddown = callback;
  55056. };
  55057. Xbox360Pad.prototype.ondpadup = function (callback) {
  55058. this._ondpadup = callback;
  55059. };
  55060. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55061. if (newValue !== currentValue) {
  55062. if (newValue === 1) {
  55063. if (this._onbuttondown) {
  55064. this._onbuttondown(buttonType);
  55065. }
  55066. this.onButtonDownObservable.notifyObservers(buttonType);
  55067. }
  55068. if (newValue === 0) {
  55069. if (this._onbuttonup) {
  55070. this._onbuttonup(buttonType);
  55071. }
  55072. this.onButtonUpObservable.notifyObservers(buttonType);
  55073. }
  55074. }
  55075. return newValue;
  55076. };
  55077. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55078. if (newValue !== currentValue) {
  55079. if (newValue === 1) {
  55080. if (this._ondpaddown) {
  55081. this._ondpaddown(buttonType);
  55082. }
  55083. this.onPadDownObservable.notifyObservers(buttonType);
  55084. }
  55085. if (newValue === 0) {
  55086. if (this._ondpadup) {
  55087. this._ondpadup(buttonType);
  55088. }
  55089. this.onPadUpObservable.notifyObservers(buttonType);
  55090. }
  55091. }
  55092. return newValue;
  55093. };
  55094. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55095. get: function () {
  55096. return this._buttonA;
  55097. },
  55098. set: function (value) {
  55099. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55100. },
  55101. enumerable: true,
  55102. configurable: true
  55103. });
  55104. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55105. get: function () {
  55106. return this._buttonB;
  55107. },
  55108. set: function (value) {
  55109. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55110. },
  55111. enumerable: true,
  55112. configurable: true
  55113. });
  55114. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55115. get: function () {
  55116. return this._buttonX;
  55117. },
  55118. set: function (value) {
  55119. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55120. },
  55121. enumerable: true,
  55122. configurable: true
  55123. });
  55124. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55125. get: function () {
  55126. return this._buttonY;
  55127. },
  55128. set: function (value) {
  55129. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55130. },
  55131. enumerable: true,
  55132. configurable: true
  55133. });
  55134. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55135. get: function () {
  55136. return this._buttonStart;
  55137. },
  55138. set: function (value) {
  55139. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55140. },
  55141. enumerable: true,
  55142. configurable: true
  55143. });
  55144. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55145. get: function () {
  55146. return this._buttonBack;
  55147. },
  55148. set: function (value) {
  55149. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55150. },
  55151. enumerable: true,
  55152. configurable: true
  55153. });
  55154. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55155. get: function () {
  55156. return this._buttonLB;
  55157. },
  55158. set: function (value) {
  55159. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55160. },
  55161. enumerable: true,
  55162. configurable: true
  55163. });
  55164. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55165. get: function () {
  55166. return this._buttonRB;
  55167. },
  55168. set: function (value) {
  55169. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55170. },
  55171. enumerable: true,
  55172. configurable: true
  55173. });
  55174. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55175. get: function () {
  55176. return this._buttonLeftStick;
  55177. },
  55178. set: function (value) {
  55179. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55180. },
  55181. enumerable: true,
  55182. configurable: true
  55183. });
  55184. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55185. get: function () {
  55186. return this._buttonRightStick;
  55187. },
  55188. set: function (value) {
  55189. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55190. },
  55191. enumerable: true,
  55192. configurable: true
  55193. });
  55194. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55195. get: function () {
  55196. return this._dPadUp;
  55197. },
  55198. set: function (value) {
  55199. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55200. },
  55201. enumerable: true,
  55202. configurable: true
  55203. });
  55204. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55205. get: function () {
  55206. return this._dPadDown;
  55207. },
  55208. set: function (value) {
  55209. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55210. },
  55211. enumerable: true,
  55212. configurable: true
  55213. });
  55214. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55215. get: function () {
  55216. return this._dPadLeft;
  55217. },
  55218. set: function (value) {
  55219. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55220. },
  55221. enumerable: true,
  55222. configurable: true
  55223. });
  55224. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55225. get: function () {
  55226. return this._dPadRight;
  55227. },
  55228. set: function (value) {
  55229. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55230. },
  55231. enumerable: true,
  55232. configurable: true
  55233. });
  55234. Xbox360Pad.prototype.update = function () {
  55235. _super.prototype.update.call(this);
  55236. if (this._isXboxOnePad) {
  55237. this.buttonA = this.browserGamepad.buttons[0].value;
  55238. this.buttonB = this.browserGamepad.buttons[1].value;
  55239. this.buttonX = this.browserGamepad.buttons[2].value;
  55240. this.buttonY = this.browserGamepad.buttons[3].value;
  55241. this.buttonLB = this.browserGamepad.buttons[4].value;
  55242. this.buttonRB = this.browserGamepad.buttons[5].value;
  55243. this.leftTrigger = this.browserGamepad.axes[2];
  55244. this.rightTrigger = this.browserGamepad.axes[5];
  55245. this.buttonBack = this.browserGamepad.buttons[9].value;
  55246. this.buttonStart = this.browserGamepad.buttons[8].value;
  55247. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  55248. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  55249. this.dPadUp = this.browserGamepad.buttons[11].value;
  55250. this.dPadDown = this.browserGamepad.buttons[12].value;
  55251. this.dPadLeft = this.browserGamepad.buttons[13].value;
  55252. this.dPadRight = this.browserGamepad.buttons[14].value;
  55253. }
  55254. else {
  55255. this.buttonA = this.browserGamepad.buttons[0].value;
  55256. this.buttonB = this.browserGamepad.buttons[1].value;
  55257. this.buttonX = this.browserGamepad.buttons[2].value;
  55258. this.buttonY = this.browserGamepad.buttons[3].value;
  55259. this.buttonLB = this.browserGamepad.buttons[4].value;
  55260. this.buttonRB = this.browserGamepad.buttons[5].value;
  55261. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55262. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55263. this.buttonBack = this.browserGamepad.buttons[8].value;
  55264. this.buttonStart = this.browserGamepad.buttons[9].value;
  55265. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55266. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55267. this.dPadUp = this.browserGamepad.buttons[12].value;
  55268. this.dPadDown = this.browserGamepad.buttons[13].value;
  55269. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55270. this.dPadRight = this.browserGamepad.buttons[15].value;
  55271. }
  55272. };
  55273. return Xbox360Pad;
  55274. }(BABYLON.Gamepad));
  55275. BABYLON.Xbox360Pad = Xbox360Pad;
  55276. })(BABYLON || (BABYLON = {}));
  55277. //# sourceMappingURL=babylon.xboxGamepad.js.map
  55278. var BABYLON;
  55279. (function (BABYLON) {
  55280. var PoseEnabledControllerType;
  55281. (function (PoseEnabledControllerType) {
  55282. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  55283. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  55284. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  55285. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  55286. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  55287. var PoseEnabledControllerHelper = /** @class */ (function () {
  55288. function PoseEnabledControllerHelper() {
  55289. }
  55290. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  55291. // Oculus Touch
  55292. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  55293. return new BABYLON.OculusTouchController(vrGamepad);
  55294. }
  55295. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  55296. return new BABYLON.WindowsMotionController(vrGamepad);
  55297. }
  55298. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  55299. return new BABYLON.ViveController(vrGamepad);
  55300. }
  55301. else {
  55302. return new BABYLON.GenericController(vrGamepad);
  55303. }
  55304. };
  55305. return PoseEnabledControllerHelper;
  55306. }());
  55307. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  55308. var PoseEnabledController = /** @class */ (function (_super) {
  55309. __extends(PoseEnabledController, _super);
  55310. function PoseEnabledController(browserGamepad) {
  55311. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  55312. _this.deviceScaleFactor = 1;
  55313. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  55314. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  55315. _this.controllerType = PoseEnabledControllerType.GENERIC;
  55316. _this.position = BABYLON.Vector3.Zero();
  55317. _this.rotationQuaternion = new BABYLON.Quaternion();
  55318. _this.devicePosition = BABYLON.Vector3.Zero();
  55319. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  55320. _this._calculatedPosition = BABYLON.Vector3.Zero();
  55321. _this._calculatedRotation = new BABYLON.Quaternion();
  55322. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  55323. return _this;
  55324. }
  55325. PoseEnabledController.prototype.update = function () {
  55326. _super.prototype.update.call(this);
  55327. var pose = this.browserGamepad.pose;
  55328. this.updateFromDevice(pose);
  55329. if (this._mesh) {
  55330. this._mesh.position.copyFrom(this._calculatedPosition);
  55331. if (this._mesh.rotationQuaternion) {
  55332. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  55333. }
  55334. }
  55335. };
  55336. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  55337. if (poseData) {
  55338. this.rawPose = poseData;
  55339. if (poseData.position) {
  55340. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  55341. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  55342. this.devicePosition.z *= -1;
  55343. }
  55344. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  55345. this._calculatedPosition.addInPlace(this.position);
  55346. }
  55347. var pose = this.rawPose;
  55348. if (poseData.orientation && pose.orientation) {
  55349. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  55350. if (this._mesh) {
  55351. if (this._mesh.getScene().useRightHandedSystem) {
  55352. this.deviceRotationQuaternion.z *= -1;
  55353. this.deviceRotationQuaternion.w *= -1;
  55354. }
  55355. else {
  55356. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  55357. }
  55358. }
  55359. // if the camera is set, rotate to the camera's rotation
  55360. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  55361. }
  55362. }
  55363. };
  55364. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  55365. if (this._mesh) {
  55366. this._mesh.parent = null;
  55367. }
  55368. this._mesh = mesh;
  55369. if (this._poseControlledCamera) {
  55370. this._mesh.parent = this._poseControlledCamera;
  55371. }
  55372. if (!this._mesh.rotationQuaternion) {
  55373. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  55374. }
  55375. };
  55376. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  55377. this._poseControlledCamera = camera;
  55378. if (this._mesh) {
  55379. this._mesh.parent = this._poseControlledCamera;
  55380. }
  55381. };
  55382. PoseEnabledController.prototype.dispose = function () {
  55383. if (this._mesh) {
  55384. this._mesh.dispose();
  55385. }
  55386. this._mesh = null;
  55387. _super.prototype.dispose.call(this);
  55388. };
  55389. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  55390. get: function () {
  55391. return this._mesh;
  55392. },
  55393. enumerable: true,
  55394. configurable: true
  55395. });
  55396. PoseEnabledController.prototype.getForwardRay = function (length) {
  55397. if (length === void 0) { length = 100; }
  55398. if (!this.mesh) {
  55399. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  55400. }
  55401. var m = this.mesh.getWorldMatrix();
  55402. var origin = m.getTranslation();
  55403. var forward = new BABYLON.Vector3(0, 0, -1);
  55404. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55405. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55406. return new BABYLON.Ray(origin, direction, length);
  55407. };
  55408. return PoseEnabledController;
  55409. }(BABYLON.Gamepad));
  55410. BABYLON.PoseEnabledController = PoseEnabledController;
  55411. })(BABYLON || (BABYLON = {}));
  55412. //# sourceMappingURL=babylon.poseEnabledController.js.map
  55413. var BABYLON;
  55414. (function (BABYLON) {
  55415. var WebVRController = /** @class */ (function (_super) {
  55416. __extends(WebVRController, _super);
  55417. function WebVRController(vrGamepad) {
  55418. var _this = _super.call(this, vrGamepad) || this;
  55419. // Observables
  55420. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  55421. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  55422. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  55423. _this.onPadStateChangedObservable = new BABYLON.Observable();
  55424. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  55425. _this.pad = { x: 0, y: 0 };
  55426. // avoid GC, store state in a tmp object
  55427. _this._changes = {
  55428. pressChanged: false,
  55429. touchChanged: false,
  55430. valueChanged: false,
  55431. changed: false
  55432. };
  55433. _this._buttons = new Array(vrGamepad.buttons.length);
  55434. _this.hand = vrGamepad.hand;
  55435. return _this;
  55436. }
  55437. WebVRController.prototype.onButtonStateChange = function (callback) {
  55438. this._onButtonStateChange = callback;
  55439. };
  55440. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  55441. get: function () {
  55442. return this._defaultModel;
  55443. },
  55444. enumerable: true,
  55445. configurable: true
  55446. });
  55447. WebVRController.prototype.update = function () {
  55448. _super.prototype.update.call(this);
  55449. for (var index = 0; index < this._buttons.length; index++) {
  55450. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  55451. }
  55452. ;
  55453. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  55454. this.pad.x = this.leftStick.x;
  55455. this.pad.y = this.leftStick.y;
  55456. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  55457. }
  55458. };
  55459. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  55460. if (!newState) {
  55461. newState = {
  55462. pressed: false,
  55463. touched: false,
  55464. value: 0
  55465. };
  55466. }
  55467. if (!currentState) {
  55468. this._buttons[buttonIndex] = {
  55469. pressed: newState.pressed,
  55470. touched: newState.touched,
  55471. value: newState.value
  55472. };
  55473. return;
  55474. }
  55475. this._checkChanges(newState, currentState);
  55476. if (this._changes.changed) {
  55477. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  55478. this.handleButtonChange(buttonIndex, newState, this._changes);
  55479. }
  55480. this._buttons[buttonIndex].pressed = newState.pressed;
  55481. this._buttons[buttonIndex].touched = newState.touched;
  55482. // oculus triggers are never 0, thou not touched.
  55483. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  55484. };
  55485. WebVRController.prototype._checkChanges = function (newState, currentState) {
  55486. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  55487. this._changes.touchChanged = newState.touched !== currentState.touched;
  55488. this._changes.valueChanged = newState.value !== currentState.value;
  55489. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  55490. return this._changes;
  55491. };
  55492. WebVRController.prototype.dispose = function () {
  55493. _super.prototype.dispose.call(this);
  55494. this.onTriggerStateChangedObservable.clear();
  55495. this.onMainButtonStateChangedObservable.clear();
  55496. this.onSecondaryButtonStateChangedObservable.clear();
  55497. this.onPadStateChangedObservable.clear();
  55498. this.onPadValuesChangedObservable.clear();
  55499. };
  55500. return WebVRController;
  55501. }(BABYLON.PoseEnabledController));
  55502. BABYLON.WebVRController = WebVRController;
  55503. })(BABYLON || (BABYLON = {}));
  55504. //# sourceMappingURL=babylon.webVRController.js.map
  55505. var BABYLON;
  55506. (function (BABYLON) {
  55507. var OculusTouchController = /** @class */ (function (_super) {
  55508. __extends(OculusTouchController, _super);
  55509. function OculusTouchController(vrGamepad) {
  55510. var _this = _super.call(this, vrGamepad) || this;
  55511. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  55512. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  55513. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  55514. return _this;
  55515. }
  55516. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55517. var _this = this;
  55518. var meshName;
  55519. // Hand
  55520. if (this.hand === 'left') {
  55521. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  55522. }
  55523. else {
  55524. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  55525. }
  55526. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  55527. /*
  55528. Parent Mesh name: oculus_touch_left
  55529. - body
  55530. - trigger
  55531. - thumbstick
  55532. - grip
  55533. - button_y
  55534. - button_x
  55535. - button_enter
  55536. */
  55537. _this._defaultModel = newMeshes[1];
  55538. _this.attachToMesh(_this._defaultModel);
  55539. if (meshLoaded) {
  55540. meshLoaded(_this._defaultModel);
  55541. }
  55542. });
  55543. };
  55544. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  55545. // helper getters for left and right hand.
  55546. get: function () {
  55547. if (this.hand === 'right') {
  55548. return this.onMainButtonStateChangedObservable;
  55549. }
  55550. else {
  55551. throw new Error('No A button on left hand');
  55552. }
  55553. },
  55554. enumerable: true,
  55555. configurable: true
  55556. });
  55557. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  55558. get: function () {
  55559. if (this.hand === 'right') {
  55560. return this.onSecondaryButtonStateChangedObservable;
  55561. }
  55562. else {
  55563. throw new Error('No B button on left hand');
  55564. }
  55565. },
  55566. enumerable: true,
  55567. configurable: true
  55568. });
  55569. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  55570. get: function () {
  55571. if (this.hand === 'left') {
  55572. return this.onMainButtonStateChangedObservable;
  55573. }
  55574. else {
  55575. throw new Error('No X button on right hand');
  55576. }
  55577. },
  55578. enumerable: true,
  55579. configurable: true
  55580. });
  55581. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  55582. get: function () {
  55583. if (this.hand === 'left') {
  55584. return this.onSecondaryButtonStateChangedObservable;
  55585. }
  55586. else {
  55587. throw new Error('No Y button on right hand');
  55588. }
  55589. },
  55590. enumerable: true,
  55591. configurable: true
  55592. });
  55593. /*
  55594. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  55595. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  55596. 2) secondary trigger (same)
  55597. 3) A (right) X (left), touch, pressed = value
  55598. 4) B / Y
  55599. 5) thumb rest
  55600. */
  55601. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55602. var notifyObject = state; //{ state: state, changes: changes };
  55603. var triggerDirection = this.hand === 'right' ? -1 : 1;
  55604. switch (buttonIdx) {
  55605. case 0:
  55606. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55607. return;
  55608. case 1:// index trigger
  55609. if (this._defaultModel) {
  55610. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  55611. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  55612. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  55613. }
  55614. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55615. return;
  55616. case 2:// secondary trigger
  55617. if (this._defaultModel) {
  55618. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  55619. }
  55620. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  55621. return;
  55622. case 3:
  55623. if (this._defaultModel) {
  55624. if (notifyObject.pressed) {
  55625. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  55626. }
  55627. else {
  55628. (this._defaultModel.getChildren()[1]).position.y = 0;
  55629. }
  55630. }
  55631. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55632. return;
  55633. case 4:
  55634. if (this._defaultModel) {
  55635. if (notifyObject.pressed) {
  55636. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55637. }
  55638. else {
  55639. (this._defaultModel.getChildren()[2]).position.y = 0;
  55640. }
  55641. }
  55642. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55643. return;
  55644. case 5:
  55645. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  55646. return;
  55647. }
  55648. };
  55649. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  55650. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  55651. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  55652. return OculusTouchController;
  55653. }(BABYLON.WebVRController));
  55654. BABYLON.OculusTouchController = OculusTouchController;
  55655. })(BABYLON || (BABYLON = {}));
  55656. //# sourceMappingURL=babylon.oculusTouchController.js.map
  55657. var BABYLON;
  55658. (function (BABYLON) {
  55659. var ViveController = /** @class */ (function (_super) {
  55660. __extends(ViveController, _super);
  55661. function ViveController(vrGamepad) {
  55662. var _this = _super.call(this, vrGamepad) || this;
  55663. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  55664. return _this;
  55665. }
  55666. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55667. var _this = this;
  55668. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  55669. /*
  55670. Parent Mesh name: ViveWand
  55671. - body
  55672. - r_gripper
  55673. - l_gripper
  55674. - menu_button
  55675. - system_button
  55676. - trackpad
  55677. - trigger
  55678. - LED
  55679. */
  55680. _this._defaultModel = newMeshes[1];
  55681. _this.attachToMesh(_this._defaultModel);
  55682. if (meshLoaded) {
  55683. meshLoaded(_this._defaultModel);
  55684. }
  55685. });
  55686. };
  55687. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  55688. get: function () {
  55689. return this.onMainButtonStateChangedObservable;
  55690. },
  55691. enumerable: true,
  55692. configurable: true
  55693. });
  55694. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  55695. get: function () {
  55696. return this.onMainButtonStateChangedObservable;
  55697. },
  55698. enumerable: true,
  55699. configurable: true
  55700. });
  55701. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  55702. get: function () {
  55703. return this.onSecondaryButtonStateChangedObservable;
  55704. },
  55705. enumerable: true,
  55706. configurable: true
  55707. });
  55708. /**
  55709. * Vive mapping:
  55710. * 0: touchpad
  55711. * 1: trigger
  55712. * 2: left AND right buttons
  55713. * 3: menu button
  55714. */
  55715. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55716. var notifyObject = state; //{ state: state, changes: changes };
  55717. switch (buttonIdx) {
  55718. case 0:
  55719. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55720. return;
  55721. case 1:// index trigger
  55722. if (this._defaultModel) {
  55723. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  55724. }
  55725. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55726. return;
  55727. case 2:// left AND right button
  55728. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55729. return;
  55730. case 3:
  55731. if (this._defaultModel) {
  55732. if (notifyObject.pressed) {
  55733. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55734. }
  55735. else {
  55736. (this._defaultModel.getChildren()[2]).position.y = 0;
  55737. }
  55738. }
  55739. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55740. return;
  55741. }
  55742. };
  55743. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  55744. ViveController.MODEL_FILENAME = 'wand.babylon';
  55745. return ViveController;
  55746. }(BABYLON.WebVRController));
  55747. BABYLON.ViveController = ViveController;
  55748. })(BABYLON || (BABYLON = {}));
  55749. //# sourceMappingURL=babylon.viveController.js.map
  55750. var BABYLON;
  55751. (function (BABYLON) {
  55752. var GenericController = /** @class */ (function (_super) {
  55753. __extends(GenericController, _super);
  55754. function GenericController(vrGamepad) {
  55755. return _super.call(this, vrGamepad) || this;
  55756. }
  55757. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55758. var _this = this;
  55759. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  55760. _this._defaultModel = newMeshes[1];
  55761. _this.attachToMesh(_this._defaultModel);
  55762. if (meshLoaded) {
  55763. meshLoaded(_this._defaultModel);
  55764. }
  55765. });
  55766. };
  55767. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55768. console.log("Button id: " + buttonIdx + "state: ");
  55769. console.dir(state);
  55770. };
  55771. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  55772. GenericController.MODEL_FILENAME = 'generic.babylon';
  55773. return GenericController;
  55774. }(BABYLON.WebVRController));
  55775. BABYLON.GenericController = GenericController;
  55776. })(BABYLON || (BABYLON = {}));
  55777. //# sourceMappingURL=babylon.genericController.js.map
  55778. var BABYLON;
  55779. (function (BABYLON) {
  55780. var LoadedMeshInfo = /** @class */ (function () {
  55781. function LoadedMeshInfo() {
  55782. this.buttonMeshes = {};
  55783. this.axisMeshes = {};
  55784. }
  55785. return LoadedMeshInfo;
  55786. }());
  55787. var WindowsMotionController = /** @class */ (function (_super) {
  55788. __extends(WindowsMotionController, _super);
  55789. function WindowsMotionController(vrGamepad) {
  55790. var _this = _super.call(this, vrGamepad) || this;
  55791. _this._mapping = {
  55792. // Semantic button names
  55793. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  55794. // A mapping of the button name to glTF model node name
  55795. // that should be transformed by button value.
  55796. buttonMeshNames: {
  55797. 'trigger': 'SELECT',
  55798. 'menu': 'MENU',
  55799. 'grip': 'GRASP',
  55800. 'thumbstick': 'THUMBSTICK_PRESS',
  55801. 'trackpad': 'TOUCHPAD_PRESS'
  55802. },
  55803. // This mapping is used to translate from the Motion Controller to Babylon semantics
  55804. buttonObservableNames: {
  55805. 'trigger': 'onTriggerStateChangedObservable',
  55806. 'menu': 'onSecondaryButtonStateChangedObservable',
  55807. 'grip': 'onMainButtonStateChangedObservable',
  55808. 'thumbstick': 'onPadStateChangedObservable',
  55809. 'trackpad': 'onTrackpadChangedObservable'
  55810. },
  55811. // A mapping of the axis name to glTF model node name
  55812. // that should be transformed by axis value.
  55813. // This array mirrors the browserGamepad.axes array, such that
  55814. // the mesh corresponding to axis 0 is in this array index 0.
  55815. axisMeshNames: [
  55816. 'THUMBSTICK_X',
  55817. 'THUMBSTICK_Y',
  55818. 'TOUCHPAD_TOUCH_X',
  55819. 'TOUCHPAD_TOUCH_Y'
  55820. ],
  55821. pointingPoseMeshName: 'POINTING_POSE'
  55822. };
  55823. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  55824. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  55825. _this._loadedMeshInfo = null;
  55826. return _this;
  55827. }
  55828. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  55829. get: function () {
  55830. return this.onTriggerStateChangedObservable;
  55831. },
  55832. enumerable: true,
  55833. configurable: true
  55834. });
  55835. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  55836. get: function () {
  55837. return this.onSecondaryButtonStateChangedObservable;
  55838. },
  55839. enumerable: true,
  55840. configurable: true
  55841. });
  55842. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  55843. get: function () {
  55844. return this.onMainButtonStateChangedObservable;
  55845. },
  55846. enumerable: true,
  55847. configurable: true
  55848. });
  55849. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  55850. get: function () {
  55851. return this.onPadStateChangedObservable;
  55852. },
  55853. enumerable: true,
  55854. configurable: true
  55855. });
  55856. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  55857. get: function () {
  55858. return this.onTrackpadChangedObservable;
  55859. },
  55860. enumerable: true,
  55861. configurable: true
  55862. });
  55863. /**
  55864. * Called once per frame by the engine.
  55865. */
  55866. WindowsMotionController.prototype.update = function () {
  55867. _super.prototype.update.call(this);
  55868. // Only need to animate axes if there is a loaded mesh
  55869. if (this._loadedMeshInfo) {
  55870. if (this.browserGamepad.axes) {
  55871. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  55872. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  55873. }
  55874. }
  55875. }
  55876. };
  55877. /**
  55878. * Called once for each button that changed state since the last frame
  55879. * @param buttonIdx Which button index changed
  55880. * @param state New state of the button
  55881. * @param changes Which properties on the state changed since last frame
  55882. */
  55883. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55884. var buttonName = this._mapping.buttons[buttonIdx];
  55885. if (!buttonName) {
  55886. return;
  55887. }
  55888. // Only emit events for buttons that we know how to map from index to name
  55889. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  55890. if (observable) {
  55891. observable.notifyObservers(state);
  55892. }
  55893. this.lerpButtonTransform(buttonName, state.value);
  55894. };
  55895. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  55896. // If there is no loaded mesh, there is nothing to transform.
  55897. if (!this._loadedMeshInfo) {
  55898. return;
  55899. }
  55900. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  55901. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  55902. return;
  55903. }
  55904. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  55905. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  55906. };
  55907. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  55908. if (!this._loadedMeshInfo) {
  55909. return;
  55910. }
  55911. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  55912. if (!meshInfo) {
  55913. return;
  55914. }
  55915. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  55916. return;
  55917. }
  55918. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  55919. var lerpValue = axisValue * 0.5 + 0.5;
  55920. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  55921. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  55922. };
  55923. /**
  55924. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  55925. * @param scene scene in which to add meshes
  55926. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  55927. */
  55928. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  55929. var _this = this;
  55930. if (forceDefault === void 0) { forceDefault = false; }
  55931. var path;
  55932. var filename;
  55933. // Checking if GLB loader is present
  55934. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  55935. // Determine the device specific folder based on the ID suffix
  55936. var device = 'default';
  55937. if (this.id && !forceDefault) {
  55938. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  55939. device = ((match && match[0]) || device);
  55940. }
  55941. // Hand
  55942. if (this.hand === 'left') {
  55943. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  55944. }
  55945. else {
  55946. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  55947. }
  55948. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  55949. }
  55950. else {
  55951. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  55952. path = BABYLON.GenericController.MODEL_BASE_URL;
  55953. filename = BABYLON.GenericController.MODEL_FILENAME;
  55954. }
  55955. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  55956. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  55957. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  55958. if (!_this._loadedMeshInfo) {
  55959. return;
  55960. }
  55961. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  55962. _this.attachToMesh(_this._defaultModel);
  55963. if (meshLoaded) {
  55964. meshLoaded(_this._defaultModel);
  55965. }
  55966. }, null, function (scene, message) {
  55967. BABYLON.Tools.Log(message);
  55968. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  55969. if (!forceDefault) {
  55970. _this.initControllerMesh(scene, meshLoaded, true);
  55971. }
  55972. });
  55973. };
  55974. /**
  55975. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  55976. * can be transformed by button presses and axes values, based on this._mapping.
  55977. *
  55978. * @param scene scene in which the meshes exist
  55979. * @param meshes list of meshes that make up the controller model to process
  55980. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  55981. */
  55982. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  55983. var loadedMeshInfo = null;
  55984. // Create a new mesh to contain the glTF hierarchy
  55985. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  55986. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  55987. var childMesh = null;
  55988. for (var i = 0; i < meshes.length; i++) {
  55989. var mesh = meshes[i];
  55990. if (!mesh.parent) {
  55991. // Exclude controller meshes from picking results
  55992. mesh.isPickable = false;
  55993. // Handle root node, attach to the new parentMesh
  55994. childMesh = mesh;
  55995. break;
  55996. }
  55997. }
  55998. if (childMesh) {
  55999. childMesh.setParent(parentMesh);
  56000. // Create our mesh info. Note that this method will always return non-null.
  56001. loadedMeshInfo = this.createMeshInfo(parentMesh);
  56002. }
  56003. else {
  56004. BABYLON.Tools.Warn('Could not find root node in model file.');
  56005. }
  56006. return loadedMeshInfo;
  56007. };
  56008. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  56009. var loadedMeshInfo = new LoadedMeshInfo();
  56010. var i;
  56011. loadedMeshInfo.rootNode = rootNode;
  56012. // Reset the caches
  56013. loadedMeshInfo.buttonMeshes = {};
  56014. loadedMeshInfo.axisMeshes = {};
  56015. // Button Meshes
  56016. for (i = 0; i < this._mapping.buttons.length; i++) {
  56017. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56018. if (!buttonMeshName) {
  56019. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56020. continue;
  56021. }
  56022. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56023. if (!buttonMesh) {
  56024. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56025. continue;
  56026. }
  56027. var buttonMeshInfo = {
  56028. index: i,
  56029. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56030. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56031. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56032. };
  56033. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56034. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56035. }
  56036. else {
  56037. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56038. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56039. '(VALUE: ' + !!buttonMeshInfo.value +
  56040. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56041. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56042. ')');
  56043. }
  56044. }
  56045. // Axis Meshes
  56046. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56047. var axisMeshName = this._mapping.axisMeshNames[i];
  56048. if (!axisMeshName) {
  56049. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56050. continue;
  56051. }
  56052. var axisMesh = getChildByName(rootNode, axisMeshName);
  56053. if (!axisMesh) {
  56054. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56055. continue;
  56056. }
  56057. var axisMeshInfo = {
  56058. index: i,
  56059. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56060. min: getImmediateChildByName(axisMesh, 'MIN'),
  56061. max: getImmediateChildByName(axisMesh, 'MAX')
  56062. };
  56063. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  56064. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  56065. }
  56066. else {
  56067. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  56068. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  56069. '(VALUE: ' + !!axisMeshInfo.value +
  56070. ', MIN: ' + !!axisMeshInfo.min +
  56071. ', MAX:' + !!axisMeshInfo.max +
  56072. ')');
  56073. }
  56074. }
  56075. // Pointing Ray
  56076. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  56077. if (!loadedMeshInfo.pointingPoseNode) {
  56078. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  56079. }
  56080. return loadedMeshInfo;
  56081. // Look through all children recursively. This will return null if no mesh exists with the given name.
  56082. function getChildByName(node, name) {
  56083. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  56084. }
  56085. // Look through only immediate children. This will return null if no mesh exists with the given name.
  56086. function getImmediateChildByName(node, name) {
  56087. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  56088. }
  56089. };
  56090. WindowsMotionController.prototype.getForwardRay = function (length) {
  56091. if (length === void 0) { length = 100; }
  56092. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  56093. return _super.prototype.getForwardRay.call(this, length);
  56094. }
  56095. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  56096. var origin = m.getTranslation();
  56097. var forward = new BABYLON.Vector3(0, 0, -1);
  56098. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56099. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56100. return new BABYLON.Ray(origin, direction, length);
  56101. };
  56102. WindowsMotionController.prototype.dispose = function () {
  56103. _super.prototype.dispose.call(this);
  56104. this.onTrackpadChangedObservable.clear();
  56105. };
  56106. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  56107. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  56108. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  56109. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  56110. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  56111. return WindowsMotionController;
  56112. }(BABYLON.WebVRController));
  56113. BABYLON.WindowsMotionController = WindowsMotionController;
  56114. })(BABYLON || (BABYLON = {}));
  56115. //# sourceMappingURL=babylon.windowsMotionController.js.map
  56116. var BABYLON;
  56117. (function (BABYLON) {
  56118. var FollowCamera = /** @class */ (function (_super) {
  56119. __extends(FollowCamera, _super);
  56120. function FollowCamera(name, position, scene, lockedTarget) {
  56121. if (lockedTarget === void 0) { lockedTarget = null; }
  56122. var _this = _super.call(this, name, position, scene) || this;
  56123. _this.radius = 12;
  56124. _this.rotationOffset = 0;
  56125. _this.heightOffset = 4;
  56126. _this.cameraAcceleration = 0.05;
  56127. _this.maxCameraSpeed = 20;
  56128. _this.lockedTarget = lockedTarget;
  56129. return _this;
  56130. }
  56131. FollowCamera.prototype.getRadians = function (degrees) {
  56132. return degrees * Math.PI / 180;
  56133. };
  56134. FollowCamera.prototype.follow = function (cameraTarget) {
  56135. if (!cameraTarget)
  56136. return;
  56137. var yRotation;
  56138. if (cameraTarget.rotationQuaternion) {
  56139. var rotMatrix = new BABYLON.Matrix();
  56140. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  56141. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  56142. }
  56143. else {
  56144. yRotation = cameraTarget.rotation.y;
  56145. }
  56146. var radians = this.getRadians(this.rotationOffset) + yRotation;
  56147. var targetPosition = cameraTarget.getAbsolutePosition();
  56148. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  56149. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  56150. var dx = targetX - this.position.x;
  56151. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  56152. var dz = (targetZ) - this.position.z;
  56153. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  56154. var vy = dy * this.cameraAcceleration;
  56155. var vz = dz * this.cameraAcceleration * 2;
  56156. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  56157. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56158. }
  56159. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  56160. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56161. }
  56162. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  56163. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56164. }
  56165. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  56166. this.setTarget(targetPosition);
  56167. };
  56168. FollowCamera.prototype._checkInputs = function () {
  56169. _super.prototype._checkInputs.call(this);
  56170. if (this.lockedTarget) {
  56171. this.follow(this.lockedTarget);
  56172. }
  56173. };
  56174. FollowCamera.prototype.getClassName = function () {
  56175. return "FollowCamera";
  56176. };
  56177. __decorate([
  56178. BABYLON.serialize()
  56179. ], FollowCamera.prototype, "radius", void 0);
  56180. __decorate([
  56181. BABYLON.serialize()
  56182. ], FollowCamera.prototype, "rotationOffset", void 0);
  56183. __decorate([
  56184. BABYLON.serialize()
  56185. ], FollowCamera.prototype, "heightOffset", void 0);
  56186. __decorate([
  56187. BABYLON.serialize()
  56188. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  56189. __decorate([
  56190. BABYLON.serialize()
  56191. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  56192. __decorate([
  56193. BABYLON.serializeAsMeshReference("lockedTargetId")
  56194. ], FollowCamera.prototype, "lockedTarget", void 0);
  56195. return FollowCamera;
  56196. }(BABYLON.TargetCamera));
  56197. BABYLON.FollowCamera = FollowCamera;
  56198. var ArcFollowCamera = /** @class */ (function (_super) {
  56199. __extends(ArcFollowCamera, _super);
  56200. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  56201. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  56202. _this.alpha = alpha;
  56203. _this.beta = beta;
  56204. _this.radius = radius;
  56205. _this.target = target;
  56206. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  56207. _this.follow();
  56208. return _this;
  56209. }
  56210. ArcFollowCamera.prototype.follow = function () {
  56211. if (!this.target) {
  56212. return;
  56213. }
  56214. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  56215. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  56216. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  56217. var targetPosition = this.target.getAbsolutePosition();
  56218. this.position = targetPosition.add(this._cartesianCoordinates);
  56219. this.setTarget(targetPosition);
  56220. };
  56221. ArcFollowCamera.prototype._checkInputs = function () {
  56222. _super.prototype._checkInputs.call(this);
  56223. this.follow();
  56224. };
  56225. ArcFollowCamera.prototype.getClassName = function () {
  56226. return "ArcFollowCamera";
  56227. };
  56228. return ArcFollowCamera;
  56229. }(BABYLON.TargetCamera));
  56230. BABYLON.ArcFollowCamera = ArcFollowCamera;
  56231. })(BABYLON || (BABYLON = {}));
  56232. //# sourceMappingURL=babylon.followCamera.js.map
  56233. var BABYLON;
  56234. (function (BABYLON) {
  56235. // We're mainly based on the logic defined into the FreeCamera code
  56236. var UniversalCamera = /** @class */ (function (_super) {
  56237. __extends(UniversalCamera, _super);
  56238. //-- end properties for backward compatibility for inputs
  56239. function UniversalCamera(name, position, scene) {
  56240. var _this = _super.call(this, name, position, scene) || this;
  56241. _this.inputs.addGamepad();
  56242. return _this;
  56243. }
  56244. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  56245. //-- Begin properties for backward compatibility for inputs
  56246. get: function () {
  56247. var gamepad = this.inputs.attached["gamepad"];
  56248. if (gamepad)
  56249. return gamepad.gamepadAngularSensibility;
  56250. return 0;
  56251. },
  56252. set: function (value) {
  56253. var gamepad = this.inputs.attached["gamepad"];
  56254. if (gamepad)
  56255. gamepad.gamepadAngularSensibility = value;
  56256. },
  56257. enumerable: true,
  56258. configurable: true
  56259. });
  56260. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  56261. get: function () {
  56262. var gamepad = this.inputs.attached["gamepad"];
  56263. if (gamepad)
  56264. return gamepad.gamepadMoveSensibility;
  56265. return 0;
  56266. },
  56267. set: function (value) {
  56268. var gamepad = this.inputs.attached["gamepad"];
  56269. if (gamepad)
  56270. gamepad.gamepadMoveSensibility = value;
  56271. },
  56272. enumerable: true,
  56273. configurable: true
  56274. });
  56275. UniversalCamera.prototype.getClassName = function () {
  56276. return "UniversalCamera";
  56277. };
  56278. return UniversalCamera;
  56279. }(BABYLON.TouchCamera));
  56280. BABYLON.UniversalCamera = UniversalCamera;
  56281. })(BABYLON || (BABYLON = {}));
  56282. //# sourceMappingURL=babylon.universalCamera.js.map
  56283. var BABYLON;
  56284. (function (BABYLON) {
  56285. // We're mainly based on the logic defined into the FreeCamera code
  56286. var GamepadCamera = /** @class */ (function (_super) {
  56287. __extends(GamepadCamera, _super);
  56288. //-- end properties for backward compatibility for inputs
  56289. function GamepadCamera(name, position, scene) {
  56290. return _super.call(this, name, position, scene) || this;
  56291. }
  56292. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  56293. //-- Begin properties for backward compatibility for inputs
  56294. get: function () {
  56295. var gamepad = this.inputs.attached["gamepad"];
  56296. if (gamepad)
  56297. return gamepad.gamepadAngularSensibility;
  56298. return 0;
  56299. },
  56300. set: function (value) {
  56301. var gamepad = this.inputs.attached["gamepad"];
  56302. if (gamepad)
  56303. gamepad.gamepadAngularSensibility = value;
  56304. },
  56305. enumerable: true,
  56306. configurable: true
  56307. });
  56308. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  56309. get: function () {
  56310. var gamepad = this.inputs.attached["gamepad"];
  56311. if (gamepad)
  56312. return gamepad.gamepadMoveSensibility;
  56313. return 0;
  56314. },
  56315. set: function (value) {
  56316. var gamepad = this.inputs.attached["gamepad"];
  56317. if (gamepad)
  56318. gamepad.gamepadMoveSensibility = value;
  56319. },
  56320. enumerable: true,
  56321. configurable: true
  56322. });
  56323. GamepadCamera.prototype.getClassName = function () {
  56324. return "GamepadCamera";
  56325. };
  56326. return GamepadCamera;
  56327. }(BABYLON.UniversalCamera));
  56328. BABYLON.GamepadCamera = GamepadCamera;
  56329. })(BABYLON || (BABYLON = {}));
  56330. //# sourceMappingURL=babylon.gamepadCamera.js.map
  56331. var BABYLON;
  56332. (function (BABYLON) {
  56333. var PostProcessRenderPipelineManager = /** @class */ (function () {
  56334. function PostProcessRenderPipelineManager() {
  56335. this._renderPipelines = {};
  56336. }
  56337. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  56338. this._renderPipelines[renderPipeline._name] = renderPipeline;
  56339. };
  56340. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  56341. if (unique === void 0) { unique = false; }
  56342. var renderPipeline = this._renderPipelines[renderPipelineName];
  56343. if (!renderPipeline) {
  56344. return;
  56345. }
  56346. renderPipeline._attachCameras(cameras, unique);
  56347. };
  56348. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  56349. var renderPipeline = this._renderPipelines[renderPipelineName];
  56350. if (!renderPipeline) {
  56351. return;
  56352. }
  56353. renderPipeline._detachCameras(cameras);
  56354. };
  56355. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56356. var renderPipeline = this._renderPipelines[renderPipelineName];
  56357. if (!renderPipeline) {
  56358. return;
  56359. }
  56360. renderPipeline._enableEffect(renderEffectName, cameras);
  56361. };
  56362. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56363. var renderPipeline = this._renderPipelines[renderPipelineName];
  56364. if (!renderPipeline) {
  56365. return;
  56366. }
  56367. renderPipeline._disableEffect(renderEffectName, cameras);
  56368. };
  56369. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  56370. var renderPipeline = this._renderPipelines[renderPipelineName];
  56371. if (!renderPipeline) {
  56372. return;
  56373. }
  56374. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  56375. };
  56376. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  56377. var renderPipeline = this._renderPipelines[renderPipelineName];
  56378. if (!renderPipeline) {
  56379. return;
  56380. }
  56381. renderPipeline._disableDisplayOnlyPass(cameras);
  56382. };
  56383. PostProcessRenderPipelineManager.prototype.update = function () {
  56384. for (var renderPipelineName in this._renderPipelines) {
  56385. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56386. var pipeline = this._renderPipelines[renderPipelineName];
  56387. if (!pipeline.isSupported) {
  56388. pipeline.dispose();
  56389. delete this._renderPipelines[renderPipelineName];
  56390. }
  56391. else {
  56392. pipeline._update();
  56393. }
  56394. }
  56395. }
  56396. };
  56397. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  56398. for (var renderPipelineName in this._renderPipelines) {
  56399. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56400. var pipeline = this._renderPipelines[renderPipelineName];
  56401. pipeline._rebuild();
  56402. }
  56403. }
  56404. };
  56405. PostProcessRenderPipelineManager.prototype.dispose = function () {
  56406. for (var renderPipelineName in this._renderPipelines) {
  56407. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56408. var pipeline = this._renderPipelines[renderPipelineName];
  56409. pipeline.dispose();
  56410. }
  56411. }
  56412. };
  56413. return PostProcessRenderPipelineManager;
  56414. }());
  56415. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  56416. })(BABYLON || (BABYLON = {}));
  56417. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  56418. var BABYLON;
  56419. (function (BABYLON) {
  56420. var PostProcessRenderPass = /** @class */ (function () {
  56421. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  56422. this._refCount = 0;
  56423. this._name = name;
  56424. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  56425. this.setRenderList(renderList);
  56426. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  56427. this._renderTexture.onAfterRenderObservable.add(afterRender);
  56428. this._scene = scene;
  56429. this._renderList = renderList;
  56430. }
  56431. // private
  56432. PostProcessRenderPass.prototype._incRefCount = function () {
  56433. if (this._refCount === 0) {
  56434. this._scene.customRenderTargets.push(this._renderTexture);
  56435. }
  56436. return ++this._refCount;
  56437. };
  56438. PostProcessRenderPass.prototype._decRefCount = function () {
  56439. this._refCount--;
  56440. if (this._refCount <= 0) {
  56441. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  56442. }
  56443. return this._refCount;
  56444. };
  56445. PostProcessRenderPass.prototype._update = function () {
  56446. this.setRenderList(this._renderList);
  56447. };
  56448. // public
  56449. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  56450. this._renderTexture.renderList = renderList;
  56451. };
  56452. PostProcessRenderPass.prototype.getRenderTexture = function () {
  56453. return this._renderTexture;
  56454. };
  56455. return PostProcessRenderPass;
  56456. }());
  56457. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  56458. })(BABYLON || (BABYLON = {}));
  56459. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  56460. var BABYLON;
  56461. (function (BABYLON) {
  56462. var PostProcessRenderEffect = /** @class */ (function () {
  56463. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  56464. this._engine = engine;
  56465. this._name = name;
  56466. this._singleInstance = singleInstance || true;
  56467. this._getPostProcess = getPostProcess;
  56468. this._cameras = {};
  56469. this._indicesForCamera = {};
  56470. this._postProcesses = {};
  56471. this._renderPasses = {};
  56472. this._renderEffectAsPasses = {};
  56473. }
  56474. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  56475. get: function () {
  56476. for (var index in this._postProcesses) {
  56477. if (!this._postProcesses[index].isSupported) {
  56478. return false;
  56479. }
  56480. }
  56481. return true;
  56482. },
  56483. enumerable: true,
  56484. configurable: true
  56485. });
  56486. PostProcessRenderEffect.prototype._update = function () {
  56487. for (var renderPassName in this._renderPasses) {
  56488. this._renderPasses[renderPassName]._update();
  56489. }
  56490. };
  56491. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  56492. this._renderPasses[renderPass._name] = renderPass;
  56493. this._linkParameters();
  56494. };
  56495. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  56496. delete this._renderPasses[renderPass._name];
  56497. this._linkParameters();
  56498. };
  56499. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  56500. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  56501. this._linkParameters();
  56502. };
  56503. PostProcessRenderEffect.prototype.getPass = function (passName) {
  56504. for (var renderPassName in this._renderPasses) {
  56505. if (renderPassName === passName) {
  56506. return this._renderPasses[passName];
  56507. }
  56508. }
  56509. return null;
  56510. };
  56511. PostProcessRenderEffect.prototype.emptyPasses = function () {
  56512. this._renderPasses = {};
  56513. this._linkParameters();
  56514. };
  56515. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  56516. var cameraKey;
  56517. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56518. if (!cams) {
  56519. return;
  56520. }
  56521. for (var i = 0; i < cams.length; i++) {
  56522. var camera = cams[i];
  56523. var cameraName = camera.name;
  56524. if (this._singleInstance) {
  56525. cameraKey = 0;
  56526. }
  56527. else {
  56528. cameraKey = cameraName;
  56529. }
  56530. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  56531. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  56532. if (!this._indicesForCamera[cameraName]) {
  56533. this._indicesForCamera[cameraName] = [];
  56534. }
  56535. this._indicesForCamera[cameraName].push(index);
  56536. if (!this._cameras[cameraName]) {
  56537. this._cameras[cameraName] = camera;
  56538. }
  56539. for (var passName in this._renderPasses) {
  56540. this._renderPasses[passName]._incRefCount();
  56541. }
  56542. }
  56543. this._linkParameters();
  56544. };
  56545. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  56546. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56547. if (!cams) {
  56548. return;
  56549. }
  56550. for (var i = 0; i < cams.length; i++) {
  56551. var camera = cams[i];
  56552. var cameraName = camera.name;
  56553. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56554. if (this._cameras[cameraName]) {
  56555. //this._indicesForCamera.splice(index, 1);
  56556. this._cameras[cameraName] = null;
  56557. }
  56558. for (var passName in this._renderPasses) {
  56559. this._renderPasses[passName]._decRefCount();
  56560. }
  56561. }
  56562. };
  56563. PostProcessRenderEffect.prototype._enable = function (cameras) {
  56564. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56565. if (!cams) {
  56566. return;
  56567. }
  56568. for (var i = 0; i < cams.length; i++) {
  56569. var camera = cams[i];
  56570. var cameraName = camera.name;
  56571. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  56572. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  56573. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  56574. }
  56575. }
  56576. for (var passName in this._renderPasses) {
  56577. this._renderPasses[passName]._incRefCount();
  56578. }
  56579. }
  56580. };
  56581. PostProcessRenderEffect.prototype._disable = function (cameras) {
  56582. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56583. if (!cams) {
  56584. return;
  56585. }
  56586. for (var i = 0; i < cams.length; i++) {
  56587. var camera = cams[i];
  56588. var cameraName = camera.Name;
  56589. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56590. for (var passName in this._renderPasses) {
  56591. this._renderPasses[passName]._decRefCount();
  56592. }
  56593. }
  56594. };
  56595. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  56596. if (this._singleInstance) {
  56597. return this._postProcesses[0];
  56598. }
  56599. else {
  56600. if (!camera) {
  56601. return null;
  56602. }
  56603. return this._postProcesses[camera.name];
  56604. }
  56605. };
  56606. PostProcessRenderEffect.prototype._linkParameters = function () {
  56607. var _this = this;
  56608. for (var index in this._postProcesses) {
  56609. if (this.applyParameters) {
  56610. this.applyParameters(this._postProcesses[index]);
  56611. }
  56612. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  56613. _this._linkTextures(effect);
  56614. });
  56615. }
  56616. };
  56617. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  56618. for (var renderPassName in this._renderPasses) {
  56619. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  56620. }
  56621. for (var renderEffectName in this._renderEffectAsPasses) {
  56622. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  56623. }
  56624. };
  56625. return PostProcessRenderEffect;
  56626. }());
  56627. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  56628. })(BABYLON || (BABYLON = {}));
  56629. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  56630. var BABYLON;
  56631. (function (BABYLON) {
  56632. var PostProcessRenderPipeline = /** @class */ (function () {
  56633. function PostProcessRenderPipeline(engine, name) {
  56634. this._engine = engine;
  56635. this._name = name;
  56636. this._renderEffects = {};
  56637. this._renderEffectsForIsolatedPass = new Array();
  56638. this._cameras = [];
  56639. }
  56640. PostProcessRenderPipeline.prototype.getClassName = function () {
  56641. return "PostProcessRenderPipeline";
  56642. };
  56643. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  56644. get: function () {
  56645. for (var renderEffectName in this._renderEffects) {
  56646. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56647. if (!this._renderEffects[renderEffectName].isSupported) {
  56648. return false;
  56649. }
  56650. }
  56651. }
  56652. return true;
  56653. },
  56654. enumerable: true,
  56655. configurable: true
  56656. });
  56657. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  56658. this._renderEffects[renderEffect._name] = renderEffect;
  56659. };
  56660. // private
  56661. PostProcessRenderPipeline.prototype._rebuild = function () {
  56662. };
  56663. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  56664. var renderEffects = this._renderEffects[renderEffectName];
  56665. if (!renderEffects) {
  56666. return;
  56667. }
  56668. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56669. };
  56670. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  56671. var renderEffects = this._renderEffects[renderEffectName];
  56672. if (!renderEffects) {
  56673. return;
  56674. }
  56675. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56676. };
  56677. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  56678. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56679. if (!cams) {
  56680. return;
  56681. }
  56682. var indicesToDelete = [];
  56683. var i;
  56684. for (i = 0; i < cams.length; i++) {
  56685. var camera = cams[i];
  56686. var cameraName = camera.name;
  56687. if (this._cameras.indexOf(camera) === -1) {
  56688. this._cameras[cameraName] = camera;
  56689. }
  56690. else if (unique) {
  56691. indicesToDelete.push(i);
  56692. }
  56693. }
  56694. for (i = 0; i < indicesToDelete.length; i++) {
  56695. cameras.splice(indicesToDelete[i], 1);
  56696. }
  56697. for (var renderEffectName in this._renderEffects) {
  56698. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56699. this._renderEffects[renderEffectName]._attachCameras(cams);
  56700. }
  56701. }
  56702. };
  56703. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  56704. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56705. if (!cams) {
  56706. return;
  56707. }
  56708. for (var renderEffectName in this._renderEffects) {
  56709. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56710. this._renderEffects[renderEffectName]._detachCameras(cams);
  56711. }
  56712. }
  56713. for (var i = 0; i < cams.length; i++) {
  56714. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  56715. }
  56716. };
  56717. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  56718. var _this = this;
  56719. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56720. if (!cams) {
  56721. return;
  56722. }
  56723. var pass = null;
  56724. var renderEffectName;
  56725. for (renderEffectName in this._renderEffects) {
  56726. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56727. pass = this._renderEffects[renderEffectName].getPass(passName);
  56728. if (pass != null) {
  56729. break;
  56730. }
  56731. }
  56732. }
  56733. if (pass === null) {
  56734. return;
  56735. }
  56736. for (renderEffectName in this._renderEffects) {
  56737. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56738. this._renderEffects[renderEffectName]._disable(cams);
  56739. }
  56740. }
  56741. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  56742. for (var i = 0; i < cams.length; i++) {
  56743. var camera = cams[i];
  56744. var cameraName = camera.name;
  56745. 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); });
  56746. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  56747. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  56748. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  56749. }
  56750. };
  56751. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  56752. var _this = this;
  56753. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56754. if (!cams) {
  56755. return;
  56756. }
  56757. for (var i = 0; i < cams.length; i++) {
  56758. var camera = cams[i];
  56759. var cameraName = camera.name;
  56760. 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); });
  56761. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  56762. }
  56763. for (var renderEffectName in this._renderEffects) {
  56764. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56765. this._renderEffects[renderEffectName]._enable(cams);
  56766. }
  56767. }
  56768. };
  56769. PostProcessRenderPipeline.prototype._update = function () {
  56770. for (var renderEffectName in this._renderEffects) {
  56771. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56772. this._renderEffects[renderEffectName]._update();
  56773. }
  56774. }
  56775. for (var i = 0; i < this._cameras.length; i++) {
  56776. var cameraName = this._cameras[i].name;
  56777. if (this._renderEffectsForIsolatedPass[cameraName]) {
  56778. this._renderEffectsForIsolatedPass[cameraName]._update();
  56779. }
  56780. }
  56781. };
  56782. PostProcessRenderPipeline.prototype._reset = function () {
  56783. this._renderEffects = {};
  56784. this._renderEffectsForIsolatedPass = new Array();
  56785. };
  56786. PostProcessRenderPipeline.prototype.dispose = function () {
  56787. // Must be implemented by children
  56788. };
  56789. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  56790. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  56791. __decorate([
  56792. BABYLON.serialize()
  56793. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  56794. return PostProcessRenderPipeline;
  56795. }());
  56796. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  56797. })(BABYLON || (BABYLON = {}));
  56798. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  56799. var BABYLON;
  56800. (function (BABYLON) {
  56801. var DepthRenderer = /** @class */ (function () {
  56802. function DepthRenderer(scene, type) {
  56803. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  56804. var _this = this;
  56805. this._scene = scene;
  56806. var engine = scene.getEngine();
  56807. // Render target
  56808. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  56809. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56810. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56811. this._depthMap.refreshRate = 1;
  56812. this._depthMap.renderParticles = false;
  56813. this._depthMap.renderList = null;
  56814. // set default depth value to 1.0 (far away)
  56815. this._depthMap.onClearObservable.add(function (engine) {
  56816. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56817. });
  56818. // Custom render function
  56819. var renderSubMesh = function (subMesh) {
  56820. var mesh = subMesh.getRenderingMesh();
  56821. var scene = _this._scene;
  56822. var engine = scene.getEngine();
  56823. var material = subMesh.getMaterial();
  56824. if (!material) {
  56825. return;
  56826. }
  56827. // Culling
  56828. engine.setState(material.backFaceCulling);
  56829. // Managing instances
  56830. var batch = mesh._getInstancesRenderList(subMesh._id);
  56831. if (batch.mustReturn) {
  56832. return;
  56833. }
  56834. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  56835. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  56836. engine.enableEffect(_this._effect);
  56837. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  56838. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  56839. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  56840. // Alpha test
  56841. if (material && material.needAlphaTesting()) {
  56842. var alphaTexture = material.getAlphaTestTexture();
  56843. if (alphaTexture) {
  56844. _this._effect.setTexture("diffuseSampler", alphaTexture);
  56845. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56846. }
  56847. }
  56848. // Bones
  56849. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  56850. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  56851. }
  56852. // Draw
  56853. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  56854. }
  56855. };
  56856. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56857. var index;
  56858. if (depthOnlySubMeshes.length) {
  56859. engine.setColorWrite(false);
  56860. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56861. renderSubMesh(depthOnlySubMeshes.data[index]);
  56862. }
  56863. engine.setColorWrite(true);
  56864. }
  56865. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56866. renderSubMesh(opaqueSubMeshes.data[index]);
  56867. }
  56868. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56869. renderSubMesh(alphaTestSubMeshes.data[index]);
  56870. }
  56871. };
  56872. }
  56873. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  56874. var material = subMesh.getMaterial();
  56875. if (material.disableDepthWrite) {
  56876. return false;
  56877. }
  56878. var defines = [];
  56879. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56880. var mesh = subMesh.getMesh();
  56881. // Alpha test
  56882. if (material && material.needAlphaTesting()) {
  56883. defines.push("#define ALPHATEST");
  56884. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56885. attribs.push(BABYLON.VertexBuffer.UVKind);
  56886. defines.push("#define UV1");
  56887. }
  56888. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56889. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56890. defines.push("#define UV2");
  56891. }
  56892. }
  56893. // Bones
  56894. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56895. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56896. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56897. if (mesh.numBoneInfluencers > 4) {
  56898. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56899. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56900. }
  56901. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56902. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  56903. }
  56904. else {
  56905. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56906. }
  56907. // Instances
  56908. if (useInstances) {
  56909. defines.push("#define INSTANCES");
  56910. attribs.push("world0");
  56911. attribs.push("world1");
  56912. attribs.push("world2");
  56913. attribs.push("world3");
  56914. }
  56915. // Get correct effect
  56916. var join = defines.join("\n");
  56917. if (this._cachedDefines !== join) {
  56918. this._cachedDefines = join;
  56919. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  56920. }
  56921. return this._effect.isReady();
  56922. };
  56923. DepthRenderer.prototype.getDepthMap = function () {
  56924. return this._depthMap;
  56925. };
  56926. // Methods
  56927. DepthRenderer.prototype.dispose = function () {
  56928. this._depthMap.dispose();
  56929. };
  56930. return DepthRenderer;
  56931. }());
  56932. BABYLON.DepthRenderer = DepthRenderer;
  56933. })(BABYLON || (BABYLON = {}));
  56934. //# sourceMappingURL=babylon.depthRenderer.js.map
  56935. var BABYLON;
  56936. (function (BABYLON) {
  56937. var SSAORenderingPipeline = /** @class */ (function (_super) {
  56938. __extends(SSAORenderingPipeline, _super);
  56939. /**
  56940. * @constructor
  56941. * @param {string} name - The rendering pipeline name
  56942. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56943. * @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 }
  56944. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56945. */
  56946. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  56947. var _this = _super.call(this, scene.getEngine(), name) || this;
  56948. // Members
  56949. /**
  56950. * The PassPostProcess id in the pipeline that contains the original scene color
  56951. * @type {string}
  56952. */
  56953. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  56954. /**
  56955. * The SSAO PostProcess id in the pipeline
  56956. * @type {string}
  56957. */
  56958. _this.SSAORenderEffect = "SSAORenderEffect";
  56959. /**
  56960. * The horizontal blur PostProcess id in the pipeline
  56961. * @type {string}
  56962. */
  56963. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  56964. /**
  56965. * The vertical blur PostProcess id in the pipeline
  56966. * @type {string}
  56967. */
  56968. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  56969. /**
  56970. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  56971. * @type {string}
  56972. */
  56973. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  56974. /**
  56975. * The output strength of the SSAO post-process. Default value is 1.0.
  56976. * @type {number}
  56977. */
  56978. _this.totalStrength = 1.0;
  56979. /**
  56980. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  56981. * @type {number}
  56982. */
  56983. _this.radius = 0.0001;
  56984. /**
  56985. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  56986. * Must not be equal to fallOff and superior to fallOff.
  56987. * Default value is 0.975
  56988. * @type {number}
  56989. */
  56990. _this.area = 0.0075;
  56991. /**
  56992. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  56993. * Must not be equal to area and inferior to area.
  56994. * Default value is 0.0
  56995. * @type {number}
  56996. */
  56997. _this.fallOff = 0.000001;
  56998. /**
  56999. * The base color of the SSAO post-process
  57000. * The final result is "base + ssao" between [0, 1]
  57001. * @type {number}
  57002. */
  57003. _this.base = 0.5;
  57004. _this._firstUpdate = true;
  57005. _this._scene = scene;
  57006. // Set up assets
  57007. _this._createRandomTexture();
  57008. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57009. var ssaoRatio = ratio.ssaoRatio || ratio;
  57010. var combineRatio = ratio.combineRatio || ratio;
  57011. _this._ratio = {
  57012. ssaoRatio: ssaoRatio,
  57013. combineRatio: combineRatio
  57014. };
  57015. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57016. _this._createSSAOPostProcess(ssaoRatio);
  57017. _this._createBlurPostProcess(ssaoRatio);
  57018. _this._createSSAOCombinePostProcess(combineRatio);
  57019. // Set up pipeline
  57020. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57021. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57022. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57023. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57024. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57025. // Finish
  57026. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57027. if (cameras)
  57028. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57029. return _this;
  57030. }
  57031. // Public Methods
  57032. /**
  57033. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57034. */
  57035. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57036. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57037. for (var i = 0; i < this._scene.cameras.length; i++) {
  57038. var camera = this._scene.cameras[i];
  57039. this._originalColorPostProcess.dispose(camera);
  57040. this._ssaoPostProcess.dispose(camera);
  57041. this._blurHPostProcess.dispose(camera);
  57042. this._blurVPostProcess.dispose(camera);
  57043. this._ssaoCombinePostProcess.dispose(camera);
  57044. }
  57045. this._randomTexture.dispose();
  57046. if (disableDepthRender)
  57047. this._scene.disableDepthRenderer();
  57048. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57049. _super.prototype.dispose.call(this);
  57050. };
  57051. // Private Methods
  57052. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57053. var _this = this;
  57054. /*
  57055. var samplerOffsets = [
  57056. -8.0, -6.0, -4.0, -2.0,
  57057. 0.0,
  57058. 2.0, 4.0, 6.0, 8.0
  57059. ];
  57060. */
  57061. var samplerOffsets = new Array();
  57062. for (var i = -8; i < 8; i++) {
  57063. samplerOffsets.push(i * 2);
  57064. }
  57065. 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");
  57066. this._blurHPostProcess.onApply = function (effect) {
  57067. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57068. effect.setTexture("depthSampler", _this._depthTexture);
  57069. if (_this._firstUpdate) {
  57070. effect.setArray("samplerOffsets", samplerOffsets);
  57071. }
  57072. };
  57073. 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");
  57074. this._blurVPostProcess.onApply = function (effect) {
  57075. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57076. effect.setTexture("depthSampler", _this._depthTexture);
  57077. if (_this._firstUpdate) {
  57078. effect.setArray("samplerOffsets", samplerOffsets);
  57079. _this._firstUpdate = false;
  57080. }
  57081. };
  57082. };
  57083. SSAORenderingPipeline.prototype._rebuild = function () {
  57084. this._firstUpdate = true;
  57085. _super.prototype._rebuild.call(this);
  57086. };
  57087. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57088. var _this = this;
  57089. var numSamples = 16;
  57090. var sampleSphere = [
  57091. 0.5381, 0.1856, -0.4319,
  57092. 0.1379, 0.2486, 0.4430,
  57093. 0.3371, 0.5679, -0.0057,
  57094. -0.6999, -0.0451, -0.0019,
  57095. 0.0689, -0.1598, -0.8547,
  57096. 0.0560, 0.0069, -0.1843,
  57097. -0.0146, 0.1402, 0.0762,
  57098. 0.0100, -0.1924, -0.0344,
  57099. -0.3577, -0.5301, -0.4358,
  57100. -0.3169, 0.1063, 0.0158,
  57101. 0.0103, -0.5869, 0.0046,
  57102. -0.0897, -0.4940, 0.3287,
  57103. 0.7119, -0.0154, -0.0918,
  57104. -0.0533, 0.0596, -0.5411,
  57105. 0.0352, -0.0631, 0.5460,
  57106. -0.4776, 0.2847, -0.0271
  57107. ];
  57108. var samplesFactor = 1.0 / numSamples;
  57109. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  57110. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57111. "area", "fallOff", "base", "range", "viewport"
  57112. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57113. this._ssaoPostProcess.onApply = function (effect) {
  57114. if (_this._firstUpdate) {
  57115. effect.setArray3("sampleSphere", sampleSphere);
  57116. effect.setFloat("samplesFactor", samplesFactor);
  57117. effect.setFloat("randTextureTiles", 4.0);
  57118. }
  57119. effect.setFloat("totalStrength", _this.totalStrength);
  57120. effect.setFloat("radius", _this.radius);
  57121. effect.setFloat("area", _this.area);
  57122. effect.setFloat("fallOff", _this.fallOff);
  57123. effect.setFloat("base", _this.base);
  57124. effect.setTexture("textureSampler", _this._depthTexture);
  57125. effect.setTexture("randomSampler", _this._randomTexture);
  57126. };
  57127. };
  57128. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57129. var _this = this;
  57130. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57131. this._ssaoCombinePostProcess.onApply = function (effect) {
  57132. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57133. };
  57134. };
  57135. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  57136. var size = 512;
  57137. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57138. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57139. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57140. var context = this._randomTexture.getContext();
  57141. var rand = function (min, max) {
  57142. return Math.random() * (max - min) + min;
  57143. };
  57144. var randVector = BABYLON.Vector3.Zero();
  57145. for (var x = 0; x < size; x++) {
  57146. for (var y = 0; y < size; y++) {
  57147. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  57148. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  57149. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  57150. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57151. context.fillRect(x, y, 1, 1);
  57152. }
  57153. }
  57154. this._randomTexture.update(false);
  57155. };
  57156. __decorate([
  57157. BABYLON.serialize()
  57158. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  57159. __decorate([
  57160. BABYLON.serialize()
  57161. ], SSAORenderingPipeline.prototype, "radius", void 0);
  57162. __decorate([
  57163. BABYLON.serialize()
  57164. ], SSAORenderingPipeline.prototype, "area", void 0);
  57165. __decorate([
  57166. BABYLON.serialize()
  57167. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  57168. __decorate([
  57169. BABYLON.serialize()
  57170. ], SSAORenderingPipeline.prototype, "base", void 0);
  57171. __decorate([
  57172. BABYLON.serialize()
  57173. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  57174. return SSAORenderingPipeline;
  57175. }(BABYLON.PostProcessRenderPipeline));
  57176. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  57177. })(BABYLON || (BABYLON = {}));
  57178. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  57179. var BABYLON;
  57180. (function (BABYLON) {
  57181. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  57182. __extends(SSAO2RenderingPipeline, _super);
  57183. /**
  57184. * @constructor
  57185. * @param {string} name - The rendering pipeline name
  57186. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57187. * @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 }
  57188. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57189. */
  57190. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  57191. var _this = _super.call(this, scene.getEngine(), name) || this;
  57192. // Members
  57193. /**
  57194. * The PassPostProcess id in the pipeline that contains the original scene color
  57195. * @type {string}
  57196. */
  57197. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57198. /**
  57199. * The SSAO PostProcess id in the pipeline
  57200. * @type {string}
  57201. */
  57202. _this.SSAORenderEffect = "SSAORenderEffect";
  57203. /**
  57204. * The horizontal blur PostProcess id in the pipeline
  57205. * @type {string}
  57206. */
  57207. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57208. /**
  57209. * The vertical blur PostProcess id in the pipeline
  57210. * @type {string}
  57211. */
  57212. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57213. /**
  57214. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57215. * @type {string}
  57216. */
  57217. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57218. /**
  57219. * The output strength of the SSAO post-process. Default value is 1.0.
  57220. * @type {number}
  57221. */
  57222. _this.totalStrength = 1.0;
  57223. /**
  57224. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  57225. * @type {number}
  57226. */
  57227. _this.maxZ = 100.0;
  57228. /**
  57229. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  57230. * @type {number}
  57231. */
  57232. _this.minZAspect = 0.2;
  57233. /**
  57234. * Number of samples used for the SSAO calculations. Default value is 8
  57235. * @type {number}
  57236. */
  57237. _this._samples = 8;
  57238. /**
  57239. * Are we using bilateral blur ?
  57240. * @type {boolean}
  57241. */
  57242. _this._expensiveBlur = true;
  57243. /**
  57244. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  57245. * @type {number}
  57246. */
  57247. _this.radius = 2.0;
  57248. /**
  57249. * The base color of the SSAO post-process
  57250. * The final result is "base + ssao" between [0, 1]
  57251. * @type {number}
  57252. */
  57253. _this.base = 0.1;
  57254. _this._firstUpdate = true;
  57255. _this._scene = scene;
  57256. if (!_this.isSupported) {
  57257. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  57258. return _this;
  57259. }
  57260. var ssaoRatio = ratio.ssaoRatio || ratio;
  57261. var blurRatio = ratio.blurRatio || ratio;
  57262. _this._ratio = {
  57263. ssaoRatio: ssaoRatio,
  57264. blurRatio: blurRatio
  57265. };
  57266. // Set up assets
  57267. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  57268. _this._createRandomTexture();
  57269. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  57270. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  57271. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57272. _this._createSSAOPostProcess(1.0);
  57273. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  57274. _this._createSSAOCombinePostProcess(blurRatio);
  57275. // Set up pipeline
  57276. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57277. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57278. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57279. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57280. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57281. // Finish
  57282. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57283. if (cameras)
  57284. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57285. return _this;
  57286. }
  57287. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  57288. get: function () {
  57289. return this._samples;
  57290. },
  57291. set: function (n) {
  57292. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  57293. this._samples = n;
  57294. this._sampleSphere = this._generateHemisphere();
  57295. this._firstUpdate = true;
  57296. },
  57297. enumerable: true,
  57298. configurable: true
  57299. });
  57300. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  57301. get: function () {
  57302. return this._expensiveBlur;
  57303. },
  57304. set: function (b) {
  57305. 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"]);
  57306. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  57307. this._expensiveBlur = b;
  57308. this._firstUpdate = true;
  57309. },
  57310. enumerable: true,
  57311. configurable: true
  57312. });
  57313. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  57314. /**
  57315. * Support test.
  57316. * @type {boolean}
  57317. */
  57318. get: function () {
  57319. var engine = BABYLON.Engine.LastCreatedEngine;
  57320. if (!engine) {
  57321. return false;
  57322. }
  57323. return engine.getCaps().drawBuffersExtension;
  57324. },
  57325. enumerable: true,
  57326. configurable: true
  57327. });
  57328. // Public Methods
  57329. /**
  57330. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57331. */
  57332. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  57333. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  57334. for (var i = 0; i < this._scene.cameras.length; i++) {
  57335. var camera = this._scene.cameras[i];
  57336. this._originalColorPostProcess.dispose(camera);
  57337. this._ssaoPostProcess.dispose(camera);
  57338. this._blurHPostProcess.dispose(camera);
  57339. this._blurVPostProcess.dispose(camera);
  57340. this._ssaoCombinePostProcess.dispose(camera);
  57341. }
  57342. this._randomTexture.dispose();
  57343. if (disableGeometryBufferRenderer)
  57344. this._scene.disableGeometryBufferRenderer();
  57345. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57346. _super.prototype.dispose.call(this);
  57347. };
  57348. // Private Methods
  57349. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  57350. var _this = this;
  57351. this._samplerOffsets = [];
  57352. var expensive = this.expensiveBlur;
  57353. for (var i = -8; i < 8; i++) {
  57354. this._samplerOffsets.push(i * 2 + 0.5);
  57355. }
  57356. 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");
  57357. this._blurHPostProcess.onApply = function (effect) {
  57358. if (!_this._scene.activeCamera) {
  57359. return;
  57360. }
  57361. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57362. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57363. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57364. effect.setFloat("radius", _this.radius);
  57365. effect.setTexture("depthSampler", _this._depthTexture);
  57366. if (_this._firstUpdate) {
  57367. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57368. }
  57369. };
  57370. 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");
  57371. this._blurVPostProcess.onApply = function (effect) {
  57372. if (!_this._scene.activeCamera) {
  57373. return;
  57374. }
  57375. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57376. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57377. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57378. effect.setFloat("radius", _this.radius);
  57379. effect.setTexture("depthSampler", _this._depthTexture);
  57380. if (_this._firstUpdate) {
  57381. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57382. _this._firstUpdate = false;
  57383. }
  57384. };
  57385. };
  57386. SSAO2RenderingPipeline.prototype._rebuild = function () {
  57387. this._firstUpdate = true;
  57388. _super.prototype._rebuild.call(this);
  57389. };
  57390. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  57391. var numSamples = this.samples;
  57392. var result = [];
  57393. var vector, scale;
  57394. var rand = function (min, max) {
  57395. return Math.random() * (max - min) + min;
  57396. };
  57397. var i = 0;
  57398. while (i < numSamples) {
  57399. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  57400. vector.normalize();
  57401. scale = i / numSamples;
  57402. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  57403. vector.scaleInPlace(scale);
  57404. result.push(vector.x, vector.y, vector.z);
  57405. i++;
  57406. }
  57407. return result;
  57408. };
  57409. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57410. var _this = this;
  57411. var numSamples = this.samples;
  57412. this._sampleSphere = this._generateHemisphere();
  57413. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  57414. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57415. "base", "range", "projection", "near", "far", "texelSize",
  57416. "xViewport", "yViewport", "maxZ", "minZAspect"
  57417. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57418. this._ssaoPostProcess.onApply = function (effect) {
  57419. if (_this._firstUpdate) {
  57420. effect.setArray3("sampleSphere", _this._sampleSphere);
  57421. effect.setFloat("randTextureTiles", 4.0);
  57422. }
  57423. if (!_this._scene.activeCamera) {
  57424. return;
  57425. }
  57426. effect.setFloat("samplesFactor", 1 / _this.samples);
  57427. effect.setFloat("totalStrength", _this.totalStrength);
  57428. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  57429. effect.setFloat("radius", _this.radius);
  57430. effect.setFloat("maxZ", _this.maxZ);
  57431. effect.setFloat("minZAspect", _this.minZAspect);
  57432. effect.setFloat("base", _this.base);
  57433. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57434. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57435. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  57436. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  57437. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  57438. effect.setTexture("textureSampler", _this._depthTexture);
  57439. effect.setTexture("normalSampler", _this._normalTexture);
  57440. effect.setTexture("randomSampler", _this._randomTexture);
  57441. };
  57442. };
  57443. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57444. var _this = this;
  57445. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57446. this._ssaoCombinePostProcess.onApply = function (effect) {
  57447. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57448. };
  57449. };
  57450. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  57451. var size = 512;
  57452. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57453. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57454. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57455. var context = this._randomTexture.getContext();
  57456. var rand = function (min, max) {
  57457. return Math.random() * (max - min) + min;
  57458. };
  57459. var randVector = BABYLON.Vector3.Zero();
  57460. for (var x = 0; x < size; x++) {
  57461. for (var y = 0; y < size; y++) {
  57462. randVector.x = rand(0.0, 1.0);
  57463. randVector.y = rand(0.0, 1.0);
  57464. randVector.z = 0.0;
  57465. randVector.normalize();
  57466. randVector.scaleInPlace(255);
  57467. randVector.x = Math.floor(randVector.x);
  57468. randVector.y = Math.floor(randVector.y);
  57469. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57470. context.fillRect(x, y, 1, 1);
  57471. }
  57472. }
  57473. this._randomTexture.update(false);
  57474. };
  57475. __decorate([
  57476. BABYLON.serialize()
  57477. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  57478. __decorate([
  57479. BABYLON.serialize()
  57480. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  57481. __decorate([
  57482. BABYLON.serialize()
  57483. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  57484. __decorate([
  57485. BABYLON.serialize("samples")
  57486. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  57487. __decorate([
  57488. BABYLON.serialize("expensiveBlur")
  57489. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  57490. __decorate([
  57491. BABYLON.serialize()
  57492. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  57493. __decorate([
  57494. BABYLON.serialize()
  57495. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  57496. __decorate([
  57497. BABYLON.serialize()
  57498. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  57499. return SSAO2RenderingPipeline;
  57500. }(BABYLON.PostProcessRenderPipeline));
  57501. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  57502. })(BABYLON || (BABYLON = {}));
  57503. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  57504. // BABYLON.JS Chromatic Aberration GLSL Shader
  57505. // Author: Olivier Guyot
  57506. // Separates very slightly R, G and B colors on the edges of the screen
  57507. // Inspired by Francois Tarlier & Martins Upitis
  57508. var BABYLON;
  57509. (function (BABYLON) {
  57510. var LensRenderingPipeline = /** @class */ (function (_super) {
  57511. __extends(LensRenderingPipeline, _super);
  57512. /**
  57513. * @constructor
  57514. *
  57515. * Effect parameters are as follow:
  57516. * {
  57517. * chromatic_aberration: number; // from 0 to x (1 for realism)
  57518. * edge_blur: number; // from 0 to x (1 for realism)
  57519. * distortion: number; // from 0 to x (1 for realism)
  57520. * grain_amount: number; // from 0 to 1
  57521. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  57522. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  57523. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  57524. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  57525. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  57526. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  57527. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  57528. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  57529. * }
  57530. * Note: if an effect parameter is unset, effect is disabled
  57531. *
  57532. * @param {string} name - The rendering pipeline name
  57533. * @param {object} parameters - An object containing all parameters (see above)
  57534. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57535. * @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)
  57536. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57537. */
  57538. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  57539. if (ratio === void 0) { ratio = 1.0; }
  57540. var _this = _super.call(this, scene.getEngine(), name) || this;
  57541. // Lens effects can be of the following:
  57542. // - chromatic aberration (slight shift of RGB colors)
  57543. // - blur on the edge of the lens
  57544. // - lens distortion
  57545. // - depth-of-field blur & highlights enhancing
  57546. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  57547. // - grain effect (noise or custom texture)
  57548. // Two additional texture samplers are needed:
  57549. // - depth map (for depth-of-field)
  57550. // - grain texture
  57551. /**
  57552. * The chromatic aberration PostProcess id in the pipeline
  57553. * @type {string}
  57554. */
  57555. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  57556. /**
  57557. * The highlights enhancing PostProcess id in the pipeline
  57558. * @type {string}
  57559. */
  57560. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  57561. /**
  57562. * The depth-of-field PostProcess id in the pipeline
  57563. * @type {string}
  57564. */
  57565. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  57566. _this._scene = scene;
  57567. // Fetch texture samplers
  57568. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57569. if (parameters.grain_texture) {
  57570. _this._grainTexture = parameters.grain_texture;
  57571. }
  57572. else {
  57573. _this._createGrainTexture();
  57574. }
  57575. // save parameters
  57576. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  57577. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  57578. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  57579. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  57580. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  57581. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  57582. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  57583. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  57584. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  57585. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  57586. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  57587. // Create effects
  57588. _this._createChromaticAberrationPostProcess(ratio);
  57589. _this._createHighlightsPostProcess(ratio);
  57590. _this._createDepthOfFieldPostProcess(ratio / 4);
  57591. // Set up pipeline
  57592. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  57593. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  57594. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  57595. if (_this._highlightsGain === -1) {
  57596. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  57597. }
  57598. // Finish
  57599. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57600. if (cameras) {
  57601. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57602. }
  57603. return _this;
  57604. }
  57605. // public methods (self explanatory)
  57606. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  57607. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  57608. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  57609. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  57610. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  57611. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  57612. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  57613. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  57614. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  57615. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  57616. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  57617. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  57618. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  57619. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  57620. };
  57621. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  57622. this._highlightsPostProcess.updateEffect();
  57623. };
  57624. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  57625. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  57626. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  57627. this._highlightsGain = amount;
  57628. };
  57629. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  57630. if (this._highlightsGain === -1) {
  57631. this._highlightsGain = 1.0;
  57632. }
  57633. this._highlightsThreshold = amount;
  57634. };
  57635. LensRenderingPipeline.prototype.disableHighlights = function () {
  57636. this._highlightsGain = -1;
  57637. };
  57638. /**
  57639. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  57640. */
  57641. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57642. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57643. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57644. this._chromaticAberrationPostProcess = null;
  57645. this._highlightsPostProcess = null;
  57646. this._depthOfFieldPostProcess = null;
  57647. this._grainTexture.dispose();
  57648. if (disableDepthRender)
  57649. this._scene.disableDepthRenderer();
  57650. };
  57651. // colors shifting and distortion
  57652. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  57653. var _this = this;
  57654. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  57655. [], // samplers
  57656. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57657. this._chromaticAberrationPostProcess.onApply = function (effect) {
  57658. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  57659. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57660. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57661. };
  57662. };
  57663. // highlights enhancing
  57664. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  57665. var _this = this;
  57666. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  57667. [], // samplers
  57668. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  57669. this._highlightsPostProcess.onApply = function (effect) {
  57670. effect.setFloat('gain', _this._highlightsGain);
  57671. effect.setFloat('threshold', _this._highlightsThreshold);
  57672. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  57673. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57674. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57675. };
  57676. };
  57677. // colors shifting and distortion
  57678. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  57679. var _this = this;
  57680. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  57681. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  57682. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  57683. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57684. this._depthOfFieldPostProcess.onApply = function (effect) {
  57685. effect.setTexture("depthSampler", _this._depthTexture);
  57686. effect.setTexture("grainSampler", _this._grainTexture);
  57687. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  57688. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  57689. effect.setFloat('grain_amount', _this._grainAmount);
  57690. effect.setBool('blur_noise', _this._blurNoise);
  57691. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57692. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57693. effect.setFloat('distortion', _this._distortion);
  57694. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  57695. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  57696. effect.setFloat('aperture', _this._dofAperture);
  57697. effect.setFloat('darken', _this._dofDarken);
  57698. effect.setFloat('edge_blur', _this._edgeBlur);
  57699. effect.setBool('highlights', (_this._highlightsGain !== -1));
  57700. if (_this._scene.activeCamera) {
  57701. effect.setFloat('near', _this._scene.activeCamera.minZ);
  57702. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  57703. }
  57704. };
  57705. };
  57706. // creates a black and white random noise texture, 512x512
  57707. LensRenderingPipeline.prototype._createGrainTexture = function () {
  57708. var size = 512;
  57709. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57710. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57711. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57712. var context = this._grainTexture.getContext();
  57713. var rand = function (min, max) {
  57714. return Math.random() * (max - min) + min;
  57715. };
  57716. var value;
  57717. for (var x = 0; x < size; x++) {
  57718. for (var y = 0; y < size; y++) {
  57719. value = Math.floor(rand(0.42, 0.58) * 255);
  57720. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  57721. context.fillRect(x, y, 1, 1);
  57722. }
  57723. }
  57724. this._grainTexture.update(false);
  57725. };
  57726. return LensRenderingPipeline;
  57727. }(BABYLON.PostProcessRenderPipeline));
  57728. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  57729. })(BABYLON || (BABYLON = {}));
  57730. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  57731. var BABYLON;
  57732. (function (BABYLON) {
  57733. var StandardRenderingPipeline = /** @class */ (function (_super) {
  57734. __extends(StandardRenderingPipeline, _super);
  57735. /**
  57736. * @constructor
  57737. * @param {string} name - The rendering pipeline name
  57738. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57739. * @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)
  57740. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  57741. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57742. */
  57743. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  57744. if (originalPostProcess === void 0) { originalPostProcess = null; }
  57745. var _this = _super.call(this, scene.getEngine(), name) || this;
  57746. _this.downSampleX4PostProcess = null;
  57747. _this.brightPassPostProcess = null;
  57748. _this.blurHPostProcesses = [];
  57749. _this.blurVPostProcesses = [];
  57750. _this.textureAdderPostProcess = null;
  57751. _this.volumetricLightPostProcess = null;
  57752. _this.volumetricLightSmoothXPostProcess = null;
  57753. _this.volumetricLightSmoothYPostProcess = null;
  57754. _this.volumetricLightMergePostProces = null;
  57755. _this.volumetricLightFinalPostProcess = null;
  57756. _this.luminancePostProcess = null;
  57757. _this.luminanceDownSamplePostProcesses = [];
  57758. _this.hdrPostProcess = null;
  57759. _this.textureAdderFinalPostProcess = null;
  57760. _this.lensFlareFinalPostProcess = null;
  57761. _this.hdrFinalPostProcess = null;
  57762. _this.lensFlarePostProcess = null;
  57763. _this.lensFlareComposePostProcess = null;
  57764. _this.motionBlurPostProcess = null;
  57765. _this.depthOfFieldPostProcess = null;
  57766. // Values
  57767. _this.brightThreshold = 1.0;
  57768. _this.blurWidth = 512.0;
  57769. _this.horizontalBlur = false;
  57770. _this.exposure = 1.0;
  57771. _this.lensTexture = null;
  57772. _this.volumetricLightCoefficient = 0.2;
  57773. _this.volumetricLightPower = 4.0;
  57774. _this.volumetricLightBlurScale = 64.0;
  57775. _this.sourceLight = null;
  57776. _this.hdrMinimumLuminance = 1.0;
  57777. _this.hdrDecreaseRate = 0.5;
  57778. _this.hdrIncreaseRate = 0.5;
  57779. _this.lensColorTexture = null;
  57780. _this.lensFlareStrength = 20.0;
  57781. _this.lensFlareGhostDispersal = 1.4;
  57782. _this.lensFlareHaloWidth = 0.7;
  57783. _this.lensFlareDistortionStrength = 16.0;
  57784. _this.lensStarTexture = null;
  57785. _this.lensFlareDirtTexture = null;
  57786. _this.depthOfFieldDistance = 10.0;
  57787. _this.depthOfFieldBlurWidth = 64.0;
  57788. _this.motionStrength = 1.0;
  57789. // IAnimatable
  57790. _this.animations = [];
  57791. _this._currentDepthOfFieldSource = null;
  57792. _this._hdrCurrentLuminance = 1.0;
  57793. // Getters and setters
  57794. _this._bloomEnabled = true;
  57795. _this._depthOfFieldEnabled = false;
  57796. _this._vlsEnabled = false;
  57797. _this._lensFlareEnabled = false;
  57798. _this._hdrEnabled = false;
  57799. _this._motionBlurEnabled = false;
  57800. _this._motionBlurSamples = 64.0;
  57801. _this._volumetricLightStepsCount = 50.0;
  57802. _this._cameras = cameras || [];
  57803. // Initialize
  57804. _this._scene = scene;
  57805. _this._basePostProcess = originalPostProcess;
  57806. _this._ratio = ratio;
  57807. // Misc
  57808. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57809. // Finish
  57810. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57811. _this._buildPipeline();
  57812. return _this;
  57813. }
  57814. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  57815. get: function () {
  57816. return this._bloomEnabled;
  57817. },
  57818. set: function (enabled) {
  57819. if (this._bloomEnabled === enabled) {
  57820. return;
  57821. }
  57822. this._bloomEnabled = enabled;
  57823. this._buildPipeline();
  57824. },
  57825. enumerable: true,
  57826. configurable: true
  57827. });
  57828. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  57829. get: function () {
  57830. return this._depthOfFieldEnabled;
  57831. },
  57832. set: function (enabled) {
  57833. if (this._depthOfFieldEnabled === enabled) {
  57834. return;
  57835. }
  57836. this._depthOfFieldEnabled = enabled;
  57837. this._buildPipeline();
  57838. },
  57839. enumerable: true,
  57840. configurable: true
  57841. });
  57842. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  57843. get: function () {
  57844. return this._lensFlareEnabled;
  57845. },
  57846. set: function (enabled) {
  57847. if (this._lensFlareEnabled === enabled) {
  57848. return;
  57849. }
  57850. this._lensFlareEnabled = enabled;
  57851. this._buildPipeline();
  57852. },
  57853. enumerable: true,
  57854. configurable: true
  57855. });
  57856. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  57857. get: function () {
  57858. return this._hdrEnabled;
  57859. },
  57860. set: function (enabled) {
  57861. if (this._hdrEnabled === enabled) {
  57862. return;
  57863. }
  57864. this._hdrEnabled = enabled;
  57865. this._buildPipeline();
  57866. },
  57867. enumerable: true,
  57868. configurable: true
  57869. });
  57870. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  57871. get: function () {
  57872. return this._vlsEnabled;
  57873. },
  57874. set: function (enabled) {
  57875. if (this._vlsEnabled === enabled) {
  57876. return;
  57877. }
  57878. if (enabled) {
  57879. var geometry = this._scene.enableGeometryBufferRenderer();
  57880. if (!geometry) {
  57881. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  57882. return;
  57883. }
  57884. }
  57885. this._vlsEnabled = enabled;
  57886. this._buildPipeline();
  57887. },
  57888. enumerable: true,
  57889. configurable: true
  57890. });
  57891. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  57892. get: function () {
  57893. return this._motionBlurEnabled;
  57894. },
  57895. set: function (enabled) {
  57896. if (this._motionBlurEnabled === enabled) {
  57897. return;
  57898. }
  57899. this._motionBlurEnabled = enabled;
  57900. this._buildPipeline();
  57901. },
  57902. enumerable: true,
  57903. configurable: true
  57904. });
  57905. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  57906. get: function () {
  57907. return this._volumetricLightStepsCount;
  57908. },
  57909. set: function (count) {
  57910. if (this.volumetricLightPostProcess) {
  57911. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  57912. }
  57913. this._volumetricLightStepsCount = count;
  57914. },
  57915. enumerable: true,
  57916. configurable: true
  57917. });
  57918. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  57919. get: function () {
  57920. return this._motionBlurSamples;
  57921. },
  57922. set: function (samples) {
  57923. if (this.motionBlurPostProcess) {
  57924. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  57925. }
  57926. this._motionBlurSamples = samples;
  57927. },
  57928. enumerable: true,
  57929. configurable: true
  57930. });
  57931. StandardRenderingPipeline.prototype._buildPipeline = function () {
  57932. var _this = this;
  57933. var ratio = this._ratio;
  57934. var scene = this._scene;
  57935. this._disposePostProcesses();
  57936. this._reset();
  57937. // Create pass post-process
  57938. if (!this._basePostProcess) {
  57939. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  57940. this.originalPostProcess.onApply = function (effect) {
  57941. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  57942. };
  57943. }
  57944. else {
  57945. this.originalPostProcess = this._basePostProcess;
  57946. }
  57947. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  57948. this._currentDepthOfFieldSource = this.originalPostProcess;
  57949. if (this._vlsEnabled) {
  57950. // Create volumetric light
  57951. this._createVolumetricLightPostProcess(scene, ratio);
  57952. // Create volumetric light final post-process
  57953. 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);
  57954. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  57955. }
  57956. if (this._bloomEnabled) {
  57957. // Create down sample X4 post-process
  57958. this._createDownSampleX4PostProcess(scene, ratio / 2);
  57959. // Create bright pass post-process
  57960. this._createBrightPassPostProcess(scene, ratio / 2);
  57961. // Create gaussian blur post-processes (down sampling blurs)
  57962. this._createBlurPostProcesses(scene, ratio / 4, 1);
  57963. // Create texture adder post-process
  57964. this._createTextureAdderPostProcess(scene, ratio);
  57965. // Create depth-of-field source post-process
  57966. 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);
  57967. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  57968. }
  57969. if (this._lensFlareEnabled) {
  57970. // Create lens flare post-process
  57971. this._createLensFlarePostProcess(scene, ratio);
  57972. // Create depth-of-field source post-process post lens-flare and disable it now
  57973. 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);
  57974. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  57975. }
  57976. if (this._hdrEnabled) {
  57977. // Create luminance
  57978. this._createLuminancePostProcesses(scene, this._floatTextureType);
  57979. // Create HDR
  57980. this._createHdrPostProcess(scene, ratio);
  57981. // Create depth-of-field source post-process post hdr and disable it now
  57982. 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);
  57983. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  57984. }
  57985. if (this._depthOfFieldEnabled) {
  57986. // Create gaussian blur used by depth-of-field
  57987. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  57988. // Create depth-of-field post-process
  57989. this._createDepthOfFieldPostProcess(scene, ratio);
  57990. }
  57991. if (this._motionBlurEnabled) {
  57992. // Create motion blur post-process
  57993. this._createMotionBlurPostProcess(scene, ratio);
  57994. }
  57995. if (this._cameras !== null) {
  57996. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  57997. }
  57998. };
  57999. // Down Sample X4 Post-Processs
  58000. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58001. var _this = this;
  58002. var downSampleX4Offsets = new Array(32);
  58003. 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);
  58004. this.downSampleX4PostProcess.onApply = function (effect) {
  58005. var id = 0;
  58006. var width = _this.downSampleX4PostProcess.width;
  58007. var height = _this.downSampleX4PostProcess.height;
  58008. for (var i = -2; i < 2; i++) {
  58009. for (var j = -2; j < 2; j++) {
  58010. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58011. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58012. id += 2;
  58013. }
  58014. }
  58015. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58016. };
  58017. // Add to pipeline
  58018. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58019. };
  58020. // Brightpass Post-Process
  58021. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58022. var _this = this;
  58023. var brightOffsets = new Array(8);
  58024. 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);
  58025. this.brightPassPostProcess.onApply = function (effect) {
  58026. var sU = (1.0 / _this.brightPassPostProcess.width);
  58027. var sV = (1.0 / _this.brightPassPostProcess.height);
  58028. brightOffsets[0] = -0.5 * sU;
  58029. brightOffsets[1] = 0.5 * sV;
  58030. brightOffsets[2] = 0.5 * sU;
  58031. brightOffsets[3] = 0.5 * sV;
  58032. brightOffsets[4] = -0.5 * sU;
  58033. brightOffsets[5] = -0.5 * sV;
  58034. brightOffsets[6] = 0.5 * sU;
  58035. brightOffsets[7] = -0.5 * sV;
  58036. effect.setArray2("dsOffsets", brightOffsets);
  58037. effect.setFloat("brightThreshold", _this.brightThreshold);
  58038. };
  58039. // Add to pipeline
  58040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58041. };
  58042. // Create blur H&V post-processes
  58043. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58044. var _this = this;
  58045. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58046. var engine = scene.getEngine();
  58047. 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);
  58048. 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);
  58049. blurX.onActivateObservable.add(function () {
  58050. var dw = blurX.width / engine.getRenderWidth();
  58051. blurX.kernel = _this[blurWidthKey] * dw;
  58052. });
  58053. blurY.onActivateObservable.add(function () {
  58054. var dw = blurY.height / engine.getRenderHeight();
  58055. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58056. });
  58057. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58058. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58059. this.blurHPostProcesses.push(blurX);
  58060. this.blurVPostProcesses.push(blurY);
  58061. };
  58062. // Create texture adder post-process
  58063. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58064. var _this = this;
  58065. 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);
  58066. this.textureAdderPostProcess.onApply = function (effect) {
  58067. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58068. effect.setTexture("lensSampler", _this.lensTexture);
  58069. effect.setFloat("exposure", _this.exposure);
  58070. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58071. };
  58072. // Add to pipeline
  58073. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58074. };
  58075. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58076. var _this = this;
  58077. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58078. geometryRenderer.enablePosition = true;
  58079. var geometry = geometryRenderer.getGBuffer();
  58080. // Base post-process
  58081. 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));
  58082. var depthValues = BABYLON.Vector2.Zero();
  58083. this.volumetricLightPostProcess.onApply = function (effect) {
  58084. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  58085. var generator = _this.sourceLight.getShadowGenerator();
  58086. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  58087. effect.setTexture("positionSampler", geometry.textures[2]);
  58088. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  58089. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  58090. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  58091. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  58092. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  58093. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  58094. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  58095. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  58096. effect.setVector2("depthValues", depthValues);
  58097. }
  58098. };
  58099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  58100. // Smooth
  58101. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  58102. // Merge
  58103. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  58104. this.volumetricLightMergePostProces.onApply = function (effect) {
  58105. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  58106. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  58107. };
  58108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  58109. };
  58110. // Create luminance
  58111. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  58112. var _this = this;
  58113. // Create luminance
  58114. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  58115. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  58116. var offsets = [];
  58117. this.luminancePostProcess.onApply = function (effect) {
  58118. var sU = (1.0 / _this.luminancePostProcess.width);
  58119. var sV = (1.0 / _this.luminancePostProcess.height);
  58120. offsets[0] = -0.5 * sU;
  58121. offsets[1] = 0.5 * sV;
  58122. offsets[2] = 0.5 * sU;
  58123. offsets[3] = 0.5 * sV;
  58124. offsets[4] = -0.5 * sU;
  58125. offsets[5] = -0.5 * sV;
  58126. offsets[6] = 0.5 * sU;
  58127. offsets[7] = -0.5 * sV;
  58128. effect.setArray2("lumOffsets", offsets);
  58129. };
  58130. // Add to pipeline
  58131. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  58132. // Create down sample luminance
  58133. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  58134. var size = Math.pow(3, i);
  58135. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  58136. if (i === 0) {
  58137. defines += "#define FINAL_DOWN_SAMPLER";
  58138. }
  58139. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  58140. this.luminanceDownSamplePostProcesses.push(postProcess);
  58141. }
  58142. // Create callbacks and add effects
  58143. var lastLuminance = this.luminancePostProcess;
  58144. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  58145. var downSampleOffsets = new Array(18);
  58146. pp.onApply = function (effect) {
  58147. if (!lastLuminance) {
  58148. return;
  58149. }
  58150. var id = 0;
  58151. for (var x = -1; x < 2; x++) {
  58152. for (var y = -1; y < 2; y++) {
  58153. downSampleOffsets[id] = x / lastLuminance.width;
  58154. downSampleOffsets[id + 1] = y / lastLuminance.height;
  58155. id += 2;
  58156. }
  58157. }
  58158. effect.setArray2("dsOffsets", downSampleOffsets);
  58159. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  58160. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58161. lastLuminance = _this.luminancePostProcess;
  58162. }
  58163. else {
  58164. lastLuminance = pp;
  58165. }
  58166. };
  58167. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58168. pp.onAfterRender = function (effect) {
  58169. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  58170. 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);
  58171. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  58172. };
  58173. }
  58174. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  58175. });
  58176. };
  58177. // Create HDR post-process
  58178. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  58179. var _this = this;
  58180. 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);
  58181. var outputLiminance = 1;
  58182. var time = 0;
  58183. var lastTime = 0;
  58184. this.hdrPostProcess.onApply = function (effect) {
  58185. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  58186. time += scene.getEngine().getDeltaTime();
  58187. if (outputLiminance < 0) {
  58188. outputLiminance = _this._hdrCurrentLuminance;
  58189. }
  58190. else {
  58191. var dt = (lastTime - time) / 1000.0;
  58192. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  58193. outputLiminance += _this.hdrDecreaseRate * dt;
  58194. }
  58195. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  58196. outputLiminance -= _this.hdrIncreaseRate * dt;
  58197. }
  58198. else {
  58199. outputLiminance = _this._hdrCurrentLuminance;
  58200. }
  58201. }
  58202. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  58203. effect.setFloat("averageLuminance", outputLiminance);
  58204. lastTime = time;
  58205. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  58206. };
  58207. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  58208. };
  58209. // Create lens flare post-process
  58210. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58211. var _this = this;
  58212. 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);
  58213. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58214. this._createBlurPostProcesses(scene, ratio / 4, 2);
  58215. 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);
  58216. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58217. var resolution = new BABYLON.Vector2(0, 0);
  58218. // Lens flare
  58219. this.lensFlarePostProcess.onApply = function (effect) {
  58220. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  58221. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58222. effect.setFloat("strength", _this.lensFlareStrength);
  58223. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58224. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58225. // Shift
  58226. resolution.x = _this.lensFlarePostProcess.width;
  58227. resolution.y = _this.lensFlarePostProcess.height;
  58228. effect.setVector2("resolution", resolution);
  58229. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58230. };
  58231. // Compose
  58232. 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);
  58233. 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);
  58234. this.lensFlareComposePostProcess.onApply = function (effect) {
  58235. if (!_this._scene.activeCamera) {
  58236. return;
  58237. }
  58238. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58239. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58240. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58241. // Lens start rotation matrix
  58242. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58243. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58244. 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));
  58245. camRot *= 4.0;
  58246. 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);
  58247. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58248. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58249. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  58250. };
  58251. };
  58252. // Create depth-of-field post-process
  58253. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58254. var _this = this;
  58255. 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);
  58256. this.depthOfFieldPostProcess.onApply = function (effect) {
  58257. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58258. effect.setTexture("depthSampler", _this._getDepthTexture());
  58259. effect.setFloat("distance", _this.depthOfFieldDistance);
  58260. };
  58261. // Add to pipeline
  58262. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58263. };
  58264. // Create motion blur post-process
  58265. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  58266. var _this = this;
  58267. 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);
  58268. var motionScale = 0;
  58269. var prevViewProjection = BABYLON.Matrix.Identity();
  58270. var invViewProjection = BABYLON.Matrix.Identity();
  58271. var viewProjection = BABYLON.Matrix.Identity();
  58272. var screenSize = BABYLON.Vector2.Zero();
  58273. this.motionBlurPostProcess.onApply = function (effect) {
  58274. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  58275. viewProjection.invertToRef(invViewProjection);
  58276. effect.setMatrix("inverseViewProjection", invViewProjection);
  58277. effect.setMatrix("prevViewProjection", prevViewProjection);
  58278. prevViewProjection = viewProjection;
  58279. screenSize.x = _this.motionBlurPostProcess.width;
  58280. screenSize.y = _this.motionBlurPostProcess.height;
  58281. effect.setVector2("screenSize", screenSize);
  58282. motionScale = scene.getEngine().getFps() / 60.0;
  58283. effect.setFloat("motionScale", motionScale);
  58284. effect.setFloat("motionStrength", _this.motionStrength);
  58285. effect.setTexture("depthSampler", _this._getDepthTexture());
  58286. };
  58287. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  58288. };
  58289. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  58290. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  58291. var renderer = this._scene.enableGeometryBufferRenderer();
  58292. return renderer.getGBuffer().textures[0];
  58293. }
  58294. return this._scene.enableDepthRenderer().getDepthMap();
  58295. };
  58296. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  58297. for (var i = 0; i < this._cameras.length; i++) {
  58298. var camera = this._cameras[i];
  58299. if (this.originalPostProcess) {
  58300. this.originalPostProcess.dispose(camera);
  58301. }
  58302. if (this.downSampleX4PostProcess) {
  58303. this.downSampleX4PostProcess.dispose(camera);
  58304. }
  58305. if (this.brightPassPostProcess) {
  58306. this.brightPassPostProcess.dispose(camera);
  58307. }
  58308. if (this.textureAdderPostProcess) {
  58309. this.textureAdderPostProcess.dispose(camera);
  58310. }
  58311. if (this.textureAdderFinalPostProcess) {
  58312. this.textureAdderFinalPostProcess.dispose(camera);
  58313. }
  58314. if (this.volumetricLightPostProcess) {
  58315. this.volumetricLightPostProcess.dispose(camera);
  58316. }
  58317. if (this.volumetricLightSmoothXPostProcess) {
  58318. this.volumetricLightSmoothXPostProcess.dispose(camera);
  58319. }
  58320. if (this.volumetricLightSmoothYPostProcess) {
  58321. this.volumetricLightSmoothYPostProcess.dispose(camera);
  58322. }
  58323. if (this.volumetricLightMergePostProces) {
  58324. this.volumetricLightMergePostProces.dispose(camera);
  58325. }
  58326. if (this.volumetricLightFinalPostProcess) {
  58327. this.volumetricLightFinalPostProcess.dispose(camera);
  58328. }
  58329. if (this.lensFlarePostProcess) {
  58330. this.lensFlarePostProcess.dispose(camera);
  58331. }
  58332. if (this.lensFlareComposePostProcess) {
  58333. this.lensFlareComposePostProcess.dispose(camera);
  58334. }
  58335. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  58336. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  58337. }
  58338. if (this.luminancePostProcess) {
  58339. this.luminancePostProcess.dispose(camera);
  58340. }
  58341. if (this.hdrPostProcess) {
  58342. this.hdrPostProcess.dispose(camera);
  58343. }
  58344. if (this.hdrFinalPostProcess) {
  58345. this.hdrFinalPostProcess.dispose(camera);
  58346. }
  58347. if (this.depthOfFieldPostProcess) {
  58348. this.depthOfFieldPostProcess.dispose(camera);
  58349. }
  58350. if (this.motionBlurPostProcess) {
  58351. this.motionBlurPostProcess.dispose(camera);
  58352. }
  58353. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  58354. this.blurHPostProcesses[j].dispose(camera);
  58355. }
  58356. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  58357. this.blurVPostProcesses[j].dispose(camera);
  58358. }
  58359. }
  58360. this.originalPostProcess = null;
  58361. this.downSampleX4PostProcess = null;
  58362. this.brightPassPostProcess = null;
  58363. this.textureAdderPostProcess = null;
  58364. this.textureAdderFinalPostProcess = null;
  58365. this.volumetricLightPostProcess = null;
  58366. this.volumetricLightSmoothXPostProcess = null;
  58367. this.volumetricLightSmoothYPostProcess = null;
  58368. this.volumetricLightMergePostProces = null;
  58369. this.volumetricLightFinalPostProcess = null;
  58370. this.lensFlarePostProcess = null;
  58371. this.lensFlareComposePostProcess = null;
  58372. this.luminancePostProcess = null;
  58373. this.hdrPostProcess = null;
  58374. this.hdrFinalPostProcess = null;
  58375. this.depthOfFieldPostProcess = null;
  58376. this.motionBlurPostProcess = null;
  58377. this.luminanceDownSamplePostProcesses = [];
  58378. this.blurHPostProcesses = [];
  58379. this.blurVPostProcesses = [];
  58380. };
  58381. // Dispose
  58382. StandardRenderingPipeline.prototype.dispose = function () {
  58383. this._disposePostProcesses();
  58384. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58385. _super.prototype.dispose.call(this);
  58386. };
  58387. // Serialize rendering pipeline
  58388. StandardRenderingPipeline.prototype.serialize = function () {
  58389. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58390. serializationObject.customType = "StandardRenderingPipeline";
  58391. return serializationObject;
  58392. };
  58393. /**
  58394. * Static members
  58395. */
  58396. // Parse serialized pipeline
  58397. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58398. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58399. };
  58400. // Luminance steps
  58401. StandardRenderingPipeline.LuminanceSteps = 6;
  58402. __decorate([
  58403. BABYLON.serialize()
  58404. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58405. __decorate([
  58406. BABYLON.serialize()
  58407. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58408. __decorate([
  58409. BABYLON.serialize()
  58410. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58411. __decorate([
  58412. BABYLON.serialize()
  58413. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58414. __decorate([
  58415. BABYLON.serializeAsTexture("lensTexture")
  58416. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58417. __decorate([
  58418. BABYLON.serialize()
  58419. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  58420. __decorate([
  58421. BABYLON.serialize()
  58422. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  58423. __decorate([
  58424. BABYLON.serialize()
  58425. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  58426. __decorate([
  58427. BABYLON.serialize()
  58428. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  58429. __decorate([
  58430. BABYLON.serialize()
  58431. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  58432. __decorate([
  58433. BABYLON.serialize()
  58434. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  58435. __decorate([
  58436. BABYLON.serializeAsTexture("lensColorTexture")
  58437. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  58438. __decorate([
  58439. BABYLON.serialize()
  58440. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  58441. __decorate([
  58442. BABYLON.serialize()
  58443. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  58444. __decorate([
  58445. BABYLON.serialize()
  58446. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  58447. __decorate([
  58448. BABYLON.serialize()
  58449. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  58450. __decorate([
  58451. BABYLON.serializeAsTexture("lensStarTexture")
  58452. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  58453. __decorate([
  58454. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  58455. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  58456. __decorate([
  58457. BABYLON.serialize()
  58458. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  58459. __decorate([
  58460. BABYLON.serialize()
  58461. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  58462. __decorate([
  58463. BABYLON.serialize()
  58464. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  58465. __decorate([
  58466. BABYLON.serialize()
  58467. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  58468. __decorate([
  58469. BABYLON.serialize()
  58470. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  58471. __decorate([
  58472. BABYLON.serialize()
  58473. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  58474. __decorate([
  58475. BABYLON.serialize()
  58476. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  58477. __decorate([
  58478. BABYLON.serialize()
  58479. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  58480. __decorate([
  58481. BABYLON.serialize()
  58482. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  58483. __decorate([
  58484. BABYLON.serialize()
  58485. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  58486. __decorate([
  58487. BABYLON.serialize()
  58488. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  58489. return StandardRenderingPipeline;
  58490. }(BABYLON.PostProcessRenderPipeline));
  58491. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  58492. })(BABYLON || (BABYLON = {}));
  58493. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  58494. var BABYLON;
  58495. (function (BABYLON) {
  58496. var FxaaPostProcess = /** @class */ (function (_super) {
  58497. __extends(FxaaPostProcess, _super);
  58498. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58499. if (camera === void 0) { camera = null; }
  58500. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58501. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  58502. _this.onApplyObservable.add(function (effect) {
  58503. var texelSize = _this.texelSize;
  58504. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  58505. });
  58506. return _this;
  58507. }
  58508. return FxaaPostProcess;
  58509. }(BABYLON.PostProcess));
  58510. BABYLON.FxaaPostProcess = FxaaPostProcess;
  58511. })(BABYLON || (BABYLON = {}));
  58512. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  58513. var BABYLON;
  58514. (function (BABYLON) {
  58515. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  58516. __extends(DefaultRenderingPipeline, _super);
  58517. /**
  58518. * @constructor
  58519. * @param {string} name - The rendering pipeline name
  58520. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58521. * @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)
  58522. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58523. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  58524. */
  58525. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  58526. if (automaticBuild === void 0) { automaticBuild = true; }
  58527. var _this = _super.call(this, scene.getEngine(), name) || this;
  58528. _this.PassPostProcessId = "PassPostProcessEffect";
  58529. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  58530. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  58531. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  58532. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  58533. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  58534. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  58535. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  58536. // IAnimatable
  58537. _this.animations = [];
  58538. // Values
  58539. _this._bloomEnabled = false;
  58540. _this._fxaaEnabled = false;
  58541. _this._imageProcessingEnabled = true;
  58542. _this._bloomScale = 0.6;
  58543. _this._buildAllowed = true;
  58544. /**
  58545. * Specifies the size of the bloom blur kernel, relative to the final output size
  58546. */
  58547. _this.bloomKernel = 64;
  58548. /**
  58549. * Specifies the weight of the bloom in the final rendering
  58550. */
  58551. _this._bloomWeight = 0.15;
  58552. _this._cameras = cameras || [];
  58553. _this._buildAllowed = automaticBuild;
  58554. // Initialize
  58555. _this._scene = scene;
  58556. var caps = _this._scene.getEngine().getCaps();
  58557. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  58558. // Misc
  58559. if (_this._hdr) {
  58560. if (caps.textureHalfFloatRender) {
  58561. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58562. }
  58563. else if (caps.textureFloatRender) {
  58564. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58565. }
  58566. }
  58567. else {
  58568. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58569. }
  58570. // Attach
  58571. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58572. _this._buildPipeline();
  58573. return _this;
  58574. }
  58575. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  58576. get: function () {
  58577. return this._bloomWeight;
  58578. },
  58579. set: function (value) {
  58580. if (this._bloomWeight === value) {
  58581. return;
  58582. }
  58583. this._bloomWeight = value;
  58584. if (this._hdr && this.copyBack) {
  58585. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  58586. }
  58587. },
  58588. enumerable: true,
  58589. configurable: true
  58590. });
  58591. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  58592. get: function () {
  58593. return this._bloomScale;
  58594. },
  58595. set: function (value) {
  58596. if (this._bloomScale === value) {
  58597. return;
  58598. }
  58599. this._bloomScale = value;
  58600. this._buildPipeline();
  58601. },
  58602. enumerable: true,
  58603. configurable: true
  58604. });
  58605. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  58606. get: function () {
  58607. return this._bloomEnabled;
  58608. },
  58609. set: function (enabled) {
  58610. if (this._bloomEnabled === enabled) {
  58611. return;
  58612. }
  58613. this._bloomEnabled = enabled;
  58614. this._buildPipeline();
  58615. },
  58616. enumerable: true,
  58617. configurable: true
  58618. });
  58619. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  58620. get: function () {
  58621. return this._fxaaEnabled;
  58622. },
  58623. set: function (enabled) {
  58624. if (this._fxaaEnabled === enabled) {
  58625. return;
  58626. }
  58627. this._fxaaEnabled = enabled;
  58628. this._buildPipeline();
  58629. },
  58630. enumerable: true,
  58631. configurable: true
  58632. });
  58633. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  58634. get: function () {
  58635. return this._imageProcessingEnabled;
  58636. },
  58637. set: function (enabled) {
  58638. if (this._imageProcessingEnabled === enabled) {
  58639. return;
  58640. }
  58641. this._imageProcessingEnabled = enabled;
  58642. this._buildPipeline();
  58643. },
  58644. enumerable: true,
  58645. configurable: true
  58646. });
  58647. /**
  58648. * Force the compilation of the entire pipeline.
  58649. */
  58650. DefaultRenderingPipeline.prototype.prepare = function () {
  58651. var previousState = this._buildAllowed;
  58652. this._buildAllowed = true;
  58653. this._buildPipeline();
  58654. this._buildAllowed = previousState;
  58655. };
  58656. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  58657. var _this = this;
  58658. if (!this._buildAllowed) {
  58659. return;
  58660. }
  58661. var engine = this._scene.getEngine();
  58662. this._disposePostProcesses();
  58663. this._reset();
  58664. if (this.bloomEnabled) {
  58665. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58666. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  58667. if (!this._hdr) {
  58668. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58669. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  58670. this.highlights.autoClear = false;
  58671. this.highlights.alwaysForcePOT = true;
  58672. }
  58673. 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);
  58674. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  58675. this.blurX.alwaysForcePOT = true;
  58676. this.blurX.autoClear = false;
  58677. this.blurX.onActivateObservable.add(function () {
  58678. var dw = _this.blurX.width / engine.getRenderWidth(true);
  58679. _this.blurX.kernel = _this.bloomKernel * dw;
  58680. });
  58681. 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);
  58682. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  58683. this.blurY.alwaysForcePOT = true;
  58684. this.blurY.autoClear = false;
  58685. this.blurY.onActivateObservable.add(function () {
  58686. var dh = _this.blurY.height / engine.getRenderHeight(true);
  58687. _this.blurY.kernel = _this.bloomKernel * dh;
  58688. });
  58689. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58690. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  58691. this.copyBack.alwaysForcePOT = true;
  58692. if (this._hdr) {
  58693. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  58694. var w = this.bloomWeight;
  58695. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  58696. }
  58697. else {
  58698. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  58699. }
  58700. this.copyBack.autoClear = false;
  58701. }
  58702. if (this._imageProcessingEnabled) {
  58703. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58704. if (this._hdr) {
  58705. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  58706. }
  58707. else {
  58708. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  58709. }
  58710. }
  58711. if (this.fxaaEnabled) {
  58712. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58713. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  58714. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58715. }
  58716. else {
  58717. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58718. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  58719. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58720. }
  58721. if (this.bloomEnabled) {
  58722. if (this._hdr) {
  58723. this.copyBack.shareOutputWith(this.blurX);
  58724. if (this.imageProcessing) {
  58725. this.imageProcessing.shareOutputWith(this.pass);
  58726. this.imageProcessing.autoClear = false;
  58727. }
  58728. else if (this.fxaa) {
  58729. this.fxaa.shareOutputWith(this.pass);
  58730. }
  58731. else {
  58732. this.finalMerge.shareOutputWith(this.pass);
  58733. }
  58734. }
  58735. else {
  58736. if (this.fxaa) {
  58737. this.fxaa.shareOutputWith(this.pass);
  58738. }
  58739. else {
  58740. this.finalMerge.shareOutputWith(this.pass);
  58741. }
  58742. }
  58743. }
  58744. if (this._cameras !== null) {
  58745. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58746. }
  58747. };
  58748. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  58749. for (var i = 0; i < this._cameras.length; i++) {
  58750. var camera = this._cameras[i];
  58751. if (this.pass) {
  58752. this.pass.dispose(camera);
  58753. }
  58754. if (this.highlights) {
  58755. this.highlights.dispose(camera);
  58756. }
  58757. if (this.blurX) {
  58758. this.blurX.dispose(camera);
  58759. }
  58760. if (this.blurY) {
  58761. this.blurY.dispose(camera);
  58762. }
  58763. if (this.copyBack) {
  58764. this.copyBack.dispose(camera);
  58765. }
  58766. if (this.imageProcessing) {
  58767. this.imageProcessing.dispose(camera);
  58768. }
  58769. if (this.fxaa) {
  58770. this.fxaa.dispose(camera);
  58771. }
  58772. if (this.finalMerge) {
  58773. this.finalMerge.dispose(camera);
  58774. }
  58775. }
  58776. this.pass = null;
  58777. this.highlights = null;
  58778. this.blurX = null;
  58779. this.blurY = null;
  58780. this.copyBack = null;
  58781. this.imageProcessing = null;
  58782. this.fxaa = null;
  58783. this.finalMerge = null;
  58784. };
  58785. // Dispose
  58786. DefaultRenderingPipeline.prototype.dispose = function () {
  58787. this._disposePostProcesses();
  58788. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58789. _super.prototype.dispose.call(this);
  58790. };
  58791. // Serialize rendering pipeline
  58792. DefaultRenderingPipeline.prototype.serialize = function () {
  58793. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58794. serializationObject.customType = "DefaultRenderingPipeline";
  58795. return serializationObject;
  58796. };
  58797. // Parse serialized pipeline
  58798. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58799. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  58800. };
  58801. __decorate([
  58802. BABYLON.serialize()
  58803. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  58804. __decorate([
  58805. BABYLON.serialize()
  58806. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  58807. __decorate([
  58808. BABYLON.serialize()
  58809. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  58810. __decorate([
  58811. BABYLON.serialize()
  58812. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  58813. __decorate([
  58814. BABYLON.serialize()
  58815. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  58816. __decorate([
  58817. BABYLON.serialize()
  58818. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  58819. __decorate([
  58820. BABYLON.serialize()
  58821. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  58822. __decorate([
  58823. BABYLON.serialize()
  58824. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  58825. return DefaultRenderingPipeline;
  58826. }(BABYLON.PostProcessRenderPipeline));
  58827. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  58828. })(BABYLON || (BABYLON = {}));
  58829. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  58830. var BABYLON;
  58831. (function (BABYLON) {
  58832. var GeometryBufferRenderer = /** @class */ (function () {
  58833. function GeometryBufferRenderer(scene, ratio) {
  58834. if (ratio === void 0) { ratio = 1; }
  58835. this._enablePosition = false;
  58836. this._scene = scene;
  58837. this._ratio = ratio;
  58838. // Render target
  58839. this._createRenderTargets();
  58840. }
  58841. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  58842. set: function (meshes) {
  58843. this._multiRenderTarget.renderList = meshes;
  58844. },
  58845. enumerable: true,
  58846. configurable: true
  58847. });
  58848. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  58849. get: function () {
  58850. return this._multiRenderTarget.isSupported;
  58851. },
  58852. enumerable: true,
  58853. configurable: true
  58854. });
  58855. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  58856. get: function () {
  58857. return this._enablePosition;
  58858. },
  58859. set: function (enable) {
  58860. this._enablePosition = enable;
  58861. this.dispose();
  58862. this._createRenderTargets();
  58863. },
  58864. enumerable: true,
  58865. configurable: true
  58866. });
  58867. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  58868. var material = subMesh.getMaterial();
  58869. if (material && material.disableDepthWrite) {
  58870. return false;
  58871. }
  58872. var defines = [];
  58873. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  58874. var mesh = subMesh.getMesh();
  58875. // Alpha test
  58876. if (material && material.needAlphaTesting()) {
  58877. defines.push("#define ALPHATEST");
  58878. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58879. attribs.push(BABYLON.VertexBuffer.UVKind);
  58880. defines.push("#define UV1");
  58881. }
  58882. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58883. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58884. defines.push("#define UV2");
  58885. }
  58886. }
  58887. // Buffers
  58888. if (this._enablePosition) {
  58889. defines.push("#define POSITION");
  58890. }
  58891. // Bones
  58892. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58893. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58894. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58895. if (mesh.numBoneInfluencers > 4) {
  58896. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58897. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58898. }
  58899. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58900. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  58901. }
  58902. else {
  58903. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58904. }
  58905. // Instances
  58906. if (useInstances) {
  58907. defines.push("#define INSTANCES");
  58908. attribs.push("world0");
  58909. attribs.push("world1");
  58910. attribs.push("world2");
  58911. attribs.push("world3");
  58912. }
  58913. // Get correct effect
  58914. var join = defines.join("\n");
  58915. if (this._cachedDefines !== join) {
  58916. this._cachedDefines = join;
  58917. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  58918. }
  58919. return this._effect.isReady();
  58920. };
  58921. GeometryBufferRenderer.prototype.getGBuffer = function () {
  58922. return this._multiRenderTarget;
  58923. };
  58924. // Methods
  58925. GeometryBufferRenderer.prototype.dispose = function () {
  58926. this.getGBuffer().dispose();
  58927. };
  58928. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  58929. var _this = this;
  58930. var engine = this._scene.getEngine();
  58931. var count = this._enablePosition ? 3 : 2;
  58932. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  58933. if (!this.isSupported) {
  58934. return;
  58935. }
  58936. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58937. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58938. this._multiRenderTarget.refreshRate = 1;
  58939. this._multiRenderTarget.renderParticles = false;
  58940. this._multiRenderTarget.renderList = null;
  58941. // set default depth value to 1.0 (far away)
  58942. this._multiRenderTarget.onClearObservable.add(function (engine) {
  58943. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  58944. });
  58945. // Custom render function
  58946. var renderSubMesh = function (subMesh) {
  58947. var mesh = subMesh.getRenderingMesh();
  58948. var scene = _this._scene;
  58949. var engine = scene.getEngine();
  58950. var material = subMesh.getMaterial();
  58951. if (!material) {
  58952. return;
  58953. }
  58954. // Culling
  58955. engine.setState(material.backFaceCulling);
  58956. // Managing instances
  58957. var batch = mesh._getInstancesRenderList(subMesh._id);
  58958. if (batch.mustReturn) {
  58959. return;
  58960. }
  58961. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  58962. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  58963. engine.enableEffect(_this._effect);
  58964. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  58965. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  58966. _this._effect.setMatrix("view", scene.getViewMatrix());
  58967. // Alpha test
  58968. if (material && material.needAlphaTesting()) {
  58969. var alphaTexture = material.getAlphaTestTexture();
  58970. if (alphaTexture) {
  58971. _this._effect.setTexture("diffuseSampler", alphaTexture);
  58972. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  58973. }
  58974. }
  58975. // Bones
  58976. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58977. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  58978. }
  58979. // Draw
  58980. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58981. }
  58982. };
  58983. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58984. var index;
  58985. if (depthOnlySubMeshes.length) {
  58986. engine.setColorWrite(false);
  58987. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58988. renderSubMesh(depthOnlySubMeshes.data[index]);
  58989. }
  58990. engine.setColorWrite(true);
  58991. }
  58992. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58993. renderSubMesh(opaqueSubMeshes.data[index]);
  58994. }
  58995. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58996. renderSubMesh(alphaTestSubMeshes.data[index]);
  58997. }
  58998. };
  58999. };
  59000. return GeometryBufferRenderer;
  59001. }());
  59002. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  59003. })(BABYLON || (BABYLON = {}));
  59004. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59005. var BABYLON;
  59006. (function (BABYLON) {
  59007. var RefractionPostProcess = /** @class */ (function (_super) {
  59008. __extends(RefractionPostProcess, _super);
  59009. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59010. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59011. _this.color = color;
  59012. _this.depth = depth;
  59013. _this.colorLevel = colorLevel;
  59014. _this.onActivateObservable.add(function (cam) {
  59015. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59016. });
  59017. _this.onApplyObservable.add(function (effect) {
  59018. effect.setColor3("baseColor", _this.color);
  59019. effect.setFloat("depth", _this.depth);
  59020. effect.setFloat("colorLevel", _this.colorLevel);
  59021. effect.setTexture("refractionSampler", _this._refRexture);
  59022. });
  59023. return _this;
  59024. }
  59025. // Methods
  59026. RefractionPostProcess.prototype.dispose = function (camera) {
  59027. if (this._refRexture) {
  59028. this._refRexture.dispose();
  59029. }
  59030. _super.prototype.dispose.call(this, camera);
  59031. };
  59032. return RefractionPostProcess;
  59033. }(BABYLON.PostProcess));
  59034. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59035. })(BABYLON || (BABYLON = {}));
  59036. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59037. var BABYLON;
  59038. (function (BABYLON) {
  59039. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59040. __extends(BlackAndWhitePostProcess, _super);
  59041. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59042. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59043. _this.degree = 1;
  59044. _this.onApplyObservable.add(function (effect) {
  59045. effect.setFloat("degree", _this.degree);
  59046. });
  59047. return _this;
  59048. }
  59049. return BlackAndWhitePostProcess;
  59050. }(BABYLON.PostProcess));
  59051. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59052. })(BABYLON || (BABYLON = {}));
  59053. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59054. var BABYLON;
  59055. (function (BABYLON) {
  59056. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59057. __extends(ConvolutionPostProcess, _super);
  59058. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59059. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59060. _this.kernel = kernel;
  59061. _this.onApply = function (effect) {
  59062. effect.setFloat2("screenSize", _this.width, _this.height);
  59063. effect.setArray("kernel", _this.kernel);
  59064. };
  59065. return _this;
  59066. }
  59067. // Statics
  59068. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59069. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59070. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59071. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59072. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59073. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59074. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59075. return ConvolutionPostProcess;
  59076. }(BABYLON.PostProcess));
  59077. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59078. })(BABYLON || (BABYLON = {}));
  59079. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59080. var BABYLON;
  59081. (function (BABYLON) {
  59082. var FilterPostProcess = /** @class */ (function (_super) {
  59083. __extends(FilterPostProcess, _super);
  59084. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  59085. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  59086. _this.kernelMatrix = kernelMatrix;
  59087. _this.onApply = function (effect) {
  59088. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  59089. };
  59090. return _this;
  59091. }
  59092. return FilterPostProcess;
  59093. }(BABYLON.PostProcess));
  59094. BABYLON.FilterPostProcess = FilterPostProcess;
  59095. })(BABYLON || (BABYLON = {}));
  59096. //# sourceMappingURL=babylon.filterPostProcess.js.map
  59097. var BABYLON;
  59098. (function (BABYLON) {
  59099. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  59100. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  59101. __extends(VolumetricLightScatteringPostProcess, _super);
  59102. /**
  59103. * @constructor
  59104. * @param {string} name - The post-process name
  59105. * @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)
  59106. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  59107. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  59108. * @param {number} samples - The post-process quality, default 100
  59109. * @param {number} samplingMode - The post-process filtering mode
  59110. * @param {BABYLON.Engine} engine - The babylon engine
  59111. * @param {boolean} reusable - If the post-process is reusable
  59112. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  59113. */
  59114. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  59115. if (samples === void 0) { samples = 100; }
  59116. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59117. 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;
  59118. _this._screenCoordinates = BABYLON.Vector2.Zero();
  59119. /**
  59120. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  59121. * @type {Vector3}
  59122. */
  59123. _this.customMeshPosition = BABYLON.Vector3.Zero();
  59124. /**
  59125. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  59126. * @type {boolean}
  59127. */
  59128. _this.useCustomMeshPosition = false;
  59129. /**
  59130. * If the post-process should inverse the light scattering direction
  59131. * @type {boolean}
  59132. */
  59133. _this.invert = true;
  59134. /**
  59135. * Array containing the excluded meshes not rendered in the internal pass
  59136. */
  59137. _this.excludedMeshes = new Array();
  59138. /**
  59139. * Controls the overall intensity of the post-process
  59140. * @type {number}
  59141. */
  59142. _this.exposure = 0.3;
  59143. /**
  59144. * Dissipates each sample's contribution in range [0, 1]
  59145. * @type {number}
  59146. */
  59147. _this.decay = 0.96815;
  59148. /**
  59149. * Controls the overall intensity of each sample
  59150. * @type {number}
  59151. */
  59152. _this.weight = 0.58767;
  59153. /**
  59154. * Controls the density of each sample
  59155. * @type {number}
  59156. */
  59157. _this.density = 0.926;
  59158. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  59159. engine = scene.getEngine();
  59160. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59161. // Configure mesh
  59162. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  59163. // Configure
  59164. _this._createPass(scene, ratio.passRatio || ratio);
  59165. _this.onActivate = function (camera) {
  59166. if (!_this.isSupported) {
  59167. _this.dispose(camera);
  59168. }
  59169. _this.onActivate = null;
  59170. };
  59171. _this.onApplyObservable.add(function (effect) {
  59172. _this._updateMeshScreenCoordinates(scene);
  59173. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  59174. effect.setFloat("exposure", _this.exposure);
  59175. effect.setFloat("decay", _this.decay);
  59176. effect.setFloat("weight", _this.weight);
  59177. effect.setFloat("density", _this.density);
  59178. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  59179. });
  59180. return _this;
  59181. }
  59182. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  59183. get: function () {
  59184. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59185. return false;
  59186. },
  59187. set: function (useDiffuseColor) {
  59188. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59189. },
  59190. enumerable: true,
  59191. configurable: true
  59192. });
  59193. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  59194. return "VolumetricLightScatteringPostProcess";
  59195. };
  59196. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  59197. var mesh = subMesh.getMesh();
  59198. // Render this.mesh as default
  59199. if (mesh === this.mesh && mesh.material) {
  59200. return mesh.material.isReady(mesh);
  59201. }
  59202. var defines = [];
  59203. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59204. var material = subMesh.getMaterial();
  59205. // Alpha test
  59206. if (material) {
  59207. if (material.needAlphaTesting()) {
  59208. defines.push("#define ALPHATEST");
  59209. }
  59210. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59211. attribs.push(BABYLON.VertexBuffer.UVKind);
  59212. defines.push("#define UV1");
  59213. }
  59214. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59215. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59216. defines.push("#define UV2");
  59217. }
  59218. }
  59219. // Bones
  59220. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59221. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59222. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59223. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59224. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  59225. }
  59226. else {
  59227. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59228. }
  59229. // Instances
  59230. if (useInstances) {
  59231. defines.push("#define INSTANCES");
  59232. attribs.push("world0");
  59233. attribs.push("world1");
  59234. attribs.push("world2");
  59235. attribs.push("world3");
  59236. }
  59237. // Get correct effect
  59238. var join = defines.join("\n");
  59239. if (this._cachedDefines !== join) {
  59240. this._cachedDefines = join;
  59241. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  59242. }
  59243. return this._volumetricLightScatteringPass.isReady();
  59244. };
  59245. /**
  59246. * Sets the new light position for light scattering effect
  59247. * @param {BABYLON.Vector3} The new custom light position
  59248. */
  59249. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  59250. this.customMeshPosition = position;
  59251. };
  59252. /**
  59253. * Returns the light position for light scattering effect
  59254. * @return {BABYLON.Vector3} The custom light position
  59255. */
  59256. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  59257. return this.customMeshPosition;
  59258. };
  59259. /**
  59260. * Disposes the internal assets and detaches the post-process from the camera
  59261. */
  59262. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  59263. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  59264. if (rttIndex !== -1) {
  59265. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  59266. }
  59267. this._volumetricLightScatteringRTT.dispose();
  59268. _super.prototype.dispose.call(this, camera);
  59269. };
  59270. /**
  59271. * Returns the render target texture used by the post-process
  59272. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  59273. */
  59274. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  59275. return this._volumetricLightScatteringRTT;
  59276. };
  59277. // Private methods
  59278. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  59279. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  59280. return true;
  59281. }
  59282. return false;
  59283. };
  59284. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  59285. var _this = this;
  59286. var engine = scene.getEngine();
  59287. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59288. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59289. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59290. this._volumetricLightScatteringRTT.renderList = null;
  59291. this._volumetricLightScatteringRTT.renderParticles = false;
  59292. var camera = this.getCamera();
  59293. if (camera) {
  59294. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59295. }
  59296. else {
  59297. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59298. }
  59299. // Custom render function for submeshes
  59300. var renderSubMesh = function (subMesh) {
  59301. var mesh = subMesh.getRenderingMesh();
  59302. if (_this._meshExcluded(mesh)) {
  59303. return;
  59304. }
  59305. var material = subMesh.getMaterial();
  59306. if (!material) {
  59307. return;
  59308. }
  59309. var scene = mesh.getScene();
  59310. var engine = scene.getEngine();
  59311. // Culling
  59312. engine.setState(material.backFaceCulling);
  59313. // Managing instances
  59314. var batch = mesh._getInstancesRenderList(subMesh._id);
  59315. if (batch.mustReturn) {
  59316. return;
  59317. }
  59318. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59319. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59320. var effect = _this._volumetricLightScatteringPass;
  59321. if (mesh === _this.mesh) {
  59322. if (subMesh.effect) {
  59323. effect = subMesh.effect;
  59324. }
  59325. else {
  59326. effect = material.getEffect();
  59327. }
  59328. }
  59329. engine.enableEffect(effect);
  59330. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  59331. if (mesh === _this.mesh) {
  59332. material.bind(mesh.getWorldMatrix(), mesh);
  59333. }
  59334. else {
  59335. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  59336. // Alpha test
  59337. if (material && material.needAlphaTesting()) {
  59338. var alphaTexture = material.getAlphaTestTexture();
  59339. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  59340. if (alphaTexture) {
  59341. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59342. }
  59343. }
  59344. // Bones
  59345. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59346. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59347. }
  59348. }
  59349. // Draw
  59350. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  59351. }
  59352. };
  59353. // Render target texture callbacks
  59354. var savedSceneClearColor;
  59355. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  59356. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  59357. savedSceneClearColor = scene.clearColor;
  59358. scene.clearColor = sceneClearColor;
  59359. });
  59360. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  59361. scene.clearColor = savedSceneClearColor;
  59362. });
  59363. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59364. var engine = scene.getEngine();
  59365. var index;
  59366. if (depthOnlySubMeshes.length) {
  59367. engine.setColorWrite(false);
  59368. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59369. renderSubMesh(depthOnlySubMeshes.data[index]);
  59370. }
  59371. engine.setColorWrite(true);
  59372. }
  59373. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59374. renderSubMesh(opaqueSubMeshes.data[index]);
  59375. }
  59376. engine.setAlphaTesting(true);
  59377. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59378. renderSubMesh(alphaTestSubMeshes.data[index]);
  59379. }
  59380. engine.setAlphaTesting(false);
  59381. if (transparentSubMeshes.length) {
  59382. // Sort sub meshes
  59383. for (index = 0; index < transparentSubMeshes.length; index++) {
  59384. var submesh = transparentSubMeshes.data[index];
  59385. var boundingInfo = submesh.getBoundingInfo();
  59386. if (boundingInfo && scene.activeCamera) {
  59387. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  59388. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  59389. }
  59390. }
  59391. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  59392. sortedArray.sort(function (a, b) {
  59393. // Alpha index first
  59394. if (a._alphaIndex > b._alphaIndex) {
  59395. return 1;
  59396. }
  59397. if (a._alphaIndex < b._alphaIndex) {
  59398. return -1;
  59399. }
  59400. // Then distance to camera
  59401. if (a._distanceToCamera < b._distanceToCamera) {
  59402. return 1;
  59403. }
  59404. if (a._distanceToCamera > b._distanceToCamera) {
  59405. return -1;
  59406. }
  59407. return 0;
  59408. });
  59409. // Render sub meshes
  59410. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59411. for (index = 0; index < sortedArray.length; index++) {
  59412. renderSubMesh(sortedArray[index]);
  59413. }
  59414. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59415. }
  59416. };
  59417. };
  59418. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  59419. var transform = scene.getTransformMatrix();
  59420. var meshPosition;
  59421. if (this.useCustomMeshPosition) {
  59422. meshPosition = this.customMeshPosition;
  59423. }
  59424. else if (this.attachedNode) {
  59425. meshPosition = this.attachedNode.position;
  59426. }
  59427. else {
  59428. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  59429. }
  59430. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  59431. this._screenCoordinates.x = pos.x / this._viewPort.width;
  59432. this._screenCoordinates.y = pos.y / this._viewPort.height;
  59433. if (this.invert)
  59434. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  59435. };
  59436. // Static methods
  59437. /**
  59438. * Creates a default mesh for the Volumeric Light Scattering post-process
  59439. * @param {string} The mesh name
  59440. * @param {BABYLON.Scene} The scene where to create the mesh
  59441. * @return {BABYLON.Mesh} the default mesh
  59442. */
  59443. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  59444. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  59445. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59446. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  59447. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  59448. mesh.material = material;
  59449. return mesh;
  59450. };
  59451. __decorate([
  59452. BABYLON.serializeAsVector3()
  59453. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  59454. __decorate([
  59455. BABYLON.serialize()
  59456. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  59457. __decorate([
  59458. BABYLON.serialize()
  59459. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  59460. __decorate([
  59461. BABYLON.serializeAsMeshReference()
  59462. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  59463. __decorate([
  59464. BABYLON.serialize()
  59465. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  59466. __decorate([
  59467. BABYLON.serialize()
  59468. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  59469. __decorate([
  59470. BABYLON.serialize()
  59471. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  59472. __decorate([
  59473. BABYLON.serialize()
  59474. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  59475. __decorate([
  59476. BABYLON.serialize()
  59477. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  59478. return VolumetricLightScatteringPostProcess;
  59479. }(BABYLON.PostProcess));
  59480. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  59481. })(BABYLON || (BABYLON = {}));
  59482. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  59483. //
  59484. // This post-process allows the modification of rendered colors by using
  59485. // a 'look-up table' (LUT). This effect is also called Color Grading.
  59486. //
  59487. // The object needs to be provided an url to a texture containing the color
  59488. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  59489. // Use an image editing software to tweak the LUT to match your needs.
  59490. //
  59491. // For an example of a color LUT, see here:
  59492. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  59493. // For explanations on color grading, see here:
  59494. // http://udn.epicgames.com/Three/ColorGrading.html
  59495. //
  59496. var BABYLON;
  59497. (function (BABYLON) {
  59498. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  59499. __extends(ColorCorrectionPostProcess, _super);
  59500. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  59501. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  59502. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59503. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  59504. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59505. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59506. _this.onApply = function (effect) {
  59507. effect.setTexture("colorTable", _this._colorTableTexture);
  59508. };
  59509. return _this;
  59510. }
  59511. return ColorCorrectionPostProcess;
  59512. }(BABYLON.PostProcess));
  59513. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  59514. })(BABYLON || (BABYLON = {}));
  59515. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  59516. var BABYLON;
  59517. (function (BABYLON) {
  59518. var TonemappingOperator;
  59519. (function (TonemappingOperator) {
  59520. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  59521. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  59522. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  59523. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  59524. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  59525. ;
  59526. var TonemapPostProcess = /** @class */ (function (_super) {
  59527. __extends(TonemapPostProcess, _super);
  59528. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  59529. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59530. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59531. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  59532. _this._operator = _operator;
  59533. _this.exposureAdjustment = exposureAdjustment;
  59534. var defines = "#define ";
  59535. if (_this._operator === TonemappingOperator.Hable)
  59536. defines += "HABLE_TONEMAPPING";
  59537. else if (_this._operator === TonemappingOperator.Reinhard)
  59538. defines += "REINHARD_TONEMAPPING";
  59539. else if (_this._operator === TonemappingOperator.HejiDawson)
  59540. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  59541. else if (_this._operator === TonemappingOperator.Photographic)
  59542. defines += "PHOTOGRAPHIC_TONEMAPPING";
  59543. //sadly a second call to create the effect.
  59544. _this.updateEffect(defines);
  59545. _this.onApply = function (effect) {
  59546. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  59547. };
  59548. return _this;
  59549. }
  59550. return TonemapPostProcess;
  59551. }(BABYLON.PostProcess));
  59552. BABYLON.TonemapPostProcess = TonemapPostProcess;
  59553. })(BABYLON || (BABYLON = {}));
  59554. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  59555. var BABYLON;
  59556. (function (BABYLON) {
  59557. var DisplayPassPostProcess = /** @class */ (function (_super) {
  59558. __extends(DisplayPassPostProcess, _super);
  59559. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  59560. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  59561. }
  59562. return DisplayPassPostProcess;
  59563. }(BABYLON.PostProcess));
  59564. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  59565. })(BABYLON || (BABYLON = {}));
  59566. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  59567. var BABYLON;
  59568. (function (BABYLON) {
  59569. var HighlightsPostProcess = /** @class */ (function (_super) {
  59570. __extends(HighlightsPostProcess, _super);
  59571. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59572. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59573. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  59574. }
  59575. return HighlightsPostProcess;
  59576. }(BABYLON.PostProcess));
  59577. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  59578. })(BABYLON || (BABYLON = {}));
  59579. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  59580. var BABYLON;
  59581. (function (BABYLON) {
  59582. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  59583. __extends(ImageProcessingPostProcess, _super);
  59584. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59585. if (camera === void 0) { camera = null; }
  59586. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59587. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  59588. _this._fromLinearSpace = true;
  59589. /**
  59590. * Defines cache preventing GC.
  59591. */
  59592. _this._defines = {
  59593. IMAGEPROCESSING: false,
  59594. VIGNETTE: false,
  59595. VIGNETTEBLENDMODEMULTIPLY: false,
  59596. VIGNETTEBLENDMODEOPAQUE: false,
  59597. TONEMAPPING: false,
  59598. CONTRAST: false,
  59599. COLORCURVES: false,
  59600. COLORGRADING: false,
  59601. COLORGRADING3D: false,
  59602. FROMLINEARSPACE: false,
  59603. SAMPLER3DGREENDEPTH: false,
  59604. SAMPLER3DBGRMAP: false,
  59605. IMAGEPROCESSINGPOSTPROCESS: false,
  59606. EXPOSURE: false,
  59607. };
  59608. // Setup the default processing configuration to the scene.
  59609. _this._attachImageProcessingConfiguration(null, true);
  59610. _this.imageProcessingConfiguration.applyByPostProcess = true;
  59611. _this.onApply = function (effect) {
  59612. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  59613. };
  59614. return _this;
  59615. }
  59616. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  59617. /**
  59618. * Gets the image processing configuration used either in this material.
  59619. */
  59620. get: function () {
  59621. return this._imageProcessingConfiguration;
  59622. },
  59623. /**
  59624. * Sets the Default image processing configuration used either in the this material.
  59625. *
  59626. * If sets to null, the scene one is in use.
  59627. */
  59628. set: function (value) {
  59629. this._attachImageProcessingConfiguration(value);
  59630. },
  59631. enumerable: true,
  59632. configurable: true
  59633. });
  59634. /**
  59635. * Attaches a new image processing configuration to the PBR Material.
  59636. * @param configuration
  59637. */
  59638. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  59639. var _this = this;
  59640. if (doNotBuild === void 0) { doNotBuild = false; }
  59641. if (configuration === this._imageProcessingConfiguration) {
  59642. return;
  59643. }
  59644. // Detaches observer.
  59645. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59646. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59647. }
  59648. // Pick the scene configuration if needed.
  59649. if (!configuration) {
  59650. var scene = null;
  59651. var engine = this.getEngine();
  59652. var camera = this.getCamera();
  59653. if (camera) {
  59654. scene = camera.getScene();
  59655. }
  59656. else if (engine && engine.scenes) {
  59657. var scenes = engine.scenes;
  59658. scene = scenes[scenes.length - 1];
  59659. }
  59660. else {
  59661. scene = BABYLON.Engine.LastCreatedScene;
  59662. }
  59663. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  59664. }
  59665. else {
  59666. this._imageProcessingConfiguration = configuration;
  59667. }
  59668. // Attaches observer.
  59669. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  59670. _this._updateParameters();
  59671. });
  59672. // Ensure the effect will be rebuilt.
  59673. if (!doNotBuild) {
  59674. this._updateParameters();
  59675. }
  59676. };
  59677. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  59678. /**
  59679. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59680. */
  59681. get: function () {
  59682. return this.imageProcessingConfiguration.colorCurves;
  59683. },
  59684. /**
  59685. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59686. */
  59687. set: function (value) {
  59688. this.imageProcessingConfiguration.colorCurves = value;
  59689. },
  59690. enumerable: true,
  59691. configurable: true
  59692. });
  59693. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  59694. /**
  59695. * Gets wether the color curves effect is enabled.
  59696. */
  59697. get: function () {
  59698. return this.imageProcessingConfiguration.colorCurvesEnabled;
  59699. },
  59700. /**
  59701. * Sets wether the color curves effect is enabled.
  59702. */
  59703. set: function (value) {
  59704. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  59705. },
  59706. enumerable: true,
  59707. configurable: true
  59708. });
  59709. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  59710. /**
  59711. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59712. */
  59713. get: function () {
  59714. return this.imageProcessingConfiguration.colorGradingTexture;
  59715. },
  59716. /**
  59717. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59718. */
  59719. set: function (value) {
  59720. this.imageProcessingConfiguration.colorGradingTexture = value;
  59721. },
  59722. enumerable: true,
  59723. configurable: true
  59724. });
  59725. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  59726. /**
  59727. * Gets wether the color grading effect is enabled.
  59728. */
  59729. get: function () {
  59730. return this.imageProcessingConfiguration.colorGradingEnabled;
  59731. },
  59732. /**
  59733. * Gets wether the color grading effect is enabled.
  59734. */
  59735. set: function (value) {
  59736. this.imageProcessingConfiguration.colorGradingEnabled = value;
  59737. },
  59738. enumerable: true,
  59739. configurable: true
  59740. });
  59741. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  59742. /**
  59743. * Gets exposure used in the effect.
  59744. */
  59745. get: function () {
  59746. return this.imageProcessingConfiguration.exposure;
  59747. },
  59748. /**
  59749. * Sets exposure used in the effect.
  59750. */
  59751. set: function (value) {
  59752. this.imageProcessingConfiguration.exposure = value;
  59753. },
  59754. enumerable: true,
  59755. configurable: true
  59756. });
  59757. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  59758. /**
  59759. * Gets wether tonemapping is enabled or not.
  59760. */
  59761. get: function () {
  59762. return this._imageProcessingConfiguration.toneMappingEnabled;
  59763. },
  59764. /**
  59765. * Sets wether tonemapping is enabled or not
  59766. */
  59767. set: function (value) {
  59768. this._imageProcessingConfiguration.toneMappingEnabled = value;
  59769. },
  59770. enumerable: true,
  59771. configurable: true
  59772. });
  59773. ;
  59774. ;
  59775. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  59776. /**
  59777. * Gets contrast used in the effect.
  59778. */
  59779. get: function () {
  59780. return this.imageProcessingConfiguration.contrast;
  59781. },
  59782. /**
  59783. * Sets contrast used in the effect.
  59784. */
  59785. set: function (value) {
  59786. this.imageProcessingConfiguration.contrast = value;
  59787. },
  59788. enumerable: true,
  59789. configurable: true
  59790. });
  59791. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  59792. /**
  59793. * Gets Vignette stretch size.
  59794. */
  59795. get: function () {
  59796. return this.imageProcessingConfiguration.vignetteStretch;
  59797. },
  59798. /**
  59799. * Sets Vignette stretch size.
  59800. */
  59801. set: function (value) {
  59802. this.imageProcessingConfiguration.vignetteStretch = value;
  59803. },
  59804. enumerable: true,
  59805. configurable: true
  59806. });
  59807. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  59808. /**
  59809. * Gets Vignette centre X Offset.
  59810. */
  59811. get: function () {
  59812. return this.imageProcessingConfiguration.vignetteCentreX;
  59813. },
  59814. /**
  59815. * Sets Vignette centre X Offset.
  59816. */
  59817. set: function (value) {
  59818. this.imageProcessingConfiguration.vignetteCentreX = value;
  59819. },
  59820. enumerable: true,
  59821. configurable: true
  59822. });
  59823. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  59824. /**
  59825. * Gets Vignette centre Y Offset.
  59826. */
  59827. get: function () {
  59828. return this.imageProcessingConfiguration.vignetteCentreY;
  59829. },
  59830. /**
  59831. * Sets Vignette centre Y Offset.
  59832. */
  59833. set: function (value) {
  59834. this.imageProcessingConfiguration.vignetteCentreY = value;
  59835. },
  59836. enumerable: true,
  59837. configurable: true
  59838. });
  59839. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  59840. /**
  59841. * Gets Vignette weight or intensity of the vignette effect.
  59842. */
  59843. get: function () {
  59844. return this.imageProcessingConfiguration.vignetteWeight;
  59845. },
  59846. /**
  59847. * Sets Vignette weight or intensity of the vignette effect.
  59848. */
  59849. set: function (value) {
  59850. this.imageProcessingConfiguration.vignetteWeight = value;
  59851. },
  59852. enumerable: true,
  59853. configurable: true
  59854. });
  59855. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  59856. /**
  59857. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  59858. * if vignetteEnabled is set to true.
  59859. */
  59860. get: function () {
  59861. return this.imageProcessingConfiguration.vignetteColor;
  59862. },
  59863. /**
  59864. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  59865. * if vignetteEnabled is set to true.
  59866. */
  59867. set: function (value) {
  59868. this.imageProcessingConfiguration.vignetteColor = value;
  59869. },
  59870. enumerable: true,
  59871. configurable: true
  59872. });
  59873. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  59874. /**
  59875. * Gets Camera field of view used by the Vignette effect.
  59876. */
  59877. get: function () {
  59878. return this.imageProcessingConfiguration.vignetteCameraFov;
  59879. },
  59880. /**
  59881. * Sets Camera field of view used by the Vignette effect.
  59882. */
  59883. set: function (value) {
  59884. this.imageProcessingConfiguration.vignetteCameraFov = value;
  59885. },
  59886. enumerable: true,
  59887. configurable: true
  59888. });
  59889. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  59890. /**
  59891. * Gets the vignette blend mode allowing different kind of effect.
  59892. */
  59893. get: function () {
  59894. return this.imageProcessingConfiguration.vignetteBlendMode;
  59895. },
  59896. /**
  59897. * Sets the vignette blend mode allowing different kind of effect.
  59898. */
  59899. set: function (value) {
  59900. this.imageProcessingConfiguration.vignetteBlendMode = value;
  59901. },
  59902. enumerable: true,
  59903. configurable: true
  59904. });
  59905. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  59906. /**
  59907. * Gets wether the vignette effect is enabled.
  59908. */
  59909. get: function () {
  59910. return this.imageProcessingConfiguration.vignetteEnabled;
  59911. },
  59912. /**
  59913. * Sets wether the vignette effect is enabled.
  59914. */
  59915. set: function (value) {
  59916. this.imageProcessingConfiguration.vignetteEnabled = value;
  59917. },
  59918. enumerable: true,
  59919. configurable: true
  59920. });
  59921. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  59922. /**
  59923. * Gets wether the input of the processing is in Gamma or Linear Space.
  59924. */
  59925. get: function () {
  59926. return this._fromLinearSpace;
  59927. },
  59928. /**
  59929. * Sets wether the input of the processing is in Gamma or Linear Space.
  59930. */
  59931. set: function (value) {
  59932. if (this._fromLinearSpace === value) {
  59933. return;
  59934. }
  59935. this._fromLinearSpace = value;
  59936. this._updateParameters();
  59937. },
  59938. enumerable: true,
  59939. configurable: true
  59940. });
  59941. ImageProcessingPostProcess.prototype.getClassName = function () {
  59942. return "ImageProcessingPostProcess";
  59943. };
  59944. ImageProcessingPostProcess.prototype._updateParameters = function () {
  59945. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  59946. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  59947. var defines = "";
  59948. for (var define in this._defines) {
  59949. if (this._defines[define]) {
  59950. defines += "#define " + define + ";\r\n";
  59951. }
  59952. }
  59953. var samplers = ["textureSampler"];
  59954. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  59955. var uniforms = ["scale"];
  59956. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  59957. this.updateEffect(defines, uniforms, samplers);
  59958. };
  59959. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  59960. _super.prototype.dispose.call(this, camera);
  59961. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59962. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59963. }
  59964. this.imageProcessingConfiguration.applyByPostProcess = false;
  59965. };
  59966. __decorate([
  59967. BABYLON.serialize()
  59968. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  59969. return ImageProcessingPostProcess;
  59970. }(BABYLON.PostProcess));
  59971. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  59972. })(BABYLON || (BABYLON = {}));
  59973. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  59974. var BABYLON;
  59975. (function (BABYLON) {
  59976. var BlurPostProcess = /** @class */ (function (_super) {
  59977. __extends(BlurPostProcess, _super);
  59978. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  59979. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59980. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59981. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  59982. _this.direction = direction;
  59983. _this._packedFloat = false;
  59984. _this.onApplyObservable.add(function (effect) {
  59985. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  59986. });
  59987. _this.kernel = kernel;
  59988. return _this;
  59989. }
  59990. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  59991. /**
  59992. * Gets the length in pixels of the blur sample region
  59993. */
  59994. get: function () {
  59995. return this._idealKernel;
  59996. },
  59997. /**
  59998. * Sets the length in pixels of the blur sample region
  59999. */
  60000. set: function (v) {
  60001. if (this._idealKernel === v) {
  60002. return;
  60003. }
  60004. v = Math.max(v, 1);
  60005. this._idealKernel = v;
  60006. this._kernel = this._nearestBestKernel(v);
  60007. this._updateParameters();
  60008. },
  60009. enumerable: true,
  60010. configurable: true
  60011. });
  60012. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60013. /**
  60014. * Gets wether or not the blur is unpacking/repacking floats
  60015. */
  60016. get: function () {
  60017. return this._packedFloat;
  60018. },
  60019. /**
  60020. * Sets wether or not the blur needs to unpack/repack floats
  60021. */
  60022. set: function (v) {
  60023. if (this._packedFloat === v) {
  60024. return;
  60025. }
  60026. this._packedFloat = v;
  60027. this._updateParameters();
  60028. },
  60029. enumerable: true,
  60030. configurable: true
  60031. });
  60032. BlurPostProcess.prototype._updateParameters = function () {
  60033. // Generate sampling offsets and weights
  60034. var N = this._kernel;
  60035. var centerIndex = (N - 1) / 2;
  60036. // Generate Gaussian sampling weights over kernel
  60037. var offsets = [];
  60038. var weights = [];
  60039. var totalWeight = 0;
  60040. for (var i = 0; i < N; i++) {
  60041. var u = i / (N - 1);
  60042. var w = this._gaussianWeight(u * 2.0 - 1);
  60043. offsets[i] = (i - centerIndex);
  60044. weights[i] = w;
  60045. totalWeight += w;
  60046. }
  60047. // Normalize weights
  60048. for (var i = 0; i < weights.length; i++) {
  60049. weights[i] /= totalWeight;
  60050. }
  60051. // Optimize: combine samples to take advantage of hardware linear sampling
  60052. // Walk from left to center, combining pairs (symmetrically)
  60053. var linearSamplingWeights = [];
  60054. var linearSamplingOffsets = [];
  60055. var linearSamplingMap = [];
  60056. for (var i = 0; i <= centerIndex; i += 2) {
  60057. var j = Math.min(i + 1, Math.floor(centerIndex));
  60058. var singleCenterSample = i === j;
  60059. if (singleCenterSample) {
  60060. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60061. }
  60062. else {
  60063. var sharedCell = j === centerIndex;
  60064. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60065. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60066. if (offsetLinear === 0) {
  60067. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60068. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60069. }
  60070. else {
  60071. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60072. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60073. }
  60074. }
  60075. }
  60076. for (var i = 0; i < linearSamplingMap.length; i++) {
  60077. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60078. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60079. }
  60080. // Replace with optimized
  60081. offsets = linearSamplingOffsets;
  60082. weights = linearSamplingWeights;
  60083. // Generate shaders
  60084. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  60085. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  60086. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  60087. var defines = "";
  60088. for (var i = 0; i < varyingCount; i++) {
  60089. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  60090. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  60091. }
  60092. var depCount = 0;
  60093. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  60094. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  60095. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  60096. depCount++;
  60097. }
  60098. if (this.packedFloat) {
  60099. defines += "#define PACKEDFLOAT 1";
  60100. }
  60101. this.updateEffect(defines, null, null, {
  60102. varyingCount: varyingCount,
  60103. depCount: depCount
  60104. });
  60105. };
  60106. /**
  60107. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  60108. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  60109. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  60110. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  60111. * The gaps between physical kernels are compensated for in the weighting of the samples
  60112. * @param idealKernel Ideal blur kernel.
  60113. * @return Nearest best kernel.
  60114. */
  60115. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  60116. var v = Math.round(idealKernel);
  60117. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  60118. var k = _a[_i];
  60119. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  60120. return Math.max(k, 3);
  60121. }
  60122. }
  60123. return Math.max(v, 3);
  60124. };
  60125. /**
  60126. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  60127. * @param x The point on the Gaussian distribution to sample.
  60128. * @return the value of the Gaussian function at x.
  60129. */
  60130. BlurPostProcess.prototype._gaussianWeight = function (x) {
  60131. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  60132. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  60133. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  60134. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  60135. // truncated at around 1.3% of peak strength.
  60136. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  60137. var sigma = (1 / 3);
  60138. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  60139. var exponent = -((x * x) / (2.0 * sigma * sigma));
  60140. var weight = (1.0 / denominator) * Math.exp(exponent);
  60141. return weight;
  60142. };
  60143. /**
  60144. * Generates a string that can be used as a floating point number in GLSL.
  60145. * @param x Value to print.
  60146. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  60147. * @return GLSL float string.
  60148. */
  60149. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  60150. if (decimalFigures === void 0) { decimalFigures = 8; }
  60151. return x.toFixed(decimalFigures).replace(/0+$/, '');
  60152. };
  60153. return BlurPostProcess;
  60154. }(BABYLON.PostProcess));
  60155. BABYLON.BlurPostProcess = BlurPostProcess;
  60156. })(BABYLON || (BABYLON = {}));
  60157. //# sourceMappingURL=babylon.blurPostProcess.js.map
  60158. var BABYLON;
  60159. (function (BABYLON) {
  60160. var Bone = /** @class */ (function (_super) {
  60161. __extends(Bone, _super);
  60162. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  60163. if (parentBone === void 0) { parentBone = null; }
  60164. if (localMatrix === void 0) { localMatrix = null; }
  60165. if (restPose === void 0) { restPose = null; }
  60166. if (baseMatrix === void 0) { baseMatrix = null; }
  60167. if (index === void 0) { index = null; }
  60168. var _this = _super.call(this, name, skeleton.getScene()) || this;
  60169. _this.name = name;
  60170. _this.children = new Array();
  60171. _this.animations = new Array();
  60172. // Set this value to map this bone to a different index in the transform matrices.
  60173. // Set this value to -1 to exclude the bone from the transform matrices.
  60174. _this._index = null;
  60175. _this._worldTransform = new BABYLON.Matrix();
  60176. _this._absoluteTransform = new BABYLON.Matrix();
  60177. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  60178. _this._scaleMatrix = BABYLON.Matrix.Identity();
  60179. _this._scaleVector = BABYLON.Vector3.One();
  60180. _this._negateScaleChildren = BABYLON.Vector3.One();
  60181. _this._scalingDeterminant = 1;
  60182. _this._skeleton = skeleton;
  60183. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  60184. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  60185. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  60186. _this._index = index;
  60187. skeleton.bones.push(_this);
  60188. _this.setParent(parentBone, false);
  60189. _this._updateDifferenceMatrix();
  60190. return _this;
  60191. }
  60192. Object.defineProperty(Bone.prototype, "_matrix", {
  60193. get: function () {
  60194. return this._localMatrix;
  60195. },
  60196. set: function (val) {
  60197. if (this._localMatrix) {
  60198. this._localMatrix.copyFrom(val);
  60199. }
  60200. else {
  60201. this._localMatrix = val;
  60202. }
  60203. },
  60204. enumerable: true,
  60205. configurable: true
  60206. });
  60207. // Members
  60208. Bone.prototype.getSkeleton = function () {
  60209. return this._skeleton;
  60210. };
  60211. Bone.prototype.getParent = function () {
  60212. return this._parent;
  60213. };
  60214. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  60215. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60216. if (this._parent === parent) {
  60217. return;
  60218. }
  60219. if (this._parent) {
  60220. var index = this._parent.children.indexOf(this);
  60221. if (index !== -1) {
  60222. this._parent.children.splice(index, 1);
  60223. }
  60224. }
  60225. this._parent = parent;
  60226. if (this._parent) {
  60227. this._parent.children.push(this);
  60228. }
  60229. if (updateDifferenceMatrix) {
  60230. this._updateDifferenceMatrix();
  60231. }
  60232. };
  60233. Bone.prototype.getLocalMatrix = function () {
  60234. return this._localMatrix;
  60235. };
  60236. Bone.prototype.getBaseMatrix = function () {
  60237. return this._baseMatrix;
  60238. };
  60239. Bone.prototype.getRestPose = function () {
  60240. return this._restPose;
  60241. };
  60242. Bone.prototype.returnToRest = function () {
  60243. this.updateMatrix(this._restPose.clone());
  60244. };
  60245. Bone.prototype.getWorldMatrix = function () {
  60246. return this._worldTransform;
  60247. };
  60248. Bone.prototype.getInvertedAbsoluteTransform = function () {
  60249. return this._invertedAbsoluteTransform;
  60250. };
  60251. Bone.prototype.getAbsoluteTransform = function () {
  60252. return this._absoluteTransform;
  60253. };
  60254. Object.defineProperty(Bone.prototype, "position", {
  60255. // Properties (matches AbstractMesh properties)
  60256. get: function () {
  60257. return this.getPosition();
  60258. },
  60259. set: function (newPosition) {
  60260. this.setPosition(newPosition);
  60261. },
  60262. enumerable: true,
  60263. configurable: true
  60264. });
  60265. Object.defineProperty(Bone.prototype, "rotation", {
  60266. get: function () {
  60267. return this.getRotation();
  60268. },
  60269. set: function (newRotation) {
  60270. this.setRotation(newRotation);
  60271. },
  60272. enumerable: true,
  60273. configurable: true
  60274. });
  60275. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  60276. get: function () {
  60277. return this.getRotationQuaternion();
  60278. },
  60279. set: function (newRotation) {
  60280. this.setRotationQuaternion(newRotation);
  60281. },
  60282. enumerable: true,
  60283. configurable: true
  60284. });
  60285. Object.defineProperty(Bone.prototype, "scaling", {
  60286. get: function () {
  60287. return this.getScale();
  60288. },
  60289. set: function (newScaling) {
  60290. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  60291. },
  60292. enumerable: true,
  60293. configurable: true
  60294. });
  60295. // Methods
  60296. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  60297. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60298. this._baseMatrix = matrix.clone();
  60299. this._localMatrix = matrix.clone();
  60300. this._skeleton._markAsDirty();
  60301. if (updateDifferenceMatrix) {
  60302. this._updateDifferenceMatrix();
  60303. }
  60304. };
  60305. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  60306. if (!rootMatrix) {
  60307. rootMatrix = this._baseMatrix;
  60308. }
  60309. if (this._parent) {
  60310. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60311. }
  60312. else {
  60313. this._absoluteTransform.copyFrom(rootMatrix);
  60314. }
  60315. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  60316. for (var index = 0; index < this.children.length; index++) {
  60317. this.children[index]._updateDifferenceMatrix();
  60318. }
  60319. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  60320. };
  60321. Bone.prototype.markAsDirty = function () {
  60322. this._currentRenderId++;
  60323. this._skeleton._markAsDirty();
  60324. };
  60325. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  60326. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60327. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  60328. // all animation may be coming from a library skeleton, so may need to create animation
  60329. if (this.animations.length === 0) {
  60330. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  60331. this.animations[0].setKeys([]);
  60332. }
  60333. // get animation info / verify there is such a range from the source bone
  60334. var sourceRange = source.animations[0].getRange(rangeName);
  60335. if (!sourceRange) {
  60336. return false;
  60337. }
  60338. var from = sourceRange.from;
  60339. var to = sourceRange.to;
  60340. var sourceKeys = source.animations[0].getKeys();
  60341. // rescaling prep
  60342. var sourceBoneLength = source.length;
  60343. var sourceParent = source.getParent();
  60344. var parent = this.getParent();
  60345. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  60346. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  60347. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  60348. var destKeys = this.animations[0].getKeys();
  60349. // loop vars declaration
  60350. var orig;
  60351. var origTranslation;
  60352. var mat;
  60353. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  60354. orig = sourceKeys[key];
  60355. if (orig.frame >= from && orig.frame <= to) {
  60356. if (rescaleAsRequired) {
  60357. mat = orig.value.clone();
  60358. // scale based on parent ratio, when bone has parent
  60359. if (parentScalingReqd) {
  60360. origTranslation = mat.getTranslation();
  60361. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  60362. // scale based on skeleton dimension ratio when root bone, and value is passed
  60363. }
  60364. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  60365. origTranslation = mat.getTranslation();
  60366. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  60367. // use original when root bone, and no data for skelDimensionsRatio
  60368. }
  60369. else {
  60370. mat = orig.value;
  60371. }
  60372. }
  60373. else {
  60374. mat = orig.value;
  60375. }
  60376. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  60377. }
  60378. }
  60379. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  60380. return true;
  60381. };
  60382. /**
  60383. * Translate the bone in local or world space.
  60384. * @param vec The amount to translate the bone.
  60385. * @param space The space that the translation is in.
  60386. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60387. */
  60388. Bone.prototype.translate = function (vec, space, mesh) {
  60389. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60390. var lm = this.getLocalMatrix();
  60391. if (space == BABYLON.Space.LOCAL) {
  60392. lm.m[12] += vec.x;
  60393. lm.m[13] += vec.y;
  60394. lm.m[14] += vec.z;
  60395. }
  60396. else {
  60397. var wm = null;
  60398. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60399. if (mesh) {
  60400. wm = mesh.getWorldMatrix();
  60401. }
  60402. this._skeleton.computeAbsoluteTransforms();
  60403. var tmat = Bone._tmpMats[0];
  60404. var tvec = Bone._tmpVecs[0];
  60405. if (this._parent) {
  60406. if (mesh && wm) {
  60407. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60408. tmat.multiplyToRef(wm, tmat);
  60409. }
  60410. else {
  60411. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60412. }
  60413. }
  60414. tmat.m[12] = 0;
  60415. tmat.m[13] = 0;
  60416. tmat.m[14] = 0;
  60417. tmat.invert();
  60418. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  60419. lm.m[12] += tvec.x;
  60420. lm.m[13] += tvec.y;
  60421. lm.m[14] += tvec.z;
  60422. }
  60423. this.markAsDirty();
  60424. };
  60425. /**
  60426. * Set the postion of the bone in local or world space.
  60427. * @param position The position to set the bone.
  60428. * @param space The space that the position is in.
  60429. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60430. */
  60431. Bone.prototype.setPosition = function (position, space, mesh) {
  60432. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60433. var lm = this.getLocalMatrix();
  60434. if (space == BABYLON.Space.LOCAL) {
  60435. lm.m[12] = position.x;
  60436. lm.m[13] = position.y;
  60437. lm.m[14] = position.z;
  60438. }
  60439. else {
  60440. var wm = null;
  60441. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60442. if (mesh) {
  60443. wm = mesh.getWorldMatrix();
  60444. }
  60445. this._skeleton.computeAbsoluteTransforms();
  60446. var tmat = Bone._tmpMats[0];
  60447. var vec = Bone._tmpVecs[0];
  60448. if (this._parent) {
  60449. if (mesh && wm) {
  60450. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60451. tmat.multiplyToRef(wm, tmat);
  60452. }
  60453. else {
  60454. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60455. }
  60456. }
  60457. tmat.invert();
  60458. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  60459. lm.m[12] = vec.x;
  60460. lm.m[13] = vec.y;
  60461. lm.m[14] = vec.z;
  60462. }
  60463. this.markAsDirty();
  60464. };
  60465. /**
  60466. * Set the absolute postion of the bone (world space).
  60467. * @param position The position to set the bone.
  60468. * @param mesh The mesh that this bone is attached to.
  60469. */
  60470. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  60471. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  60472. };
  60473. /**
  60474. * Set the scale of the bone on the x, y and z axes.
  60475. * @param x The scale of the bone on the x axis.
  60476. * @param x The scale of the bone on the y axis.
  60477. * @param z The scale of the bone on the z axis.
  60478. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60479. */
  60480. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  60481. if (scaleChildren === void 0) { scaleChildren = false; }
  60482. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  60483. if (!scaleChildren) {
  60484. this._negateScaleChildren.x = 1 / x;
  60485. this._negateScaleChildren.y = 1 / y;
  60486. this._negateScaleChildren.z = 1 / z;
  60487. }
  60488. this._syncScaleVector();
  60489. }
  60490. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  60491. };
  60492. /**
  60493. * Scale the bone on the x, y and z axes.
  60494. * @param x The amount to scale the bone on the x axis.
  60495. * @param x The amount to scale the bone on the y axis.
  60496. * @param z The amount to scale the bone on the z axis.
  60497. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60498. */
  60499. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  60500. if (scaleChildren === void 0) { scaleChildren = false; }
  60501. var locMat = this.getLocalMatrix();
  60502. var origLocMat = Bone._tmpMats[0];
  60503. origLocMat.copyFrom(locMat);
  60504. var origLocMatInv = Bone._tmpMats[1];
  60505. origLocMatInv.copyFrom(origLocMat);
  60506. origLocMatInv.invert();
  60507. var scaleMat = Bone._tmpMats[2];
  60508. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  60509. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  60510. this._scaleVector.x *= x;
  60511. this._scaleVector.y *= y;
  60512. this._scaleVector.z *= z;
  60513. locMat.multiplyToRef(origLocMatInv, locMat);
  60514. locMat.multiplyToRef(scaleMat, locMat);
  60515. locMat.multiplyToRef(origLocMat, locMat);
  60516. var parent = this.getParent();
  60517. if (parent) {
  60518. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  60519. }
  60520. else {
  60521. this.getAbsoluteTransform().copyFrom(locMat);
  60522. }
  60523. var len = this.children.length;
  60524. scaleMat.invert();
  60525. for (var i = 0; i < len; i++) {
  60526. var child = this.children[i];
  60527. var cm = child.getLocalMatrix();
  60528. cm.multiplyToRef(scaleMat, cm);
  60529. var lm = child.getLocalMatrix();
  60530. lm.m[12] *= x;
  60531. lm.m[13] *= y;
  60532. lm.m[14] *= z;
  60533. }
  60534. this.computeAbsoluteTransforms();
  60535. if (scaleChildren) {
  60536. for (var i = 0; i < len; i++) {
  60537. this.children[i].scale(x, y, z, scaleChildren);
  60538. }
  60539. }
  60540. this.markAsDirty();
  60541. };
  60542. /**
  60543. * Set the yaw, pitch, and roll of the bone in local or world space.
  60544. * @param yaw The rotation of the bone on the y axis.
  60545. * @param pitch The rotation of the bone on the x axis.
  60546. * @param roll The rotation of the bone on the z axis.
  60547. * @param space The space that the axes of rotation are in.
  60548. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60549. */
  60550. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  60551. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60552. var rotMat = Bone._tmpMats[0];
  60553. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  60554. var rotMatInv = Bone._tmpMats[1];
  60555. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60556. rotMatInv.multiplyToRef(rotMat, rotMat);
  60557. this._rotateWithMatrix(rotMat, space, mesh);
  60558. };
  60559. /**
  60560. * Rotate the bone on an axis in local or world space.
  60561. * @param axis The axis to rotate the bone on.
  60562. * @param amount The amount to rotate the bone.
  60563. * @param space The space that the axis is in.
  60564. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60565. */
  60566. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  60567. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60568. var rmat = Bone._tmpMats[0];
  60569. rmat.m[12] = 0;
  60570. rmat.m[13] = 0;
  60571. rmat.m[14] = 0;
  60572. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  60573. this._rotateWithMatrix(rmat, space, mesh);
  60574. };
  60575. /**
  60576. * Set the rotation of the bone to a particular axis angle in local or world space.
  60577. * @param axis The axis to rotate the bone on.
  60578. * @param angle The angle that the bone should be rotated to.
  60579. * @param space The space that the axis is in.
  60580. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60581. */
  60582. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  60583. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60584. var rotMat = Bone._tmpMats[0];
  60585. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  60586. var rotMatInv = Bone._tmpMats[1];
  60587. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60588. rotMatInv.multiplyToRef(rotMat, rotMat);
  60589. this._rotateWithMatrix(rotMat, space, mesh);
  60590. };
  60591. /**
  60592. * Set the euler rotation of the bone in local of world space.
  60593. * @param rotation The euler rotation that the bone should be set to.
  60594. * @param space The space that the rotation is in.
  60595. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60596. */
  60597. Bone.prototype.setRotation = function (rotation, space, mesh) {
  60598. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60599. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  60600. };
  60601. /**
  60602. * Set the quaternion rotation of the bone in local of world space.
  60603. * @param quat The quaternion rotation that the bone should be set to.
  60604. * @param space The space that the rotation is in.
  60605. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60606. */
  60607. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  60608. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60609. var rotMatInv = Bone._tmpMats[0];
  60610. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60611. var rotMat = Bone._tmpMats[1];
  60612. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  60613. rotMatInv.multiplyToRef(rotMat, rotMat);
  60614. this._rotateWithMatrix(rotMat, space, mesh);
  60615. };
  60616. /**
  60617. * Set the rotation matrix of the bone in local of world space.
  60618. * @param rotMat The rotation matrix that the bone should be set to.
  60619. * @param space The space that the rotation is in.
  60620. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60621. */
  60622. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  60623. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60624. var rotMatInv = Bone._tmpMats[0];
  60625. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60626. var rotMat2 = Bone._tmpMats[1];
  60627. rotMat2.copyFrom(rotMat);
  60628. rotMatInv.multiplyToRef(rotMat, rotMat2);
  60629. this._rotateWithMatrix(rotMat2, space, mesh);
  60630. };
  60631. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  60632. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60633. var lmat = this.getLocalMatrix();
  60634. var lx = lmat.m[12];
  60635. var ly = lmat.m[13];
  60636. var lz = lmat.m[14];
  60637. var parent = this.getParent();
  60638. var parentScale = Bone._tmpMats[3];
  60639. var parentScaleInv = Bone._tmpMats[4];
  60640. if (parent) {
  60641. if (space == BABYLON.Space.WORLD) {
  60642. if (mesh) {
  60643. parentScale.copyFrom(mesh.getWorldMatrix());
  60644. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  60645. }
  60646. else {
  60647. parentScale.copyFrom(parent.getAbsoluteTransform());
  60648. }
  60649. }
  60650. else {
  60651. parentScale = parent._scaleMatrix;
  60652. }
  60653. parentScaleInv.copyFrom(parentScale);
  60654. parentScaleInv.invert();
  60655. lmat.multiplyToRef(parentScale, lmat);
  60656. lmat.multiplyToRef(rmat, lmat);
  60657. lmat.multiplyToRef(parentScaleInv, lmat);
  60658. }
  60659. else {
  60660. if (space == BABYLON.Space.WORLD && mesh) {
  60661. parentScale.copyFrom(mesh.getWorldMatrix());
  60662. parentScaleInv.copyFrom(parentScale);
  60663. parentScaleInv.invert();
  60664. lmat.multiplyToRef(parentScale, lmat);
  60665. lmat.multiplyToRef(rmat, lmat);
  60666. lmat.multiplyToRef(parentScaleInv, lmat);
  60667. }
  60668. else {
  60669. lmat.multiplyToRef(rmat, lmat);
  60670. }
  60671. }
  60672. lmat.m[12] = lx;
  60673. lmat.m[13] = ly;
  60674. lmat.m[14] = lz;
  60675. this.computeAbsoluteTransforms();
  60676. this.markAsDirty();
  60677. };
  60678. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  60679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60680. if (space == BABYLON.Space.WORLD) {
  60681. var scaleMatrix = Bone._tmpMats[2];
  60682. scaleMatrix.copyFrom(this._scaleMatrix);
  60683. rotMatInv.copyFrom(this.getAbsoluteTransform());
  60684. if (mesh) {
  60685. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  60686. var meshScale = Bone._tmpMats[3];
  60687. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  60688. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  60689. }
  60690. rotMatInv.invert();
  60691. scaleMatrix.m[0] *= this._scalingDeterminant;
  60692. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60693. }
  60694. else {
  60695. rotMatInv.copyFrom(this.getLocalMatrix());
  60696. rotMatInv.invert();
  60697. var scaleMatrix = Bone._tmpMats[2];
  60698. scaleMatrix.copyFrom(this._scaleMatrix);
  60699. if (this._parent) {
  60700. var pscaleMatrix = Bone._tmpMats[3];
  60701. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  60702. pscaleMatrix.invert();
  60703. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  60704. }
  60705. else {
  60706. scaleMatrix.m[0] *= this._scalingDeterminant;
  60707. }
  60708. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60709. }
  60710. };
  60711. /**
  60712. * Get the scale of the bone
  60713. * @returns the scale of the bone
  60714. */
  60715. Bone.prototype.getScale = function () {
  60716. return this._scaleVector.clone();
  60717. };
  60718. /**
  60719. * Copy the scale of the bone to a vector3.
  60720. * @param result The vector3 to copy the scale to
  60721. */
  60722. Bone.prototype.getScaleToRef = function (result) {
  60723. result.copyFrom(this._scaleVector);
  60724. };
  60725. /**
  60726. * Get the position of the bone in local or world space.
  60727. * @param space The space that the returned position is in.
  60728. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60729. * @returns The position of the bone
  60730. */
  60731. Bone.prototype.getPosition = function (space, mesh) {
  60732. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60733. if (mesh === void 0) { mesh = null; }
  60734. var pos = BABYLON.Vector3.Zero();
  60735. this.getPositionToRef(space, mesh, pos);
  60736. return pos;
  60737. };
  60738. /**
  60739. * Copy the position of the bone to a vector3 in local or world space.
  60740. * @param space The space that the returned position is in.
  60741. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60742. * @param result The vector3 to copy the position to.
  60743. */
  60744. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  60745. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60746. if (space == BABYLON.Space.LOCAL) {
  60747. var lm = this.getLocalMatrix();
  60748. result.x = lm.m[12];
  60749. result.y = lm.m[13];
  60750. result.z = lm.m[14];
  60751. }
  60752. else {
  60753. var wm = null;
  60754. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60755. if (mesh) {
  60756. wm = mesh.getWorldMatrix();
  60757. }
  60758. this._skeleton.computeAbsoluteTransforms();
  60759. var tmat = Bone._tmpMats[0];
  60760. if (mesh && wm) {
  60761. tmat.copyFrom(this.getAbsoluteTransform());
  60762. tmat.multiplyToRef(wm, tmat);
  60763. }
  60764. else {
  60765. tmat = this.getAbsoluteTransform();
  60766. }
  60767. result.x = tmat.m[12];
  60768. result.y = tmat.m[13];
  60769. result.z = tmat.m[14];
  60770. }
  60771. };
  60772. /**
  60773. * Get the absolute position of the bone (world space).
  60774. * @param mesh The mesh that this bone is attached to.
  60775. * @returns The absolute position of the bone
  60776. */
  60777. Bone.prototype.getAbsolutePosition = function (mesh) {
  60778. if (mesh === void 0) { mesh = null; }
  60779. var pos = BABYLON.Vector3.Zero();
  60780. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  60781. return pos;
  60782. };
  60783. /**
  60784. * Copy the absolute position of the bone (world space) to the result param.
  60785. * @param mesh The mesh that this bone is attached to.
  60786. * @param result The vector3 to copy the absolute position to.
  60787. */
  60788. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  60789. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  60790. };
  60791. /**
  60792. * Compute the absolute transforms of this bone and its children.
  60793. */
  60794. Bone.prototype.computeAbsoluteTransforms = function () {
  60795. if (this._parent) {
  60796. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60797. }
  60798. else {
  60799. this._absoluteTransform.copyFrom(this._localMatrix);
  60800. var poseMatrix = this._skeleton.getPoseMatrix();
  60801. if (poseMatrix) {
  60802. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  60803. }
  60804. }
  60805. var children = this.children;
  60806. var len = children.length;
  60807. for (var i = 0; i < len; i++) {
  60808. children[i].computeAbsoluteTransforms();
  60809. }
  60810. };
  60811. Bone.prototype._syncScaleVector = function () {
  60812. var lm = this.getLocalMatrix();
  60813. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  60814. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  60815. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  60816. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  60817. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  60818. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  60819. this._scaleVector.x = xs * Math.sqrt(xsq);
  60820. this._scaleVector.y = ys * Math.sqrt(ysq);
  60821. this._scaleVector.z = zs * Math.sqrt(zsq);
  60822. if (this._parent) {
  60823. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  60824. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  60825. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  60826. }
  60827. 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);
  60828. };
  60829. /**
  60830. * Get the world direction from an axis that is in the local space of the bone.
  60831. * @param localAxis The local direction that is used to compute the world direction.
  60832. * @param mesh The mesh that this bone is attached to.
  60833. * @returns The world direction
  60834. */
  60835. Bone.prototype.getDirection = function (localAxis, mesh) {
  60836. if (mesh === void 0) { mesh = null; }
  60837. var result = BABYLON.Vector3.Zero();
  60838. this.getDirectionToRef(localAxis, mesh, result);
  60839. return result;
  60840. };
  60841. /**
  60842. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  60843. * @param localAxis The local direction that is used to compute the world direction.
  60844. * @param mesh The mesh that this bone is attached to.
  60845. * @param result The vector3 that the world direction will be copied to.
  60846. */
  60847. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  60848. if (mesh === void 0) { mesh = null; }
  60849. var wm = null;
  60850. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60851. if (mesh) {
  60852. wm = mesh.getWorldMatrix();
  60853. }
  60854. this._skeleton.computeAbsoluteTransforms();
  60855. var mat = Bone._tmpMats[0];
  60856. mat.copyFrom(this.getAbsoluteTransform());
  60857. if (mesh && wm) {
  60858. mat.multiplyToRef(wm, mat);
  60859. }
  60860. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  60861. result.normalize();
  60862. };
  60863. /**
  60864. * Get the euler rotation of the bone in local or world space.
  60865. * @param space The space that the rotation should be in.
  60866. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60867. * @returns The euler rotation
  60868. */
  60869. Bone.prototype.getRotation = function (space, mesh) {
  60870. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60871. if (mesh === void 0) { mesh = null; }
  60872. var result = BABYLON.Vector3.Zero();
  60873. this.getRotationToRef(space, mesh, result);
  60874. return result;
  60875. };
  60876. /**
  60877. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  60878. * @param space The space that the rotation should be in.
  60879. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60880. * @param result The vector3 that the rotation should be copied to.
  60881. */
  60882. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  60883. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60884. if (mesh === void 0) { mesh = null; }
  60885. var quat = Bone._tmpQuat;
  60886. this.getRotationQuaternionToRef(space, mesh, quat);
  60887. quat.toEulerAnglesToRef(result);
  60888. };
  60889. /**
  60890. * Get the quaternion rotation of the bone in either local or world space.
  60891. * @param space The space that the rotation should be in.
  60892. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60893. * @returns The quaternion rotation
  60894. */
  60895. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  60896. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60897. if (mesh === void 0) { mesh = null; }
  60898. var result = BABYLON.Quaternion.Identity();
  60899. this.getRotationQuaternionToRef(space, mesh, result);
  60900. return result;
  60901. };
  60902. /**
  60903. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  60904. * @param space The space that the rotation should be in.
  60905. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60906. * @param result The quaternion that the rotation should be copied to.
  60907. */
  60908. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  60909. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60910. if (mesh === void 0) { mesh = null; }
  60911. if (space == BABYLON.Space.LOCAL) {
  60912. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  60913. }
  60914. else {
  60915. var mat = Bone._tmpMats[0];
  60916. var amat = this.getAbsoluteTransform();
  60917. if (mesh) {
  60918. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  60919. }
  60920. else {
  60921. mat.copyFrom(amat);
  60922. }
  60923. mat.m[0] *= this._scalingDeterminant;
  60924. mat.m[1] *= this._scalingDeterminant;
  60925. mat.m[2] *= this._scalingDeterminant;
  60926. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  60927. }
  60928. };
  60929. /**
  60930. * Get the rotation matrix of the bone in local or world space.
  60931. * @param space The space that the rotation should be in.
  60932. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60933. * @returns The rotation matrix
  60934. */
  60935. Bone.prototype.getRotationMatrix = function (space, mesh) {
  60936. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60937. var result = BABYLON.Matrix.Identity();
  60938. this.getRotationMatrixToRef(space, mesh, result);
  60939. return result;
  60940. };
  60941. /**
  60942. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  60943. * @param space The space that the rotation should be in.
  60944. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60945. * @param result The quaternion that the rotation should be copied to.
  60946. */
  60947. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  60948. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60949. if (space == BABYLON.Space.LOCAL) {
  60950. this.getLocalMatrix().getRotationMatrixToRef(result);
  60951. }
  60952. else {
  60953. var mat = Bone._tmpMats[0];
  60954. var amat = this.getAbsoluteTransform();
  60955. if (mesh) {
  60956. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  60957. }
  60958. else {
  60959. mat.copyFrom(amat);
  60960. }
  60961. mat.m[0] *= this._scalingDeterminant;
  60962. mat.m[1] *= this._scalingDeterminant;
  60963. mat.m[2] *= this._scalingDeterminant;
  60964. mat.getRotationMatrixToRef(result);
  60965. }
  60966. };
  60967. /**
  60968. * Get the world position of a point that is in the local space of the bone.
  60969. * @param position The local position
  60970. * @param mesh The mesh that this bone is attached to.
  60971. * @returns The world position
  60972. */
  60973. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  60974. if (mesh === void 0) { mesh = null; }
  60975. var result = BABYLON.Vector3.Zero();
  60976. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  60977. return result;
  60978. };
  60979. /**
  60980. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  60981. * @param position The local position
  60982. * @param mesh The mesh that this bone is attached to.
  60983. * @param result The vector3 that the world position should be copied to.
  60984. */
  60985. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  60986. if (mesh === void 0) { mesh = null; }
  60987. var wm = null;
  60988. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60989. if (mesh) {
  60990. wm = mesh.getWorldMatrix();
  60991. }
  60992. this._skeleton.computeAbsoluteTransforms();
  60993. var tmat = Bone._tmpMats[0];
  60994. if (mesh && wm) {
  60995. tmat.copyFrom(this.getAbsoluteTransform());
  60996. tmat.multiplyToRef(wm, tmat);
  60997. }
  60998. else {
  60999. tmat = this.getAbsoluteTransform();
  61000. }
  61001. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61002. };
  61003. /**
  61004. * Get the local position of a point that is in world space.
  61005. * @param position The world position
  61006. * @param mesh The mesh that this bone is attached to.
  61007. * @returns The local position
  61008. */
  61009. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61010. if (mesh === void 0) { mesh = null; }
  61011. var result = BABYLON.Vector3.Zero();
  61012. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61013. return result;
  61014. };
  61015. /**
  61016. * Get the local position of a point that is in world space and copy it to the result param.
  61017. * @param position The world position
  61018. * @param mesh The mesh that this bone is attached to.
  61019. * @param result The vector3 that the local position should be copied to.
  61020. */
  61021. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61022. if (mesh === void 0) { mesh = null; }
  61023. var wm = null;
  61024. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61025. if (mesh) {
  61026. wm = mesh.getWorldMatrix();
  61027. }
  61028. this._skeleton.computeAbsoluteTransforms();
  61029. var tmat = Bone._tmpMats[0];
  61030. tmat.copyFrom(this.getAbsoluteTransform());
  61031. if (mesh && wm) {
  61032. tmat.multiplyToRef(wm, tmat);
  61033. }
  61034. tmat.invert();
  61035. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61036. };
  61037. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61038. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61039. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61040. return Bone;
  61041. }(BABYLON.Node));
  61042. BABYLON.Bone = Bone;
  61043. })(BABYLON || (BABYLON = {}));
  61044. //# sourceMappingURL=babylon.bone.js.map
  61045. var BABYLON;
  61046. (function (BABYLON) {
  61047. var BoneIKController = /** @class */ (function () {
  61048. function BoneIKController(mesh, bone, options) {
  61049. this.targetPosition = BABYLON.Vector3.Zero();
  61050. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61051. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61052. this.poleAngle = 0;
  61053. this.slerpAmount = 1;
  61054. this._bone1Quat = BABYLON.Quaternion.Identity();
  61055. this._bone1Mat = BABYLON.Matrix.Identity();
  61056. this._bone2Ang = Math.PI;
  61057. this._maxAngle = Math.PI;
  61058. this._rightHandedSystem = false;
  61059. this._bendAxis = BABYLON.Vector3.Right();
  61060. this._slerping = false;
  61061. this._adjustRoll = 0;
  61062. this._bone2 = bone;
  61063. this._bone1 = bone.getParent();
  61064. if (!this._bone1) {
  61065. return;
  61066. }
  61067. this.mesh = mesh;
  61068. var bonePos = bone.getPosition();
  61069. if (bone.getAbsoluteTransform().determinant() > 0) {
  61070. this._rightHandedSystem = true;
  61071. this._bendAxis.x = 0;
  61072. this._bendAxis.y = 0;
  61073. this._bendAxis.z = -1;
  61074. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61075. this._adjustRoll = Math.PI * .5;
  61076. this._bendAxis.z = 1;
  61077. }
  61078. }
  61079. if (this._bone1.length) {
  61080. var boneScale1 = this._bone1.getScale();
  61081. var boneScale2 = this._bone2.getScale();
  61082. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  61083. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  61084. }
  61085. else if (this._bone1.children[0]) {
  61086. mesh.computeWorldMatrix(true);
  61087. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  61088. var pos2 = this._bone2.getAbsolutePosition(mesh);
  61089. var pos3 = this._bone1.getAbsolutePosition(mesh);
  61090. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  61091. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  61092. }
  61093. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  61094. this.maxAngle = Math.PI;
  61095. if (options) {
  61096. if (options.targetMesh) {
  61097. this.targetMesh = options.targetMesh;
  61098. this.targetMesh.computeWorldMatrix(true);
  61099. }
  61100. if (options.poleTargetMesh) {
  61101. this.poleTargetMesh = options.poleTargetMesh;
  61102. this.poleTargetMesh.computeWorldMatrix(true);
  61103. }
  61104. else if (options.poleTargetBone) {
  61105. this.poleTargetBone = options.poleTargetBone;
  61106. }
  61107. else if (this._bone1.getParent()) {
  61108. this.poleTargetBone = this._bone1.getParent();
  61109. }
  61110. if (options.poleTargetLocalOffset) {
  61111. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  61112. }
  61113. if (options.poleAngle) {
  61114. this.poleAngle = options.poleAngle;
  61115. }
  61116. if (options.bendAxis) {
  61117. this._bendAxis.copyFrom(options.bendAxis);
  61118. }
  61119. if (options.maxAngle) {
  61120. this.maxAngle = options.maxAngle;
  61121. }
  61122. if (options.slerpAmount) {
  61123. this.slerpAmount = options.slerpAmount;
  61124. }
  61125. }
  61126. }
  61127. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  61128. get: function () {
  61129. return this._maxAngle;
  61130. },
  61131. set: function (value) {
  61132. this._setMaxAngle(value);
  61133. },
  61134. enumerable: true,
  61135. configurable: true
  61136. });
  61137. BoneIKController.prototype._setMaxAngle = function (ang) {
  61138. if (ang < 0) {
  61139. ang = 0;
  61140. }
  61141. if (ang > Math.PI || ang == undefined) {
  61142. ang = Math.PI;
  61143. }
  61144. this._maxAngle = ang;
  61145. var a = this._bone1Length;
  61146. var b = this._bone2Length;
  61147. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  61148. };
  61149. BoneIKController.prototype.update = function () {
  61150. var bone1 = this._bone1;
  61151. if (!bone1) {
  61152. return;
  61153. }
  61154. var target = this.targetPosition;
  61155. var poleTarget = this.poleTargetPosition;
  61156. var mat1 = BoneIKController._tmpMats[0];
  61157. var mat2 = BoneIKController._tmpMats[1];
  61158. if (this.targetMesh) {
  61159. target.copyFrom(this.targetMesh.getAbsolutePosition());
  61160. }
  61161. if (this.poleTargetBone) {
  61162. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  61163. }
  61164. else if (this.poleTargetMesh) {
  61165. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  61166. }
  61167. var bonePos = BoneIKController._tmpVecs[0];
  61168. var zaxis = BoneIKController._tmpVecs[1];
  61169. var xaxis = BoneIKController._tmpVecs[2];
  61170. var yaxis = BoneIKController._tmpVecs[3];
  61171. var upAxis = BoneIKController._tmpVecs[4];
  61172. var _tmpQuat = BoneIKController._tmpQuat;
  61173. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  61174. poleTarget.subtractToRef(bonePos, upAxis);
  61175. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  61176. upAxis.y = 1;
  61177. }
  61178. else {
  61179. upAxis.normalize();
  61180. }
  61181. target.subtractToRef(bonePos, yaxis);
  61182. yaxis.normalize();
  61183. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  61184. zaxis.normalize();
  61185. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  61186. xaxis.normalize();
  61187. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  61188. var a = this._bone1Length;
  61189. var b = this._bone2Length;
  61190. var c = BABYLON.Vector3.Distance(bonePos, target);
  61191. if (this._maxReach > 0) {
  61192. c = Math.min(this._maxReach, c);
  61193. }
  61194. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  61195. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  61196. if (acosa > 1) {
  61197. acosa = 1;
  61198. }
  61199. if (acosb > 1) {
  61200. acosb = 1;
  61201. }
  61202. if (acosa < -1) {
  61203. acosa = -1;
  61204. }
  61205. if (acosb < -1) {
  61206. acosb = -1;
  61207. }
  61208. var angA = Math.acos(acosa);
  61209. var angB = Math.acos(acosb);
  61210. var angC = -angA - angB;
  61211. if (this._rightHandedSystem) {
  61212. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  61213. mat2.multiplyToRef(mat1, mat1);
  61214. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  61215. mat2.multiplyToRef(mat1, mat1);
  61216. }
  61217. else {
  61218. var _tmpVec = BoneIKController._tmpVecs[5];
  61219. _tmpVec.copyFrom(this._bendAxis);
  61220. _tmpVec.x *= -1;
  61221. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  61222. mat2.multiplyToRef(mat1, mat1);
  61223. }
  61224. if (this.poleAngle) {
  61225. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  61226. mat1.multiplyToRef(mat2, mat1);
  61227. }
  61228. if (this._bone1) {
  61229. if (this.slerpAmount < 1) {
  61230. if (!this._slerping) {
  61231. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  61232. }
  61233. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  61234. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  61235. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  61236. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  61237. this._slerping = true;
  61238. }
  61239. else {
  61240. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  61241. this._bone1Mat.copyFrom(mat1);
  61242. this._slerping = false;
  61243. }
  61244. }
  61245. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  61246. this._bone2Ang = angC;
  61247. };
  61248. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61249. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  61250. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61251. return BoneIKController;
  61252. }());
  61253. BABYLON.BoneIKController = BoneIKController;
  61254. })(BABYLON || (BABYLON = {}));
  61255. //# sourceMappingURL=babylon.boneIKController.js.map
  61256. var BABYLON;
  61257. (function (BABYLON) {
  61258. var BoneLookController = /** @class */ (function () {
  61259. /**
  61260. * Create a BoneLookController
  61261. * @param mesh the mesh that the bone belongs to
  61262. * @param bone the bone that will be looking to the target
  61263. * @param target the target Vector3 to look at
  61264. * @param settings optional settings:
  61265. * - maxYaw: the maximum angle the bone will yaw to
  61266. * - minYaw: the minimum angle the bone will yaw to
  61267. * - maxPitch: the maximum angle the bone will pitch to
  61268. * - minPitch: the minimum angle the bone will yaw to
  61269. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  61270. * - upAxis: the up axis of the coordinate system
  61271. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61272. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  61273. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  61274. * - adjustYaw: used to make an adjustment to the yaw of the bone
  61275. * - adjustPitch: used to make an adjustment to the pitch of the bone
  61276. * - adjustRoll: used to make an adjustment to the roll of the bone
  61277. **/
  61278. function BoneLookController(mesh, bone, target, options) {
  61279. /**
  61280. * The up axis of the coordinate system that is used when the bone is rotated.
  61281. */
  61282. this.upAxis = BABYLON.Vector3.Up();
  61283. /**
  61284. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61285. */
  61286. this.upAxisSpace = BABYLON.Space.LOCAL;
  61287. /**
  61288. * Used to make an adjustment to the yaw of the bone.
  61289. */
  61290. this.adjustYaw = 0;
  61291. /**
  61292. * Used to make an adjustment to the pitch of the bone.
  61293. */
  61294. this.adjustPitch = 0;
  61295. /**
  61296. * Used to make an adjustment to the roll of the bone.
  61297. */
  61298. this.adjustRoll = 0;
  61299. /**
  61300. * 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).
  61301. */
  61302. this.slerpAmount = 1;
  61303. this._boneQuat = BABYLON.Quaternion.Identity();
  61304. this._slerping = false;
  61305. this._firstFrameSkipped = false;
  61306. this._fowardAxis = BABYLON.Vector3.Forward();
  61307. this.mesh = mesh;
  61308. this.bone = bone;
  61309. this.target = target;
  61310. if (options) {
  61311. if (options.adjustYaw) {
  61312. this.adjustYaw = options.adjustYaw;
  61313. }
  61314. if (options.adjustPitch) {
  61315. this.adjustPitch = options.adjustPitch;
  61316. }
  61317. if (options.adjustRoll) {
  61318. this.adjustRoll = options.adjustRoll;
  61319. }
  61320. if (options.maxYaw != null) {
  61321. this.maxYaw = options.maxYaw;
  61322. }
  61323. else {
  61324. this.maxYaw = Math.PI;
  61325. }
  61326. if (options.minYaw != null) {
  61327. this.minYaw = options.minYaw;
  61328. }
  61329. else {
  61330. this.minYaw = -Math.PI;
  61331. }
  61332. if (options.maxPitch != null) {
  61333. this.maxPitch = options.maxPitch;
  61334. }
  61335. else {
  61336. this.maxPitch = Math.PI;
  61337. }
  61338. if (options.minPitch != null) {
  61339. this.minPitch = options.minPitch;
  61340. }
  61341. else {
  61342. this.minPitch = -Math.PI;
  61343. }
  61344. if (options.slerpAmount != null) {
  61345. this.slerpAmount = options.slerpAmount;
  61346. }
  61347. if (options.upAxis != null) {
  61348. this.upAxis = options.upAxis;
  61349. }
  61350. if (options.upAxisSpace != null) {
  61351. this.upAxisSpace = options.upAxisSpace;
  61352. }
  61353. if (options.yawAxis != null || options.pitchAxis != null) {
  61354. var newYawAxis = BABYLON.Axis.Y;
  61355. var newPitchAxis = BABYLON.Axis.X;
  61356. if (options.yawAxis != null) {
  61357. newYawAxis = options.yawAxis.clone();
  61358. newYawAxis.normalize();
  61359. }
  61360. if (options.pitchAxis != null) {
  61361. newPitchAxis = options.pitchAxis.clone();
  61362. newPitchAxis.normalize();
  61363. }
  61364. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  61365. this._transformYawPitch = BABYLON.Matrix.Identity();
  61366. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  61367. this._transformYawPitchInv = this._transformYawPitch.clone();
  61368. this._transformYawPitch.invert();
  61369. }
  61370. }
  61371. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  61372. this.upAxisSpace = BABYLON.Space.LOCAL;
  61373. }
  61374. }
  61375. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  61376. /**
  61377. * Get/set the minimum yaw angle that the bone can look to.
  61378. */
  61379. get: function () {
  61380. return this._minYaw;
  61381. },
  61382. set: function (value) {
  61383. this._minYaw = value;
  61384. this._minYawSin = Math.sin(value);
  61385. this._minYawCos = Math.cos(value);
  61386. if (this._maxYaw != null) {
  61387. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61388. this._yawRange = this._maxYaw - this._minYaw;
  61389. }
  61390. },
  61391. enumerable: true,
  61392. configurable: true
  61393. });
  61394. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  61395. /**
  61396. * Get/set the maximum yaw angle that the bone can look to.
  61397. */
  61398. get: function () {
  61399. return this._maxYaw;
  61400. },
  61401. set: function (value) {
  61402. this._maxYaw = value;
  61403. this._maxYawSin = Math.sin(value);
  61404. this._maxYawCos = Math.cos(value);
  61405. if (this._minYaw != null) {
  61406. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61407. this._yawRange = this._maxYaw - this._minYaw;
  61408. }
  61409. },
  61410. enumerable: true,
  61411. configurable: true
  61412. });
  61413. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  61414. /**
  61415. * Get/set the minimum pitch angle that the bone can look to.
  61416. */
  61417. get: function () {
  61418. return this._minPitch;
  61419. },
  61420. set: function (value) {
  61421. this._minPitch = value;
  61422. this._minPitchTan = Math.tan(value);
  61423. },
  61424. enumerable: true,
  61425. configurable: true
  61426. });
  61427. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  61428. /**
  61429. * Get/set the maximum pitch angle that the bone can look to.
  61430. */
  61431. get: function () {
  61432. return this._maxPitch;
  61433. },
  61434. set: function (value) {
  61435. this._maxPitch = value;
  61436. this._maxPitchTan = Math.tan(value);
  61437. },
  61438. enumerable: true,
  61439. configurable: true
  61440. });
  61441. /**
  61442. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  61443. */
  61444. BoneLookController.prototype.update = function () {
  61445. //skip the first frame when slerping so that the mesh rotation is correct
  61446. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  61447. this._firstFrameSkipped = true;
  61448. return;
  61449. }
  61450. var bone = this.bone;
  61451. var bonePos = BoneLookController._tmpVecs[0];
  61452. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  61453. var target = this.target;
  61454. var _tmpMat1 = BoneLookController._tmpMats[0];
  61455. var _tmpMat2 = BoneLookController._tmpMats[1];
  61456. var mesh = this.mesh;
  61457. var parentBone = bone.getParent();
  61458. var upAxis = BoneLookController._tmpVecs[1];
  61459. upAxis.copyFrom(this.upAxis);
  61460. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  61461. if (this._transformYawPitch) {
  61462. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  61463. }
  61464. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  61465. }
  61466. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  61467. mesh.getDirectionToRef(upAxis, upAxis);
  61468. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  61469. upAxis.normalize();
  61470. }
  61471. }
  61472. var checkYaw = false;
  61473. var checkPitch = false;
  61474. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  61475. checkYaw = true;
  61476. }
  61477. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  61478. checkPitch = true;
  61479. }
  61480. if (checkYaw || checkPitch) {
  61481. var spaceMat = BoneLookController._tmpMats[2];
  61482. var spaceMatInv = BoneLookController._tmpMats[3];
  61483. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  61484. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  61485. }
  61486. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  61487. spaceMat.copyFrom(mesh.getWorldMatrix());
  61488. }
  61489. else {
  61490. var forwardAxis = BoneLookController._tmpVecs[2];
  61491. forwardAxis.copyFrom(this._fowardAxis);
  61492. if (this._transformYawPitch) {
  61493. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  61494. }
  61495. if (parentBone) {
  61496. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  61497. }
  61498. else {
  61499. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  61500. }
  61501. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  61502. rightAxis.normalize();
  61503. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  61504. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  61505. }
  61506. spaceMat.invertToRef(spaceMatInv);
  61507. var xzlen = null;
  61508. if (checkPitch) {
  61509. var localTarget = BoneLookController._tmpVecs[3];
  61510. target.subtractToRef(bonePos, localTarget);
  61511. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61512. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61513. var pitch = Math.atan2(localTarget.y, xzlen);
  61514. var newPitch = pitch;
  61515. if (pitch > this._maxPitch) {
  61516. localTarget.y = this._maxPitchTan * xzlen;
  61517. newPitch = this._maxPitch;
  61518. }
  61519. else if (pitch < this._minPitch) {
  61520. localTarget.y = this._minPitchTan * xzlen;
  61521. newPitch = this._minPitch;
  61522. }
  61523. if (pitch != newPitch) {
  61524. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61525. localTarget.addInPlace(bonePos);
  61526. target = localTarget;
  61527. }
  61528. }
  61529. if (checkYaw) {
  61530. var localTarget = BoneLookController._tmpVecs[4];
  61531. target.subtractToRef(bonePos, localTarget);
  61532. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61533. var yaw = Math.atan2(localTarget.x, localTarget.z);
  61534. var newYaw = yaw;
  61535. if (yaw > this._maxYaw || yaw < this._minYaw) {
  61536. if (xzlen == null) {
  61537. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61538. }
  61539. if (this._yawRange > Math.PI) {
  61540. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  61541. localTarget.z = this._maxYawCos * xzlen;
  61542. localTarget.x = this._maxYawSin * xzlen;
  61543. newYaw = this._maxYaw;
  61544. }
  61545. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  61546. localTarget.z = this._minYawCos * xzlen;
  61547. localTarget.x = this._minYawSin * xzlen;
  61548. newYaw = this._minYaw;
  61549. }
  61550. }
  61551. else {
  61552. if (yaw > this._maxYaw) {
  61553. localTarget.z = this._maxYawCos * xzlen;
  61554. localTarget.x = this._maxYawSin * xzlen;
  61555. newYaw = this._maxYaw;
  61556. }
  61557. else if (yaw < this._minYaw) {
  61558. localTarget.z = this._minYawCos * xzlen;
  61559. localTarget.x = this._minYawSin * xzlen;
  61560. newYaw = this._minYaw;
  61561. }
  61562. }
  61563. }
  61564. if (this._slerping && this._yawRange > Math.PI) {
  61565. //are we going to be crossing into the min/max region?
  61566. var boneFwd = BoneLookController._tmpVecs[8];
  61567. boneFwd.copyFrom(BABYLON.Axis.Z);
  61568. if (this._transformYawPitch) {
  61569. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  61570. }
  61571. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  61572. this._boneQuat.toRotationMatrix(boneRotMat);
  61573. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  61574. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  61575. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  61576. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  61577. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  61578. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  61579. if (angBtwTar > angBtwMidYaw) {
  61580. if (xzlen == null) {
  61581. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61582. }
  61583. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  61584. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  61585. if (angBtwMin < angBtwMax) {
  61586. newYaw = boneYaw + Math.PI * .75;
  61587. localTarget.z = Math.cos(newYaw) * xzlen;
  61588. localTarget.x = Math.sin(newYaw) * xzlen;
  61589. }
  61590. else {
  61591. newYaw = boneYaw - Math.PI * .75;
  61592. localTarget.z = Math.cos(newYaw) * xzlen;
  61593. localTarget.x = Math.sin(newYaw) * xzlen;
  61594. }
  61595. }
  61596. }
  61597. if (yaw != newYaw) {
  61598. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61599. localTarget.addInPlace(bonePos);
  61600. target = localTarget;
  61601. }
  61602. }
  61603. }
  61604. var zaxis = BoneLookController._tmpVecs[5];
  61605. var xaxis = BoneLookController._tmpVecs[6];
  61606. var yaxis = BoneLookController._tmpVecs[7];
  61607. var _tmpQuat = BoneLookController._tmpQuat;
  61608. target.subtractToRef(bonePos, zaxis);
  61609. zaxis.normalize();
  61610. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  61611. xaxis.normalize();
  61612. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  61613. yaxis.normalize();
  61614. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  61615. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  61616. return;
  61617. }
  61618. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  61619. return;
  61620. }
  61621. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  61622. return;
  61623. }
  61624. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  61625. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  61626. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  61627. }
  61628. if (this.slerpAmount < 1) {
  61629. if (!this._slerping) {
  61630. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  61631. }
  61632. if (this._transformYawPitch) {
  61633. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61634. }
  61635. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  61636. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  61637. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  61638. this._slerping = true;
  61639. }
  61640. else {
  61641. if (this._transformYawPitch) {
  61642. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61643. }
  61644. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  61645. this._slerping = false;
  61646. }
  61647. };
  61648. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  61649. var angDiff = ang2 - ang1;
  61650. angDiff %= Math.PI * 2;
  61651. if (angDiff > Math.PI) {
  61652. angDiff -= Math.PI * 2;
  61653. }
  61654. else if (angDiff < -Math.PI) {
  61655. angDiff += Math.PI * 2;
  61656. }
  61657. return angDiff;
  61658. };
  61659. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  61660. ang1 %= (2 * Math.PI);
  61661. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61662. ang2 %= (2 * Math.PI);
  61663. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61664. var ab = 0;
  61665. if (ang1 < ang2) {
  61666. ab = ang2 - ang1;
  61667. }
  61668. else {
  61669. ab = ang1 - ang2;
  61670. }
  61671. if (ab > Math.PI) {
  61672. ab = Math.PI * 2 - ab;
  61673. }
  61674. return ab;
  61675. };
  61676. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  61677. ang %= (2 * Math.PI);
  61678. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  61679. ang1 %= (2 * Math.PI);
  61680. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61681. ang2 %= (2 * Math.PI);
  61682. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61683. if (ang1 < ang2) {
  61684. if (ang > ang1 && ang < ang2) {
  61685. return true;
  61686. }
  61687. }
  61688. else {
  61689. if (ang > ang2 && ang < ang1) {
  61690. return true;
  61691. }
  61692. }
  61693. return false;
  61694. };
  61695. 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()];
  61696. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  61697. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61698. return BoneLookController;
  61699. }());
  61700. BABYLON.BoneLookController = BoneLookController;
  61701. })(BABYLON || (BABYLON = {}));
  61702. //# sourceMappingURL=babylon.boneLookController.js.map
  61703. var BABYLON;
  61704. (function (BABYLON) {
  61705. var Skeleton = /** @class */ (function () {
  61706. function Skeleton(name, id, scene) {
  61707. this.name = name;
  61708. this.id = id;
  61709. this.bones = new Array();
  61710. this.needInitialSkinMatrix = false;
  61711. this._isDirty = true;
  61712. this._meshesWithPoseMatrix = new Array();
  61713. this._identity = BABYLON.Matrix.Identity();
  61714. this._ranges = {};
  61715. this._lastAbsoluteTransformsUpdateId = -1;
  61716. // Events
  61717. /**
  61718. * An event triggered before computing the skeleton's matrices
  61719. * @type {BABYLON.Observable}
  61720. */
  61721. this.onBeforeComputeObservable = new BABYLON.Observable();
  61722. this.bones = [];
  61723. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61724. scene.skeletons.push(this);
  61725. //make sure it will recalculate the matrix next time prepare is called.
  61726. this._isDirty = true;
  61727. }
  61728. // Members
  61729. Skeleton.prototype.getTransformMatrices = function (mesh) {
  61730. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  61731. return mesh._bonesTransformMatrices;
  61732. }
  61733. if (!this._transformMatrices) {
  61734. this.prepare();
  61735. }
  61736. return this._transformMatrices;
  61737. };
  61738. Skeleton.prototype.getScene = function () {
  61739. return this._scene;
  61740. };
  61741. // Methods
  61742. /**
  61743. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  61744. */
  61745. Skeleton.prototype.toString = function (fullDetails) {
  61746. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  61747. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  61748. if (fullDetails) {
  61749. ret += ", Ranges: {";
  61750. var first = true;
  61751. for (var name_1 in this._ranges) {
  61752. if (first) {
  61753. ret += ", ";
  61754. first = false;
  61755. }
  61756. ret += name_1;
  61757. }
  61758. ret += "}";
  61759. }
  61760. return ret;
  61761. };
  61762. /**
  61763. * Get bone's index searching by name
  61764. * @param {string} name is bone's name to search for
  61765. * @return {number} Indice of the bone. Returns -1 if not found
  61766. */
  61767. Skeleton.prototype.getBoneIndexByName = function (name) {
  61768. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  61769. if (this.bones[boneIndex].name === name) {
  61770. return boneIndex;
  61771. }
  61772. }
  61773. return -1;
  61774. };
  61775. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  61776. // check name not already in use
  61777. if (!this._ranges[name]) {
  61778. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  61779. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61780. if (this.bones[i].animations[0]) {
  61781. this.bones[i].animations[0].createRange(name, from, to);
  61782. }
  61783. }
  61784. }
  61785. };
  61786. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  61787. if (deleteFrames === void 0) { deleteFrames = true; }
  61788. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61789. if (this.bones[i].animations[0]) {
  61790. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  61791. }
  61792. }
  61793. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  61794. };
  61795. Skeleton.prototype.getAnimationRange = function (name) {
  61796. return this._ranges[name];
  61797. };
  61798. /**
  61799. * Returns as an Array, all AnimationRanges defined on this skeleton
  61800. */
  61801. Skeleton.prototype.getAnimationRanges = function () {
  61802. var animationRanges = [];
  61803. var name;
  61804. var i = 0;
  61805. for (name in this._ranges) {
  61806. animationRanges[i] = this._ranges[name];
  61807. i++;
  61808. }
  61809. return animationRanges;
  61810. };
  61811. /**
  61812. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  61813. */
  61814. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  61815. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61816. if (this._ranges[name] || !source.getAnimationRange(name)) {
  61817. return false;
  61818. }
  61819. var ret = true;
  61820. var frameOffset = this._getHighestAnimationFrame() + 1;
  61821. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  61822. var boneDict = {};
  61823. var sourceBones = source.bones;
  61824. var nBones;
  61825. var i;
  61826. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  61827. boneDict[sourceBones[i].name] = sourceBones[i];
  61828. }
  61829. if (this.bones.length !== sourceBones.length) {
  61830. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  61831. ret = false;
  61832. }
  61833. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  61834. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  61835. var boneName = this.bones[i].name;
  61836. var sourceBone = boneDict[boneName];
  61837. if (sourceBone) {
  61838. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  61839. }
  61840. else {
  61841. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  61842. ret = false;
  61843. }
  61844. }
  61845. // do not call createAnimationRange(), since it also is done to bones, which was already done
  61846. var range = source.getAnimationRange(name);
  61847. if (range) {
  61848. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  61849. }
  61850. return ret;
  61851. };
  61852. Skeleton.prototype.returnToRest = function () {
  61853. for (var index = 0; index < this.bones.length; index++) {
  61854. this.bones[index].returnToRest();
  61855. }
  61856. };
  61857. Skeleton.prototype._getHighestAnimationFrame = function () {
  61858. var ret = 0;
  61859. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61860. if (this.bones[i].animations[0]) {
  61861. var highest = this.bones[i].animations[0].getHighestFrame();
  61862. if (ret < highest) {
  61863. ret = highest;
  61864. }
  61865. }
  61866. }
  61867. return ret;
  61868. };
  61869. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  61870. var range = this.getAnimationRange(name);
  61871. if (!range) {
  61872. return null;
  61873. }
  61874. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  61875. };
  61876. Skeleton.prototype._markAsDirty = function () {
  61877. this._isDirty = true;
  61878. };
  61879. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  61880. this._meshesWithPoseMatrix.push(mesh);
  61881. };
  61882. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  61883. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  61884. if (index > -1) {
  61885. this._meshesWithPoseMatrix.splice(index, 1);
  61886. }
  61887. };
  61888. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  61889. this.onBeforeComputeObservable.notifyObservers(this);
  61890. for (var index = 0; index < this.bones.length; index++) {
  61891. var bone = this.bones[index];
  61892. var parentBone = bone.getParent();
  61893. if (parentBone) {
  61894. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  61895. }
  61896. else {
  61897. if (initialSkinMatrix) {
  61898. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  61899. }
  61900. else {
  61901. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  61902. }
  61903. }
  61904. if (bone._index !== -1) {
  61905. var mappedIndex = bone._index === null ? index : bone._index;
  61906. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  61907. }
  61908. }
  61909. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  61910. };
  61911. Skeleton.prototype.prepare = function () {
  61912. if (!this._isDirty) {
  61913. return;
  61914. }
  61915. if (this.needInitialSkinMatrix) {
  61916. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  61917. var mesh = this._meshesWithPoseMatrix[index];
  61918. var poseMatrix = mesh.getPoseMatrix();
  61919. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  61920. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  61921. }
  61922. if (this._synchronizedWithMesh !== mesh) {
  61923. this._synchronizedWithMesh = mesh;
  61924. // Prepare bones
  61925. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  61926. var bone = this.bones[boneIndex];
  61927. if (!bone.getParent()) {
  61928. var matrix = bone.getBaseMatrix();
  61929. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  61930. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  61931. }
  61932. }
  61933. }
  61934. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  61935. }
  61936. }
  61937. else {
  61938. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  61939. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  61940. }
  61941. this._computeTransformMatrices(this._transformMatrices, null);
  61942. }
  61943. this._isDirty = false;
  61944. this._scene._activeBones.addCount(this.bones.length, false);
  61945. };
  61946. Skeleton.prototype.getAnimatables = function () {
  61947. if (!this._animatables || this._animatables.length !== this.bones.length) {
  61948. this._animatables = [];
  61949. for (var index = 0; index < this.bones.length; index++) {
  61950. this._animatables.push(this.bones[index]);
  61951. }
  61952. }
  61953. return this._animatables;
  61954. };
  61955. Skeleton.prototype.clone = function (name, id) {
  61956. var result = new Skeleton(name, id || name, this._scene);
  61957. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  61958. for (var index = 0; index < this.bones.length; index++) {
  61959. var source = this.bones[index];
  61960. var parentBone = null;
  61961. var parent_1 = source.getParent();
  61962. if (parent_1) {
  61963. var parentIndex = this.bones.indexOf(parent_1);
  61964. parentBone = result.bones[parentIndex];
  61965. }
  61966. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  61967. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  61968. }
  61969. if (this._ranges) {
  61970. result._ranges = {};
  61971. for (var rangeName in this._ranges) {
  61972. var range = this._ranges[rangeName];
  61973. if (range) {
  61974. result._ranges[rangeName] = range.clone();
  61975. }
  61976. }
  61977. }
  61978. this._isDirty = true;
  61979. return result;
  61980. };
  61981. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  61982. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  61983. this.bones.forEach(function (bone) {
  61984. bone.animations.forEach(function (animation) {
  61985. animation.enableBlending = true;
  61986. animation.blendingSpeed = blendingSpeed;
  61987. });
  61988. });
  61989. };
  61990. Skeleton.prototype.dispose = function () {
  61991. this._meshesWithPoseMatrix = [];
  61992. // Animations
  61993. this.getScene().stopAnimation(this);
  61994. // Remove from scene
  61995. this.getScene().removeSkeleton(this);
  61996. };
  61997. Skeleton.prototype.serialize = function () {
  61998. var serializationObject = {};
  61999. serializationObject.name = this.name;
  62000. serializationObject.id = this.id;
  62001. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  62002. serializationObject.bones = [];
  62003. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62004. for (var index = 0; index < this.bones.length; index++) {
  62005. var bone = this.bones[index];
  62006. var parent_2 = bone.getParent();
  62007. var serializedBone = {
  62008. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62009. name: bone.name,
  62010. matrix: bone.getBaseMatrix().toArray(),
  62011. rest: bone.getRestPose().toArray()
  62012. };
  62013. serializationObject.bones.push(serializedBone);
  62014. if (bone.length) {
  62015. serializedBone.length = bone.length;
  62016. }
  62017. if (bone.animations && bone.animations.length > 0) {
  62018. serializedBone.animation = bone.animations[0].serialize();
  62019. }
  62020. serializationObject.ranges = [];
  62021. for (var name in this._ranges) {
  62022. var source = this._ranges[name];
  62023. if (!source) {
  62024. continue;
  62025. }
  62026. var range = {};
  62027. range.name = name;
  62028. range.from = source.from;
  62029. range.to = source.to;
  62030. serializationObject.ranges.push(range);
  62031. }
  62032. }
  62033. return serializationObject;
  62034. };
  62035. Skeleton.Parse = function (parsedSkeleton, scene) {
  62036. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62037. if (parsedSkeleton.dimensionsAtRest) {
  62038. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62039. }
  62040. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62041. var index;
  62042. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62043. var parsedBone = parsedSkeleton.bones[index];
  62044. var parentBone = null;
  62045. if (parsedBone.parentBoneIndex > -1) {
  62046. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62047. }
  62048. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62049. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62050. if (parsedBone.length) {
  62051. bone.length = parsedBone.length;
  62052. }
  62053. if (parsedBone.animation) {
  62054. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62055. }
  62056. }
  62057. // placed after bones, so createAnimationRange can cascade down
  62058. if (parsedSkeleton.ranges) {
  62059. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62060. var data = parsedSkeleton.ranges[index];
  62061. skeleton.createAnimationRange(data.name, data.from, data.to);
  62062. }
  62063. }
  62064. return skeleton;
  62065. };
  62066. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62067. if (forceUpdate === void 0) { forceUpdate = false; }
  62068. var renderId = this._scene.getRenderId();
  62069. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62070. this.bones[0].computeAbsoluteTransforms();
  62071. this._lastAbsoluteTransformsUpdateId = renderId;
  62072. }
  62073. };
  62074. Skeleton.prototype.getPoseMatrix = function () {
  62075. var poseMatrix = null;
  62076. if (this._meshesWithPoseMatrix.length > 0) {
  62077. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62078. }
  62079. return poseMatrix;
  62080. };
  62081. Skeleton.prototype.sortBones = function () {
  62082. var bones = new Array();
  62083. var visited = new Array(this.bones.length);
  62084. for (var index = 0; index < this.bones.length; index++) {
  62085. this._sortBones(index, bones, visited);
  62086. }
  62087. this.bones = bones;
  62088. };
  62089. Skeleton.prototype._sortBones = function (index, bones, visited) {
  62090. if (visited[index]) {
  62091. return;
  62092. }
  62093. visited[index] = true;
  62094. var bone = this.bones[index];
  62095. if (bone._index === undefined) {
  62096. bone._index = index;
  62097. }
  62098. var parentBone = bone.getParent();
  62099. if (parentBone) {
  62100. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  62101. }
  62102. bones.push(bone);
  62103. };
  62104. return Skeleton;
  62105. }());
  62106. BABYLON.Skeleton = Skeleton;
  62107. })(BABYLON || (BABYLON = {}));
  62108. //# sourceMappingURL=babylon.skeleton.js.map
  62109. var BABYLON;
  62110. (function (BABYLON) {
  62111. var SphericalPolynomial = /** @class */ (function () {
  62112. function SphericalPolynomial() {
  62113. this.x = BABYLON.Vector3.Zero();
  62114. this.y = BABYLON.Vector3.Zero();
  62115. this.z = BABYLON.Vector3.Zero();
  62116. this.xx = BABYLON.Vector3.Zero();
  62117. this.yy = BABYLON.Vector3.Zero();
  62118. this.zz = BABYLON.Vector3.Zero();
  62119. this.xy = BABYLON.Vector3.Zero();
  62120. this.yz = BABYLON.Vector3.Zero();
  62121. this.zx = BABYLON.Vector3.Zero();
  62122. }
  62123. SphericalPolynomial.prototype.addAmbient = function (color) {
  62124. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62125. this.xx = this.xx.add(colorVector);
  62126. this.yy = this.yy.add(colorVector);
  62127. this.zz = this.zz.add(colorVector);
  62128. };
  62129. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  62130. var result = new SphericalPolynomial();
  62131. result.x = harmonics.L11.scale(1.02333);
  62132. result.y = harmonics.L1_1.scale(1.02333);
  62133. result.z = harmonics.L10.scale(1.02333);
  62134. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  62135. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  62136. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  62137. result.yz = harmonics.L2_1.scale(0.858086);
  62138. result.zx = harmonics.L21.scale(0.858086);
  62139. result.xy = harmonics.L2_2.scale(0.858086);
  62140. result.scale(1.0 / Math.PI);
  62141. return result;
  62142. };
  62143. SphericalPolynomial.prototype.scale = function (scale) {
  62144. this.x = this.x.scale(scale);
  62145. this.y = this.y.scale(scale);
  62146. this.z = this.z.scale(scale);
  62147. this.xx = this.xx.scale(scale);
  62148. this.yy = this.yy.scale(scale);
  62149. this.zz = this.zz.scale(scale);
  62150. this.yz = this.yz.scale(scale);
  62151. this.zx = this.zx.scale(scale);
  62152. this.xy = this.xy.scale(scale);
  62153. };
  62154. return SphericalPolynomial;
  62155. }());
  62156. BABYLON.SphericalPolynomial = SphericalPolynomial;
  62157. var SphericalHarmonics = /** @class */ (function () {
  62158. function SphericalHarmonics() {
  62159. this.L00 = BABYLON.Vector3.Zero();
  62160. this.L1_1 = BABYLON.Vector3.Zero();
  62161. this.L10 = BABYLON.Vector3.Zero();
  62162. this.L11 = BABYLON.Vector3.Zero();
  62163. this.L2_2 = BABYLON.Vector3.Zero();
  62164. this.L2_1 = BABYLON.Vector3.Zero();
  62165. this.L20 = BABYLON.Vector3.Zero();
  62166. this.L21 = BABYLON.Vector3.Zero();
  62167. this.L22 = BABYLON.Vector3.Zero();
  62168. }
  62169. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  62170. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62171. var c = colorVector.scale(deltaSolidAngle);
  62172. this.L00 = this.L00.add(c.scale(0.282095));
  62173. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  62174. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  62175. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  62176. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  62177. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  62178. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  62179. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  62180. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  62181. };
  62182. SphericalHarmonics.prototype.scale = function (scale) {
  62183. this.L00 = this.L00.scale(scale);
  62184. this.L1_1 = this.L1_1.scale(scale);
  62185. this.L10 = this.L10.scale(scale);
  62186. this.L11 = this.L11.scale(scale);
  62187. this.L2_2 = this.L2_2.scale(scale);
  62188. this.L2_1 = this.L2_1.scale(scale);
  62189. this.L20 = this.L20.scale(scale);
  62190. this.L21 = this.L21.scale(scale);
  62191. this.L22 = this.L22.scale(scale);
  62192. };
  62193. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  62194. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  62195. //
  62196. // E_lm = A_l * L_lm
  62197. //
  62198. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  62199. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  62200. // the scaling factors are given in equation 9.
  62201. // Constant (Band 0)
  62202. this.L00 = this.L00.scale(3.141593);
  62203. // Linear (Band 1)
  62204. this.L1_1 = this.L1_1.scale(2.094395);
  62205. this.L10 = this.L10.scale(2.094395);
  62206. this.L11 = this.L11.scale(2.094395);
  62207. // Quadratic (Band 2)
  62208. this.L2_2 = this.L2_2.scale(0.785398);
  62209. this.L2_1 = this.L2_1.scale(0.785398);
  62210. this.L20 = this.L20.scale(0.785398);
  62211. this.L21 = this.L21.scale(0.785398);
  62212. this.L22 = this.L22.scale(0.785398);
  62213. };
  62214. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  62215. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  62216. // L = (1/pi) * E * rho
  62217. //
  62218. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  62219. this.scale(1.0 / Math.PI);
  62220. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  62221. // (The pixel shader must apply albedo after texture fetches, etc).
  62222. };
  62223. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  62224. var result = new SphericalHarmonics();
  62225. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  62226. result.L1_1 = polynomial.y.scale(0.977204);
  62227. result.L10 = polynomial.z.scale(0.977204);
  62228. result.L11 = polynomial.x.scale(0.977204);
  62229. result.L2_2 = polynomial.xy.scale(1.16538);
  62230. result.L2_1 = polynomial.yz.scale(1.16538);
  62231. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  62232. result.L21 = polynomial.zx.scale(1.16538);
  62233. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  62234. result.scale(Math.PI);
  62235. return result;
  62236. };
  62237. return SphericalHarmonics;
  62238. }());
  62239. BABYLON.SphericalHarmonics = SphericalHarmonics;
  62240. })(BABYLON || (BABYLON = {}));
  62241. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  62242. var BABYLON;
  62243. (function (BABYLON) {
  62244. var Internals;
  62245. (function (Internals) {
  62246. var FileFaceOrientation = /** @class */ (function () {
  62247. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  62248. this.name = name;
  62249. this.worldAxisForNormal = worldAxisForNormal;
  62250. this.worldAxisForFileX = worldAxisForFileX;
  62251. this.worldAxisForFileY = worldAxisForFileY;
  62252. }
  62253. return FileFaceOrientation;
  62254. }());
  62255. ;
  62256. /**
  62257. * Helper class dealing with the extraction of spherical polynomial dataArray
  62258. * from a cube map.
  62259. */
  62260. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  62261. function CubeMapToSphericalPolynomialTools() {
  62262. }
  62263. /**
  62264. * Converts a texture to the according Spherical Polynomial data.
  62265. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62266. *
  62267. * @param texture The texture to extract the information from.
  62268. * @return The Spherical Polynomial data.
  62269. */
  62270. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  62271. if (!texture.isCube) {
  62272. // Only supports cube Textures currently.
  62273. return null;
  62274. }
  62275. var size = texture.getSize().width;
  62276. var right = texture.readPixels(0);
  62277. var left = texture.readPixels(1);
  62278. var up;
  62279. var down;
  62280. if (texture.isRenderTarget) {
  62281. up = texture.readPixels(3);
  62282. down = texture.readPixels(2);
  62283. }
  62284. else {
  62285. up = texture.readPixels(2);
  62286. down = texture.readPixels(3);
  62287. }
  62288. var front = texture.readPixels(4);
  62289. var back = texture.readPixels(5);
  62290. var gammaSpace = texture.gammaSpace;
  62291. // Always read as RGBA.
  62292. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  62293. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62294. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62295. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62296. }
  62297. var cubeInfo = {
  62298. size: size,
  62299. right: right,
  62300. left: left,
  62301. up: up,
  62302. down: down,
  62303. front: front,
  62304. back: back,
  62305. format: format,
  62306. type: type,
  62307. gammaSpace: gammaSpace,
  62308. };
  62309. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  62310. };
  62311. /**
  62312. * Converts a cubemap to the according Spherical Polynomial data.
  62313. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62314. *
  62315. * @param cubeInfo The Cube map to extract the information from.
  62316. * @return The Spherical Polynomial data.
  62317. */
  62318. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  62319. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  62320. var totalSolidAngle = 0.0;
  62321. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  62322. var du = 2.0 / cubeInfo.size;
  62323. var dv = du;
  62324. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  62325. var minUV = du * 0.5 - 1.0;
  62326. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62327. var fileFace = this.FileFaces[faceIndex];
  62328. var dataArray = cubeInfo[fileFace.name];
  62329. var v = minUV;
  62330. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  62331. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  62332. // Because SP is still linear, so summation is fine in that basis.
  62333. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  62334. for (var y = 0; y < cubeInfo.size; y++) {
  62335. var u = minUV;
  62336. for (var x = 0; x < cubeInfo.size; x++) {
  62337. // World direction (not normalised)
  62338. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  62339. worldDirection.normalize();
  62340. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  62341. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  62342. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  62343. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  62344. // Handle Integer types.
  62345. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62346. r /= 255;
  62347. g /= 255;
  62348. b /= 255;
  62349. }
  62350. // Handle Gamma space textures.
  62351. if (cubeInfo.gammaSpace) {
  62352. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  62353. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  62354. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  62355. }
  62356. var color = new BABYLON.Color3(r, g, b);
  62357. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  62358. totalSolidAngle += deltaSolidAngle;
  62359. u += du;
  62360. }
  62361. v += dv;
  62362. }
  62363. }
  62364. // Solid angle for entire sphere is 4*pi
  62365. var sphereSolidAngle = 4.0 * Math.PI;
  62366. // Adjust the solid angle to allow for how many faces we processed.
  62367. var facesProcessed = 6.0;
  62368. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  62369. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  62370. // This is needed because the numerical integration over the cube uses a
  62371. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  62372. // and also to compensate for accumulative error due to float precision in the summation.
  62373. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  62374. sphericalHarmonics.scale(correctionFactor);
  62375. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  62376. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  62377. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  62378. };
  62379. CubeMapToSphericalPolynomialTools.FileFaces = [
  62380. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  62381. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  62382. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  62383. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  62384. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  62385. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  62386. ];
  62387. return CubeMapToSphericalPolynomialTools;
  62388. }());
  62389. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  62390. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62391. })(BABYLON || (BABYLON = {}));
  62392. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  62393. var BABYLON;
  62394. (function (BABYLON) {
  62395. var Internals;
  62396. (function (Internals) {
  62397. /**
  62398. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  62399. */
  62400. var PanoramaToCubeMapTools = /** @class */ (function () {
  62401. function PanoramaToCubeMapTools() {
  62402. }
  62403. /**
  62404. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  62405. *
  62406. * @param float32Array The source data.
  62407. * @param inputWidth The width of the input panorama.
  62408. * @param inputhHeight The height of the input panorama.
  62409. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  62410. * @return The cubemap data
  62411. */
  62412. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  62413. if (!float32Array) {
  62414. throw "ConvertPanoramaToCubemap: input cannot be null";
  62415. }
  62416. if (float32Array.length != inputWidth * inputHeight * 3) {
  62417. throw "ConvertPanoramaToCubemap: input size is wrong";
  62418. }
  62419. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  62420. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  62421. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  62422. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  62423. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  62424. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  62425. return {
  62426. front: textureFront,
  62427. back: textureBack,
  62428. left: textureLeft,
  62429. right: textureRight,
  62430. up: textureUp,
  62431. down: textureDown,
  62432. size: size,
  62433. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  62434. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  62435. gammaSpace: false,
  62436. };
  62437. };
  62438. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  62439. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  62440. var textureArray = new Float32Array(buffer);
  62441. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  62442. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  62443. var dy = 1 / texSize;
  62444. var fy = 0;
  62445. for (var y = 0; y < texSize; y++) {
  62446. var xv1 = faceData[0];
  62447. var xv2 = faceData[2];
  62448. for (var x = 0; x < texSize; x++) {
  62449. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  62450. v.normalize();
  62451. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  62452. // 3 channels per pixels
  62453. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  62454. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  62455. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  62456. xv1 = xv1.add(rotDX1);
  62457. xv2 = xv2.add(rotDX2);
  62458. }
  62459. fy += dy;
  62460. }
  62461. return textureArray;
  62462. };
  62463. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  62464. var theta = Math.atan2(vDir.z, vDir.x);
  62465. var phi = Math.acos(vDir.y);
  62466. while (theta < -Math.PI)
  62467. theta += 2 * Math.PI;
  62468. while (theta > Math.PI)
  62469. theta -= 2 * Math.PI;
  62470. var dx = theta / Math.PI;
  62471. var dy = phi / Math.PI;
  62472. // recenter.
  62473. dx = dx * 0.5 + 0.5;
  62474. var px = Math.round(dx * inputWidth);
  62475. if (px < 0)
  62476. px = 0;
  62477. else if (px >= inputWidth)
  62478. px = inputWidth - 1;
  62479. var py = Math.round(dy * inputHeight);
  62480. if (py < 0)
  62481. py = 0;
  62482. else if (py >= inputHeight)
  62483. py = inputHeight - 1;
  62484. var inputY = (inputHeight - py - 1);
  62485. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  62486. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  62487. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  62488. return {
  62489. r: r,
  62490. g: g,
  62491. b: b
  62492. };
  62493. };
  62494. PanoramaToCubeMapTools.FACE_FRONT = [
  62495. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62496. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62497. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62498. new BABYLON.Vector3(1.0, 1.0, -1.0)
  62499. ];
  62500. PanoramaToCubeMapTools.FACE_BACK = [
  62501. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62502. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62503. new BABYLON.Vector3(1.0, 1.0, 1.0),
  62504. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  62505. ];
  62506. PanoramaToCubeMapTools.FACE_RIGHT = [
  62507. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62508. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62509. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62510. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62511. ];
  62512. PanoramaToCubeMapTools.FACE_LEFT = [
  62513. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62514. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62515. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62516. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  62517. ];
  62518. PanoramaToCubeMapTools.FACE_DOWN = [
  62519. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62520. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62521. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62522. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62523. ];
  62524. PanoramaToCubeMapTools.FACE_UP = [
  62525. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62526. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62527. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62528. new BABYLON.Vector3(1.0, -1.0, -1.0)
  62529. ];
  62530. return PanoramaToCubeMapTools;
  62531. }());
  62532. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  62533. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62534. })(BABYLON || (BABYLON = {}));
  62535. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  62536. var BABYLON;
  62537. (function (BABYLON) {
  62538. var Internals;
  62539. (function (Internals) {
  62540. ;
  62541. /**
  62542. * This groups tools to convert HDR texture to native colors array.
  62543. */
  62544. var HDRTools = /** @class */ (function () {
  62545. function HDRTools() {
  62546. }
  62547. HDRTools.Ldexp = function (mantissa, exponent) {
  62548. if (exponent > 1023) {
  62549. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  62550. }
  62551. if (exponent < -1074) {
  62552. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  62553. }
  62554. return mantissa * Math.pow(2, exponent);
  62555. };
  62556. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  62557. if (exponent > 0) {
  62558. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  62559. float32array[index + 0] = red * exponent;
  62560. float32array[index + 1] = green * exponent;
  62561. float32array[index + 2] = blue * exponent;
  62562. }
  62563. else {
  62564. float32array[index + 0] = 0;
  62565. float32array[index + 1] = 0;
  62566. float32array[index + 2] = 0;
  62567. }
  62568. };
  62569. HDRTools.readStringLine = function (uint8array, startIndex) {
  62570. var line = "";
  62571. var character = "";
  62572. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  62573. character = String.fromCharCode(uint8array[i]);
  62574. if (character == "\n") {
  62575. break;
  62576. }
  62577. line += character;
  62578. }
  62579. return line;
  62580. };
  62581. /**
  62582. * Reads header information from an RGBE texture stored in a native array.
  62583. * More information on this format are available here:
  62584. * https://en.wikipedia.org/wiki/RGBE_image_format
  62585. *
  62586. * @param uint8array The binary file stored in native array.
  62587. * @return The header information.
  62588. */
  62589. HDRTools.RGBE_ReadHeader = function (uint8array) {
  62590. var height = 0;
  62591. var width = 0;
  62592. var line = this.readStringLine(uint8array, 0);
  62593. if (line[0] != '#' || line[1] != '?') {
  62594. throw "Bad HDR Format.";
  62595. }
  62596. var endOfHeader = false;
  62597. var findFormat = false;
  62598. var lineIndex = 0;
  62599. do {
  62600. lineIndex += (line.length + 1);
  62601. line = this.readStringLine(uint8array, lineIndex);
  62602. if (line == "FORMAT=32-bit_rle_rgbe") {
  62603. findFormat = true;
  62604. }
  62605. else if (line.length == 0) {
  62606. endOfHeader = true;
  62607. }
  62608. } while (!endOfHeader);
  62609. if (!findFormat) {
  62610. throw "HDR Bad header format, unsupported FORMAT";
  62611. }
  62612. lineIndex += (line.length + 1);
  62613. line = this.readStringLine(uint8array, lineIndex);
  62614. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  62615. var match = sizeRegexp.exec(line);
  62616. // TODO. Support +Y and -X if needed.
  62617. if (!match || match.length < 3) {
  62618. throw "HDR Bad header format, no size";
  62619. }
  62620. width = parseInt(match[2]);
  62621. height = parseInt(match[1]);
  62622. if (width < 8 || width > 0x7fff) {
  62623. throw "HDR Bad header format, unsupported size";
  62624. }
  62625. lineIndex += (line.length + 1);
  62626. return {
  62627. height: height,
  62628. width: width,
  62629. dataPosition: lineIndex
  62630. };
  62631. };
  62632. /**
  62633. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  62634. * This RGBE texture needs to store the information as a panorama.
  62635. *
  62636. * More information on this format are available here:
  62637. * https://en.wikipedia.org/wiki/RGBE_image_format
  62638. *
  62639. * @param buffer The binary file stored in an array buffer.
  62640. * @param size The expected size of the extracted cubemap.
  62641. * @return The Cube Map information.
  62642. */
  62643. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  62644. var uint8array = new Uint8Array(buffer);
  62645. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  62646. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62647. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  62648. return cubeMapData;
  62649. };
  62650. /**
  62651. * Returns the pixels data extracted from an RGBE texture.
  62652. * This pixels will be stored left to right up to down in the R G B order in one array.
  62653. *
  62654. * More information on this format are available here:
  62655. * https://en.wikipedia.org/wiki/RGBE_image_format
  62656. *
  62657. * @param uint8array The binary file stored in an array buffer.
  62658. * @param hdrInfo The header information of the file.
  62659. * @return The pixels data in RGB right to left up to down order.
  62660. */
  62661. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  62662. // Keep for multi format supports.
  62663. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62664. };
  62665. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  62666. var num_scanlines = hdrInfo.height;
  62667. var scanline_width = hdrInfo.width;
  62668. var a, b, c, d, count;
  62669. var dataIndex = hdrInfo.dataPosition;
  62670. var index = 0, endIndex = 0, i = 0;
  62671. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  62672. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  62673. // 3 channels of 4 bytes per pixel in float.
  62674. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  62675. var resultArray = new Float32Array(resultBuffer);
  62676. // read in each successive scanline
  62677. while (num_scanlines > 0) {
  62678. a = uint8array[dataIndex++];
  62679. b = uint8array[dataIndex++];
  62680. c = uint8array[dataIndex++];
  62681. d = uint8array[dataIndex++];
  62682. if (a != 2 || b != 2 || (c & 0x80)) {
  62683. // this file is not run length encoded
  62684. throw "HDR Bad header format, not RLE";
  62685. }
  62686. if (((c << 8) | d) != scanline_width) {
  62687. throw "HDR Bad header format, wrong scan line width";
  62688. }
  62689. index = 0;
  62690. // read each of the four channels for the scanline into the buffer
  62691. for (i = 0; i < 4; i++) {
  62692. endIndex = (i + 1) * scanline_width;
  62693. while (index < endIndex) {
  62694. a = uint8array[dataIndex++];
  62695. b = uint8array[dataIndex++];
  62696. if (a > 128) {
  62697. // a run of the same value
  62698. count = a - 128;
  62699. if ((count == 0) || (count > endIndex - index)) {
  62700. throw "HDR Bad Format, bad scanline data (run)";
  62701. }
  62702. while (count-- > 0) {
  62703. scanLineArray[index++] = b;
  62704. }
  62705. }
  62706. else {
  62707. // a non-run
  62708. count = a;
  62709. if ((count == 0) || (count > endIndex - index)) {
  62710. throw "HDR Bad Format, bad scanline data (non-run)";
  62711. }
  62712. scanLineArray[index++] = b;
  62713. if (--count > 0) {
  62714. for (var j = 0; j < count; j++) {
  62715. scanLineArray[index++] = uint8array[dataIndex++];
  62716. }
  62717. }
  62718. }
  62719. }
  62720. }
  62721. // now convert data from buffer into floats
  62722. for (i = 0; i < scanline_width; i++) {
  62723. a = scanLineArray[i];
  62724. b = scanLineArray[i + scanline_width];
  62725. c = scanLineArray[i + 2 * scanline_width];
  62726. d = scanLineArray[i + 3 * scanline_width];
  62727. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  62728. }
  62729. num_scanlines--;
  62730. }
  62731. return resultArray;
  62732. };
  62733. return HDRTools;
  62734. }());
  62735. Internals.HDRTools = HDRTools;
  62736. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62737. })(BABYLON || (BABYLON = {}));
  62738. //# sourceMappingURL=babylon.hdr.js.map
  62739. var BABYLON;
  62740. (function (BABYLON) {
  62741. /**
  62742. * This represents a texture coming from an HDR input.
  62743. *
  62744. * The only supported format is currently panorama picture stored in RGBE format.
  62745. * Example of such files can be found on HDRLib: http://hdrlib.com/
  62746. */
  62747. var HDRCubeTexture = /** @class */ (function (_super) {
  62748. __extends(HDRCubeTexture, _super);
  62749. /**
  62750. * Instantiates an HDRTexture from the following parameters.
  62751. *
  62752. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  62753. * @param scene The scene the texture will be used in
  62754. * @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.
  62755. * @param noMipmap Forces to not generate the mipmap if true
  62756. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  62757. * @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)
  62758. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  62759. */
  62760. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  62761. if (noMipmap === void 0) { noMipmap = false; }
  62762. if (generateHarmonics === void 0) { generateHarmonics = true; }
  62763. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  62764. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  62765. if (onLoad === void 0) { onLoad = null; }
  62766. if (onError === void 0) { onError = null; }
  62767. var _this = _super.call(this, scene) || this;
  62768. _this._useInGammaSpace = false;
  62769. _this._generateHarmonics = true;
  62770. _this._isBABYLONPreprocessed = false;
  62771. _this._onLoad = null;
  62772. _this._onError = null;
  62773. /**
  62774. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  62775. */
  62776. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62777. /**
  62778. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  62779. * This is usefull at run time to apply the good shader.
  62780. */
  62781. _this.isPMREM = false;
  62782. _this._isBlocking = true;
  62783. if (!url) {
  62784. return _this;
  62785. }
  62786. _this.name = url;
  62787. _this.url = url;
  62788. _this.hasAlpha = false;
  62789. _this.isCube = true;
  62790. _this._textureMatrix = BABYLON.Matrix.Identity();
  62791. _this._onLoad = onLoad;
  62792. _this._onError = onError;
  62793. _this.gammaSpace = false;
  62794. var caps = scene.getEngine().getCaps();
  62795. if (size) {
  62796. _this._isBABYLONPreprocessed = false;
  62797. _this._noMipmap = noMipmap;
  62798. _this._size = size;
  62799. _this._useInGammaSpace = useInGammaSpace;
  62800. _this._usePMREMGenerator = usePMREMGenerator &&
  62801. caps.textureLOD &&
  62802. caps.textureFloat &&
  62803. !_this._useInGammaSpace;
  62804. }
  62805. else {
  62806. _this._isBABYLONPreprocessed = true;
  62807. _this._noMipmap = false;
  62808. _this._useInGammaSpace = false;
  62809. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  62810. !_this._useInGammaSpace;
  62811. }
  62812. _this.isPMREM = _this._usePMREMGenerator;
  62813. _this._texture = _this._getFromCache(url, _this._noMipmap);
  62814. if (!_this._texture) {
  62815. if (!scene.useDelayedTextureLoading) {
  62816. _this.loadTexture();
  62817. }
  62818. else {
  62819. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62820. }
  62821. }
  62822. return _this;
  62823. }
  62824. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  62825. /**
  62826. * Gets wether or not the texture is blocking during loading.
  62827. */
  62828. get: function () {
  62829. return this._isBlocking;
  62830. },
  62831. /**
  62832. * Sets wether or not the texture is blocking during loading.
  62833. */
  62834. set: function (value) {
  62835. this._isBlocking = value;
  62836. },
  62837. enumerable: true,
  62838. configurable: true
  62839. });
  62840. /**
  62841. * Occurs when the file is a preprocessed .babylon.hdr file.
  62842. */
  62843. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  62844. var _this = this;
  62845. var mipLevels = 0;
  62846. var floatArrayView = null;
  62847. var scene = this.getScene();
  62848. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  62849. var mips = new Array();
  62850. if (!floatArrayView) {
  62851. return mips;
  62852. }
  62853. var startIndex = 30;
  62854. for (var level = 0; level < mipLevels; level++) {
  62855. mips.push([]);
  62856. // Fill each pixel of the mip level.
  62857. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  62858. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62859. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  62860. mips[level].push(faceData);
  62861. startIndex += faceSize;
  62862. }
  62863. }
  62864. return mips;
  62865. } : null;
  62866. var callback = function (buffer) {
  62867. var scene = _this.getScene();
  62868. if (!scene) {
  62869. return null;
  62870. }
  62871. // Create Native Array Views
  62872. var intArrayView = new Int32Array(buffer);
  62873. floatArrayView = new Float32Array(buffer);
  62874. // Fill header.
  62875. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  62876. _this._size = intArrayView[1]; // CubeMap max mip face size.
  62877. // Update Texture Information.
  62878. if (!_this._texture) {
  62879. return null;
  62880. }
  62881. _this._texture.updateSize(_this._size, _this._size);
  62882. // Fill polynomial information.
  62883. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  62884. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  62885. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  62886. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  62887. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  62888. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  62889. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  62890. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  62891. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  62892. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  62893. _this.sphericalPolynomial = sphericalPolynomial;
  62894. // Fill pixel data.
  62895. mipLevels = intArrayView[29]; // Number of mip levels.
  62896. var startIndex = 30;
  62897. var data = [];
  62898. var faceSize = Math.pow(_this._size, 2) * 3;
  62899. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62900. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  62901. startIndex += faceSize;
  62902. }
  62903. var results = [];
  62904. var byteArray = null;
  62905. // Push each faces.
  62906. for (var k = 0; k < 6; k++) {
  62907. var dataFace = null;
  62908. // To be deprecated.
  62909. if (version === 1) {
  62910. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  62911. dataFace = data[j];
  62912. }
  62913. // If special cases.
  62914. if (!mipmapGenerator && dataFace) {
  62915. if (!scene.getEngine().getCaps().textureFloat) {
  62916. // 3 channels of 1 bytes per pixel in bytes.
  62917. var byteBuffer = new ArrayBuffer(faceSize);
  62918. byteArray = new Uint8Array(byteBuffer);
  62919. }
  62920. for (var i = 0; i < _this._size * _this._size; i++) {
  62921. // Put in gamma space if requested.
  62922. if (_this._useInGammaSpace) {
  62923. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  62924. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  62925. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  62926. }
  62927. // Convert to int texture for fallback.
  62928. if (byteArray) {
  62929. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  62930. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  62931. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  62932. // May use luminance instead if the result is not accurate.
  62933. var max = Math.max(Math.max(r, g), b);
  62934. if (max > 255) {
  62935. var scale = 255 / max;
  62936. r *= scale;
  62937. g *= scale;
  62938. b *= scale;
  62939. }
  62940. byteArray[(i * 3) + 0] = r;
  62941. byteArray[(i * 3) + 1] = g;
  62942. byteArray[(i * 3) + 2] = b;
  62943. }
  62944. }
  62945. }
  62946. // Fill the array accordingly.
  62947. if (byteArray) {
  62948. results.push(byteArray);
  62949. }
  62950. else {
  62951. results.push(dataFace);
  62952. }
  62953. }
  62954. return results;
  62955. };
  62956. if (scene) {
  62957. 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);
  62958. }
  62959. };
  62960. /**
  62961. * Occurs when the file is raw .hdr file.
  62962. */
  62963. HDRCubeTexture.prototype.loadHDRTexture = function () {
  62964. var _this = this;
  62965. var callback = function (buffer) {
  62966. var scene = _this.getScene();
  62967. if (!scene) {
  62968. return null;
  62969. }
  62970. // Extract the raw linear data.
  62971. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  62972. // Generate harmonics if needed.
  62973. if (_this._generateHarmonics) {
  62974. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  62975. _this.sphericalPolynomial = sphericalPolynomial;
  62976. }
  62977. var results = [];
  62978. var byteArray = null;
  62979. // Push each faces.
  62980. for (var j = 0; j < 6; j++) {
  62981. // Create uintarray fallback.
  62982. if (!scene.getEngine().getCaps().textureFloat) {
  62983. // 3 channels of 1 bytes per pixel in bytes.
  62984. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  62985. byteArray = new Uint8Array(byteBuffer);
  62986. }
  62987. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  62988. // If special cases.
  62989. if (_this._useInGammaSpace || byteArray) {
  62990. for (var i = 0; i < _this._size * _this._size; i++) {
  62991. // Put in gamma space if requested.
  62992. if (_this._useInGammaSpace) {
  62993. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  62994. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  62995. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  62996. }
  62997. // Convert to int texture for fallback.
  62998. if (byteArray) {
  62999. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63000. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63001. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63002. // May use luminance instead if the result is not accurate.
  63003. var max = Math.max(Math.max(r, g), b);
  63004. if (max > 255) {
  63005. var scale = 255 / max;
  63006. r *= scale;
  63007. g *= scale;
  63008. b *= scale;
  63009. }
  63010. byteArray[(i * 3) + 0] = r;
  63011. byteArray[(i * 3) + 1] = g;
  63012. byteArray[(i * 3) + 2] = b;
  63013. }
  63014. }
  63015. }
  63016. if (byteArray) {
  63017. results.push(byteArray);
  63018. }
  63019. else {
  63020. results.push(dataFace);
  63021. }
  63022. }
  63023. return results;
  63024. };
  63025. var mipmapGenerator = null;
  63026. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63027. // if (!this._noMipmap &&
  63028. // this._usePMREMGenerator) {
  63029. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63030. // // Custom setup of the generator matching with the PBR shader values.
  63031. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63032. // this._size,
  63033. // this._size,
  63034. // 0,
  63035. // 3,
  63036. // this.getScene().getEngine().getCaps().textureFloat,
  63037. // 2048,
  63038. // 0.25,
  63039. // false,
  63040. // true);
  63041. // return generator.filterCubeMap();
  63042. // };
  63043. // }
  63044. var scene = this.getScene();
  63045. if (scene) {
  63046. 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);
  63047. }
  63048. };
  63049. /**
  63050. * Starts the loading process of the texture.
  63051. */
  63052. HDRCubeTexture.prototype.loadTexture = function () {
  63053. if (this._isBABYLONPreprocessed) {
  63054. this.loadBabylonTexture();
  63055. }
  63056. else {
  63057. this.loadHDRTexture();
  63058. }
  63059. };
  63060. HDRCubeTexture.prototype.clone = function () {
  63061. var scene = this.getScene();
  63062. if (!scene) {
  63063. return this;
  63064. }
  63065. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63066. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63067. // Base texture
  63068. newTexture.level = this.level;
  63069. newTexture.wrapU = this.wrapU;
  63070. newTexture.wrapV = this.wrapV;
  63071. newTexture.coordinatesIndex = this.coordinatesIndex;
  63072. newTexture.coordinatesMode = this.coordinatesMode;
  63073. return newTexture;
  63074. };
  63075. // Methods
  63076. HDRCubeTexture.prototype.delayLoad = function () {
  63077. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63078. return;
  63079. }
  63080. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63081. this._texture = this._getFromCache(this.url, this._noMipmap);
  63082. if (!this._texture) {
  63083. this.loadTexture();
  63084. }
  63085. };
  63086. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  63087. return this._textureMatrix;
  63088. };
  63089. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63090. this._textureMatrix = value;
  63091. };
  63092. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63093. var texture = null;
  63094. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63095. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  63096. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  63097. texture.name = parsedTexture.name;
  63098. texture.hasAlpha = parsedTexture.hasAlpha;
  63099. texture.level = parsedTexture.level;
  63100. texture.coordinatesMode = parsedTexture.coordinatesMode;
  63101. texture.isBlocking = parsedTexture.isBlocking;
  63102. }
  63103. return texture;
  63104. };
  63105. HDRCubeTexture.prototype.serialize = function () {
  63106. if (!this.name) {
  63107. return null;
  63108. }
  63109. var serializationObject = {};
  63110. serializationObject.name = this.name;
  63111. serializationObject.hasAlpha = this.hasAlpha;
  63112. serializationObject.isCube = true;
  63113. serializationObject.level = this.level;
  63114. serializationObject.size = this._size;
  63115. serializationObject.coordinatesMode = this.coordinatesMode;
  63116. serializationObject.useInGammaSpace = this._useInGammaSpace;
  63117. serializationObject.generateHarmonics = this._generateHarmonics;
  63118. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  63119. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  63120. serializationObject.customType = "BABYLON.HDRCubeTexture";
  63121. serializationObject.noMipmap = this._noMipmap;
  63122. serializationObject.isBlocking = this._isBlocking;
  63123. return serializationObject;
  63124. };
  63125. /**
  63126. * Saves as a file the data contained in the texture in a binary format.
  63127. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63128. * as the spherical used in the lighting.
  63129. * @param url The HDR file url.
  63130. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63131. * @param onError Method called if any error happens during download.
  63132. * @return The packed binary data.
  63133. */
  63134. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  63135. if (onError === void 0) { onError = null; }
  63136. var callback = function (buffer) {
  63137. var data = new Blob([buffer], { type: 'application/octet-stream' });
  63138. // Returns a URL you can use as a href.
  63139. var objUrl = window.URL.createObjectURL(data);
  63140. // Simulates a link to it and click to dowload.
  63141. var a = document.createElement("a");
  63142. document.body.appendChild(a);
  63143. a.style.display = "none";
  63144. a.href = objUrl;
  63145. a.download = "envmap.babylon.hdr";
  63146. a.click();
  63147. };
  63148. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  63149. };
  63150. /**
  63151. * Serializes the data contained in the texture in a binary format.
  63152. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63153. * as the spherical used in the lighting.
  63154. * @param url The HDR file url.
  63155. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63156. * @param onError Method called if any error happens during download.
  63157. * @return The packed binary data.
  63158. */
  63159. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  63160. if (onError === void 0) { onError = null; }
  63161. // Needs the url tho create the texture.
  63162. if (!url) {
  63163. return;
  63164. }
  63165. // Check Power of two size.
  63166. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  63167. return;
  63168. }
  63169. // Coming Back in 3.x.
  63170. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  63171. };
  63172. HDRCubeTexture._facesMapping = [
  63173. "right",
  63174. "left",
  63175. "up",
  63176. "down",
  63177. "front",
  63178. "back"
  63179. ];
  63180. return HDRCubeTexture;
  63181. }(BABYLON.BaseTexture));
  63182. BABYLON.HDRCubeTexture = HDRCubeTexture;
  63183. })(BABYLON || (BABYLON = {}));
  63184. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  63185. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  63186. // Huge respect for a such great lib.
  63187. // Earcut license:
  63188. // Copyright (c) 2016, Mapbox
  63189. //
  63190. // Permission to use, copy, modify, and/or distribute this software for any purpose
  63191. // with or without fee is hereby granted, provided that the above copyright notice
  63192. // and this permission notice appear in all copies.
  63193. //
  63194. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  63195. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  63196. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  63197. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  63198. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  63199. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  63200. // THIS SOFTWARE.
  63201. var Earcut;
  63202. (function (Earcut) {
  63203. /**
  63204. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  63205. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  63206. * @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).
  63207. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  63208. */
  63209. function earcut(data, holeIndices, dim) {
  63210. dim = dim || 2;
  63211. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  63212. if (!outerNode)
  63213. return triangles;
  63214. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  63215. if (hasHoles)
  63216. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  63217. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  63218. if (data.length > 80 * dim) {
  63219. minX = maxX = data[0];
  63220. minY = maxY = data[1];
  63221. for (var i = dim; i < outerLen; i += dim) {
  63222. x = data[i];
  63223. y = data[i + 1];
  63224. if (x < minX)
  63225. minX = x;
  63226. if (y < minY)
  63227. minY = y;
  63228. if (x > maxX)
  63229. maxX = x;
  63230. if (y > maxY)
  63231. maxY = y;
  63232. }
  63233. // minX, minY and size are later used to transform coords into integers for z-order calculation
  63234. size = Math.max(maxX - minX, maxY - minY);
  63235. }
  63236. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  63237. return triangles;
  63238. }
  63239. Earcut.earcut = earcut;
  63240. var Node = /** @class */ (function () {
  63241. function Node(i, x, y) {
  63242. this.i = i;
  63243. this.x = x;
  63244. this.y = y;
  63245. this.prev = null;
  63246. this.next = null;
  63247. this.z = null;
  63248. this.prevZ = null;
  63249. this.nextZ = null;
  63250. this.steiner = false;
  63251. }
  63252. return Node;
  63253. }());
  63254. // create a circular doubly linked list from polygon points in the specified winding order
  63255. function linkedList(data, start, end, dim, clockwise) {
  63256. var i, last = null;
  63257. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  63258. for (i = start; i < end; i += dim)
  63259. last = insertNode(i, data[i], data[i + 1], last);
  63260. }
  63261. else {
  63262. for (i = end - dim; i >= start; i -= dim)
  63263. last = insertNode(i, data[i], data[i + 1], last);
  63264. }
  63265. if (last && equals(last, last.next)) {
  63266. removeNode(last);
  63267. last = last.next;
  63268. }
  63269. return last;
  63270. }
  63271. // eliminate colinear or duplicate points
  63272. function filterPoints(start, end) {
  63273. if (!start)
  63274. return start;
  63275. if (!end)
  63276. end = start;
  63277. var p = start, again;
  63278. do {
  63279. again = false;
  63280. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  63281. removeNode(p);
  63282. p = end = p.prev;
  63283. if (p === p.next)
  63284. return undefined;
  63285. again = true;
  63286. }
  63287. else {
  63288. p = p.next;
  63289. }
  63290. } while (again || p !== end);
  63291. return end;
  63292. }
  63293. // main ear slicing loop which triangulates a polygon (given as a linked list)
  63294. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63295. if (!ear)
  63296. return;
  63297. // interlink polygon nodes in z-order
  63298. if (!pass && size)
  63299. indexCurve(ear, minX, minY, size);
  63300. var stop = ear, prev, next;
  63301. // iterate through ears, slicing them one by one
  63302. while (ear.prev !== ear.next) {
  63303. prev = ear.prev;
  63304. next = ear.next;
  63305. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  63306. // cut off the triangle
  63307. triangles.push(prev.i / dim);
  63308. triangles.push(ear.i / dim);
  63309. triangles.push(next.i / dim);
  63310. removeNode(ear);
  63311. // skipping the next vertice leads to less sliver triangles
  63312. ear = next.next;
  63313. stop = next.next;
  63314. continue;
  63315. }
  63316. ear = next;
  63317. // if we looped through the whole remaining polygon and can't find any more ears
  63318. if (ear === stop) {
  63319. // try filtering points and slicing again
  63320. if (!pass) {
  63321. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  63322. // if this didn't work, try curing all small self-intersections locally
  63323. }
  63324. else if (pass === 1) {
  63325. ear = cureLocalIntersections(ear, triangles, dim);
  63326. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  63327. // as a last resort, try splitting the remaining polygon into two
  63328. }
  63329. else if (pass === 2) {
  63330. splitEarcut(ear, triangles, dim, minX, minY, size);
  63331. }
  63332. break;
  63333. }
  63334. }
  63335. }
  63336. // check whether a polygon node forms a valid ear with adjacent nodes
  63337. function isEar(ear) {
  63338. var a = ear.prev, b = ear, c = ear.next;
  63339. if (area(a, b, c) >= 0)
  63340. return false; // reflex, can't be an ear
  63341. // now make sure we don't have other points inside the potential ear
  63342. var p = ear.next.next;
  63343. while (p !== ear.prev) {
  63344. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63345. area(p.prev, p, p.next) >= 0)
  63346. return false;
  63347. p = p.next;
  63348. }
  63349. return true;
  63350. }
  63351. function isEarHashed(ear, minX, minY, size) {
  63352. var a = ear.prev, b = ear, c = ear.next;
  63353. if (area(a, b, c) >= 0)
  63354. return false; // reflex, can't be an ear
  63355. // triangle bbox; min & max are calculated like this for speed
  63356. 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);
  63357. // z-order range for the current triangle bbox;
  63358. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  63359. // first look for points inside the triangle in increasing z-order
  63360. var p = ear.nextZ;
  63361. while (p && p.z <= maxZ) {
  63362. if (p !== ear.prev &&
  63363. p !== ear.next &&
  63364. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63365. area(p.prev, p, p.next) >= 0)
  63366. return false;
  63367. p = p.nextZ;
  63368. }
  63369. // then look for points in decreasing z-order
  63370. p = ear.prevZ;
  63371. while (p && p.z >= minZ) {
  63372. if (p !== ear.prev &&
  63373. p !== ear.next &&
  63374. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63375. area(p.prev, p, p.next) >= 0)
  63376. return false;
  63377. p = p.prevZ;
  63378. }
  63379. return true;
  63380. }
  63381. // go through all polygon nodes and cure small local self-intersections
  63382. function cureLocalIntersections(start, triangles, dim) {
  63383. var p = start;
  63384. do {
  63385. var a = p.prev, b = p.next.next;
  63386. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  63387. triangles.push(a.i / dim);
  63388. triangles.push(p.i / dim);
  63389. triangles.push(b.i / dim);
  63390. // remove two nodes involved
  63391. removeNode(p);
  63392. removeNode(p.next);
  63393. p = start = b;
  63394. }
  63395. p = p.next;
  63396. } while (p !== start);
  63397. return p;
  63398. }
  63399. // try splitting polygon into two and triangulate them independently
  63400. function splitEarcut(start, triangles, dim, minX, minY, size) {
  63401. // look for a valid diagonal that divides the polygon into two
  63402. var a = start;
  63403. do {
  63404. var b = a.next.next;
  63405. while (b !== a.prev) {
  63406. if (a.i !== b.i && isValidDiagonal(a, b)) {
  63407. // split the polygon in two by the diagonal
  63408. var c = splitPolygon(a, b);
  63409. // filter colinear points around the cuts
  63410. a = filterPoints(a, a.next);
  63411. c = filterPoints(c, c.next);
  63412. // run earcut on each half
  63413. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  63414. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  63415. return;
  63416. }
  63417. b = b.next;
  63418. }
  63419. a = a.next;
  63420. } while (a !== start);
  63421. }
  63422. // link every hole into the outer loop, producing a single-ring polygon without holes
  63423. function eliminateHoles(data, holeIndices, outerNode, dim) {
  63424. var queue = [], i, len, start, end, list;
  63425. for (i = 0, len = holeIndices.length; i < len; i++) {
  63426. start = holeIndices[i] * dim;
  63427. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63428. list = linkedList(data, start, end, dim, false);
  63429. if (list === list.next)
  63430. list.steiner = true;
  63431. queue.push(getLeftmost(list));
  63432. }
  63433. queue.sort(compareX);
  63434. // process holes from left to right
  63435. for (i = 0; i < queue.length; i++) {
  63436. eliminateHole(queue[i], outerNode);
  63437. outerNode = filterPoints(outerNode, outerNode.next);
  63438. }
  63439. return outerNode;
  63440. }
  63441. function compareX(a, b) {
  63442. return a.x - b.x;
  63443. }
  63444. // find a bridge between vertices that connects hole with an outer ring and and link it
  63445. function eliminateHole(hole, outerNode) {
  63446. outerNode = findHoleBridge(hole, outerNode);
  63447. if (outerNode) {
  63448. var b = splitPolygon(outerNode, hole);
  63449. filterPoints(b, b.next);
  63450. }
  63451. }
  63452. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  63453. function findHoleBridge(hole, outerNode) {
  63454. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  63455. // find a segment intersected by a ray from the hole's leftmost point to the left;
  63456. // segment's endpoint with lesser x will be potential connection point
  63457. do {
  63458. if (hy <= p.y && hy >= p.next.y) {
  63459. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  63460. if (x <= hx && x > qx) {
  63461. qx = x;
  63462. if (x === hx) {
  63463. if (hy === p.y)
  63464. return p;
  63465. if (hy === p.next.y)
  63466. return p.next;
  63467. }
  63468. m = p.x < p.next.x ? p : p.next;
  63469. }
  63470. }
  63471. p = p.next;
  63472. } while (p !== outerNode);
  63473. if (!m)
  63474. return null;
  63475. if (hx === qx)
  63476. return m.prev; // hole touches outer segment; pick lower endpoint
  63477. // look for points inside the triangle of hole point, segment intersection and endpoint;
  63478. // if there are no points found, we have a valid connection;
  63479. // otherwise choose the point of the minimum angle with the ray as connection point
  63480. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  63481. p = m.next;
  63482. while (p !== stop) {
  63483. if (hx >= p.x &&
  63484. p.x >= mx &&
  63485. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  63486. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  63487. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  63488. m = p;
  63489. tanMin = tan;
  63490. }
  63491. }
  63492. p = p.next;
  63493. }
  63494. return m;
  63495. }
  63496. // interlink polygon nodes in z-order
  63497. function indexCurve(start, minX, minY, size) {
  63498. var p = start;
  63499. do {
  63500. if (p.z === null)
  63501. p.z = zOrder(p.x, p.y, minX, minY, size);
  63502. p.prevZ = p.prev;
  63503. p.nextZ = p.next;
  63504. p = p.next;
  63505. } while (p !== start);
  63506. p.prevZ.nextZ = null;
  63507. p.prevZ = null;
  63508. sortLinked(p);
  63509. }
  63510. // Simon Tatham's linked list merge sort algorithm
  63511. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  63512. function sortLinked(list) {
  63513. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  63514. do {
  63515. p = list;
  63516. list = null;
  63517. tail = null;
  63518. numMerges = 0;
  63519. while (p) {
  63520. numMerges++;
  63521. q = p;
  63522. pSize = 0;
  63523. for (i = 0; i < inSize; i++) {
  63524. pSize++;
  63525. q = q.nextZ;
  63526. if (!q)
  63527. break;
  63528. }
  63529. qSize = inSize;
  63530. while (pSize > 0 || (qSize > 0 && q)) {
  63531. if (pSize === 0) {
  63532. e = q;
  63533. q = q.nextZ;
  63534. qSize--;
  63535. }
  63536. else if (qSize === 0 || !q) {
  63537. e = p;
  63538. p = p.nextZ;
  63539. pSize--;
  63540. }
  63541. else if (p.z <= q.z) {
  63542. e = p;
  63543. p = p.nextZ;
  63544. pSize--;
  63545. }
  63546. else {
  63547. e = q;
  63548. q = q.nextZ;
  63549. qSize--;
  63550. }
  63551. if (tail)
  63552. tail.nextZ = e;
  63553. else
  63554. list = e;
  63555. e.prevZ = tail;
  63556. tail = e;
  63557. }
  63558. p = q;
  63559. }
  63560. tail.nextZ = null;
  63561. inSize *= 2;
  63562. } while (numMerges > 1);
  63563. return list;
  63564. }
  63565. // z-order of a point given coords and size of the data bounding box
  63566. function zOrder(x, y, minX, minY, size) {
  63567. // coords are transformed into non-negative 15-bit integer range
  63568. x = 32767 * (x - minX) / size;
  63569. y = 32767 * (y - minY) / size;
  63570. x = (x | (x << 8)) & 0x00FF00FF;
  63571. x = (x | (x << 4)) & 0x0F0F0F0F;
  63572. x = (x | (x << 2)) & 0x33333333;
  63573. x = (x | (x << 1)) & 0x55555555;
  63574. y = (y | (y << 8)) & 0x00FF00FF;
  63575. y = (y | (y << 4)) & 0x0F0F0F0F;
  63576. y = (y | (y << 2)) & 0x33333333;
  63577. y = (y | (y << 1)) & 0x55555555;
  63578. return x | (y << 1);
  63579. }
  63580. // find the leftmost node of a polygon ring
  63581. function getLeftmost(start) {
  63582. var p = start, leftmost = start;
  63583. do {
  63584. if (p.x < leftmost.x)
  63585. leftmost = p;
  63586. p = p.next;
  63587. } while (p !== start);
  63588. return leftmost;
  63589. }
  63590. // check if a point lies within a convex triangle
  63591. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  63592. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  63593. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  63594. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  63595. }
  63596. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  63597. function isValidDiagonal(a, b) {
  63598. return a.next.i !== b.i &&
  63599. a.prev.i !== b.i &&
  63600. !intersectsPolygon(a, b) &&
  63601. locallyInside(a, b) &&
  63602. locallyInside(b, a) &&
  63603. middleInside(a, b);
  63604. }
  63605. // signed area of a triangle
  63606. function area(p, q, r) {
  63607. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  63608. }
  63609. // check if two points are equal
  63610. function equals(p1, p2) {
  63611. return p1.x === p2.x && p1.y === p2.y;
  63612. }
  63613. // check if two segments intersect
  63614. function intersects(p1, q1, p2, q2) {
  63615. if ((equals(p1, q1) && equals(p2, q2)) ||
  63616. (equals(p1, q2) && equals(p2, q1)))
  63617. return true;
  63618. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  63619. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  63620. }
  63621. // check if a polygon diagonal intersects any polygon segments
  63622. function intersectsPolygon(a, b) {
  63623. var p = a;
  63624. do {
  63625. if (p.i !== a.i &&
  63626. p.next.i !== a.i &&
  63627. p.i !== b.i &&
  63628. p.next.i !== b.i &&
  63629. intersects(p, p.next, a, b))
  63630. return true;
  63631. p = p.next;
  63632. } while (p !== a);
  63633. return false;
  63634. }
  63635. // check if a polygon diagonal is locally inside the polygon
  63636. function locallyInside(a, b) {
  63637. return area(a.prev, a, a.next) < 0
  63638. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  63639. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  63640. }
  63641. // check if the middle point of a polygon diagonal is inside the polygon
  63642. function middleInside(a, b) {
  63643. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  63644. do {
  63645. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  63646. inside = !inside;
  63647. p = p.next;
  63648. } while (p !== a);
  63649. return inside;
  63650. }
  63651. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  63652. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  63653. function splitPolygon(a, b) {
  63654. 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;
  63655. a.next = b;
  63656. b.prev = a;
  63657. a2.next = an;
  63658. an.prev = a2;
  63659. b2.next = a2;
  63660. a2.prev = b2;
  63661. bp.next = b2;
  63662. b2.prev = bp;
  63663. return b2;
  63664. }
  63665. // create a node and optionally link it with previous one (in a circular doubly linked list)
  63666. function insertNode(i, x, y, last) {
  63667. var p = new Node(i, x, y);
  63668. if (!last) {
  63669. p.prev = p;
  63670. p.next = p;
  63671. }
  63672. else {
  63673. p.next = last.next;
  63674. p.prev = last;
  63675. last.next.prev = p;
  63676. last.next = p;
  63677. }
  63678. return p;
  63679. }
  63680. function removeNode(p) {
  63681. p.next.prev = p.prev;
  63682. p.prev.next = p.next;
  63683. if (p.prevZ)
  63684. p.prevZ.nextZ = p.nextZ;
  63685. if (p.nextZ)
  63686. p.nextZ.prevZ = p.prevZ;
  63687. }
  63688. /**
  63689. * return a percentage difference between the polygon area and its triangulation area;
  63690. * used to verify correctness of triangulation
  63691. */
  63692. function deviation(data, holeIndices, dim, triangles) {
  63693. var hasHoles = holeIndices && holeIndices.length;
  63694. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  63695. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  63696. if (hasHoles) {
  63697. for (var i = 0, len = holeIndices.length; i < len; i++) {
  63698. var start = holeIndices[i] * dim;
  63699. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63700. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  63701. }
  63702. }
  63703. var trianglesArea = 0;
  63704. for (i = 0; i < triangles.length; i += 3) {
  63705. var a = triangles[i] * dim;
  63706. var b = triangles[i + 1] * dim;
  63707. var c = triangles[i + 2] * dim;
  63708. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  63709. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  63710. }
  63711. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  63712. }
  63713. Earcut.deviation = deviation;
  63714. ;
  63715. function signedArea(data, start, end, dim) {
  63716. var sum = 0;
  63717. for (var i = start, j = end - dim; i < end; i += dim) {
  63718. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  63719. j = i;
  63720. }
  63721. return sum;
  63722. }
  63723. /**
  63724. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  63725. */
  63726. function flatten(data) {
  63727. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  63728. for (var i = 0; i < data.length; i++) {
  63729. for (var j = 0; j < data[i].length; j++) {
  63730. for (var d = 0; d < dim; d++)
  63731. result.vertices.push(data[i][j][d]);
  63732. }
  63733. if (i > 0) {
  63734. holeIndex += data[i - 1].length;
  63735. result.holes.push(holeIndex);
  63736. }
  63737. }
  63738. return result;
  63739. }
  63740. Earcut.flatten = flatten;
  63741. ;
  63742. })(Earcut || (Earcut = {}));
  63743. //# sourceMappingURL=babylon.earcut.js.map
  63744. var BABYLON;
  63745. (function (BABYLON) {
  63746. var IndexedVector2 = /** @class */ (function (_super) {
  63747. __extends(IndexedVector2, _super);
  63748. function IndexedVector2(original, index) {
  63749. var _this = _super.call(this, original.x, original.y) || this;
  63750. _this.index = index;
  63751. return _this;
  63752. }
  63753. return IndexedVector2;
  63754. }(BABYLON.Vector2));
  63755. var PolygonPoints = /** @class */ (function () {
  63756. function PolygonPoints() {
  63757. this.elements = new Array();
  63758. }
  63759. PolygonPoints.prototype.add = function (originalPoints) {
  63760. var _this = this;
  63761. var result = new Array();
  63762. originalPoints.forEach(function (point) {
  63763. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  63764. var newPoint = new IndexedVector2(point, _this.elements.length);
  63765. result.push(newPoint);
  63766. _this.elements.push(newPoint);
  63767. }
  63768. });
  63769. return result;
  63770. };
  63771. PolygonPoints.prototype.computeBounds = function () {
  63772. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63773. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63774. this.elements.forEach(function (point) {
  63775. // x
  63776. if (point.x < lmin.x) {
  63777. lmin.x = point.x;
  63778. }
  63779. else if (point.x > lmax.x) {
  63780. lmax.x = point.x;
  63781. }
  63782. // y
  63783. if (point.y < lmin.y) {
  63784. lmin.y = point.y;
  63785. }
  63786. else if (point.y > lmax.y) {
  63787. lmax.y = point.y;
  63788. }
  63789. });
  63790. return {
  63791. min: lmin,
  63792. max: lmax,
  63793. width: lmax.x - lmin.x,
  63794. height: lmax.y - lmin.y
  63795. };
  63796. };
  63797. return PolygonPoints;
  63798. }());
  63799. var Polygon = /** @class */ (function () {
  63800. function Polygon() {
  63801. }
  63802. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  63803. return [
  63804. new BABYLON.Vector2(xmin, ymin),
  63805. new BABYLON.Vector2(xmax, ymin),
  63806. new BABYLON.Vector2(xmax, ymax),
  63807. new BABYLON.Vector2(xmin, ymax)
  63808. ];
  63809. };
  63810. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  63811. if (cx === void 0) { cx = 0; }
  63812. if (cy === void 0) { cy = 0; }
  63813. if (numberOfSides === void 0) { numberOfSides = 32; }
  63814. var result = new Array();
  63815. var angle = 0;
  63816. var increment = (Math.PI * 2) / numberOfSides;
  63817. for (var i = 0; i < numberOfSides; i++) {
  63818. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  63819. angle -= increment;
  63820. }
  63821. return result;
  63822. };
  63823. Polygon.Parse = function (input) {
  63824. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  63825. var i, result = [];
  63826. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  63827. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  63828. }
  63829. return result;
  63830. };
  63831. Polygon.StartingAt = function (x, y) {
  63832. return BABYLON.Path2.StartingAt(x, y);
  63833. };
  63834. return Polygon;
  63835. }());
  63836. BABYLON.Polygon = Polygon;
  63837. var PolygonMeshBuilder = /** @class */ (function () {
  63838. function PolygonMeshBuilder(name, contours, scene) {
  63839. this._points = new PolygonPoints();
  63840. this._outlinepoints = new PolygonPoints();
  63841. this._holes = new Array();
  63842. this._epoints = new Array();
  63843. this._eholes = new Array();
  63844. this._name = name;
  63845. this._scene = scene;
  63846. var points;
  63847. if (contours instanceof BABYLON.Path2) {
  63848. points = contours.getPoints();
  63849. }
  63850. else {
  63851. points = contours;
  63852. }
  63853. this._addToepoint(points);
  63854. this._points.add(points);
  63855. this._outlinepoints.add(points);
  63856. }
  63857. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  63858. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  63859. var p = points_1[_i];
  63860. this._epoints.push(p.x, p.y);
  63861. }
  63862. };
  63863. PolygonMeshBuilder.prototype.addHole = function (hole) {
  63864. this._points.add(hole);
  63865. var holepoints = new PolygonPoints();
  63866. holepoints.add(hole);
  63867. this._holes.push(holepoints);
  63868. this._eholes.push(this._epoints.length / 2);
  63869. this._addToepoint(hole);
  63870. return this;
  63871. };
  63872. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  63873. var _this = this;
  63874. if (updatable === void 0) { updatable = false; }
  63875. if (depth === void 0) { depth = 0; }
  63876. var result = new BABYLON.Mesh(this._name, this._scene);
  63877. var normals = new Array();
  63878. var positions = new Array();
  63879. var uvs = new Array();
  63880. var bounds = this._points.computeBounds();
  63881. this._points.elements.forEach(function (p) {
  63882. normals.push(0, 1.0, 0);
  63883. positions.push(p.x, 0, p.y);
  63884. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  63885. });
  63886. var indices = new Array();
  63887. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  63888. for (var i = 0; i < res.length; i++) {
  63889. indices.push(res[i]);
  63890. }
  63891. if (depth > 0) {
  63892. var positionscount = (positions.length / 3); //get the current pointcount
  63893. this._points.elements.forEach(function (p) {
  63894. normals.push(0, -1.0, 0);
  63895. positions.push(p.x, -depth, p.y);
  63896. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  63897. });
  63898. var totalCount = indices.length;
  63899. for (var i = 0; i < totalCount; i += 3) {
  63900. var i0 = indices[i + 0];
  63901. var i1 = indices[i + 1];
  63902. var i2 = indices[i + 2];
  63903. indices.push(i2 + positionscount);
  63904. indices.push(i1 + positionscount);
  63905. indices.push(i0 + positionscount);
  63906. }
  63907. //Add the sides
  63908. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  63909. this._holes.forEach(function (hole) {
  63910. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  63911. });
  63912. }
  63913. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  63914. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  63915. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  63916. result.setIndices(indices);
  63917. return result;
  63918. };
  63919. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  63920. var StartIndex = positions.length / 3;
  63921. var ulength = 0;
  63922. for (var i = 0; i < points.elements.length; i++) {
  63923. var p = points.elements[i];
  63924. var p1;
  63925. if ((i + 1) > points.elements.length - 1) {
  63926. p1 = points.elements[0];
  63927. }
  63928. else {
  63929. p1 = points.elements[i + 1];
  63930. }
  63931. positions.push(p.x, 0, p.y);
  63932. positions.push(p.x, -depth, p.y);
  63933. positions.push(p1.x, 0, p1.y);
  63934. positions.push(p1.x, -depth, p1.y);
  63935. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  63936. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  63937. var v3 = v2.subtract(v1);
  63938. var v4 = new BABYLON.Vector3(0, 1, 0);
  63939. var vn = BABYLON.Vector3.Cross(v3, v4);
  63940. vn = vn.normalize();
  63941. uvs.push(ulength / bounds.width, 0);
  63942. uvs.push(ulength / bounds.width, 1);
  63943. ulength += v3.length();
  63944. uvs.push((ulength / bounds.width), 0);
  63945. uvs.push((ulength / bounds.width), 1);
  63946. if (!flip) {
  63947. normals.push(-vn.x, -vn.y, -vn.z);
  63948. normals.push(-vn.x, -vn.y, -vn.z);
  63949. normals.push(-vn.x, -vn.y, -vn.z);
  63950. normals.push(-vn.x, -vn.y, -vn.z);
  63951. indices.push(StartIndex);
  63952. indices.push(StartIndex + 1);
  63953. indices.push(StartIndex + 2);
  63954. indices.push(StartIndex + 1);
  63955. indices.push(StartIndex + 3);
  63956. indices.push(StartIndex + 2);
  63957. }
  63958. else {
  63959. normals.push(vn.x, vn.y, vn.z);
  63960. normals.push(vn.x, vn.y, vn.z);
  63961. normals.push(vn.x, vn.y, vn.z);
  63962. normals.push(vn.x, vn.y, vn.z);
  63963. indices.push(StartIndex);
  63964. indices.push(StartIndex + 2);
  63965. indices.push(StartIndex + 1);
  63966. indices.push(StartIndex + 1);
  63967. indices.push(StartIndex + 2);
  63968. indices.push(StartIndex + 3);
  63969. }
  63970. StartIndex += 4;
  63971. }
  63972. ;
  63973. };
  63974. return PolygonMeshBuilder;
  63975. }());
  63976. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  63977. })(BABYLON || (BABYLON = {}));
  63978. //# sourceMappingURL=babylon.polygonMesh.js.map
  63979. var BABYLON;
  63980. (function (BABYLON) {
  63981. // Unique ID when we import meshes from Babylon to CSG
  63982. var currentCSGMeshId = 0;
  63983. // # class Vertex
  63984. // Represents a vertex of a polygon. Use your own vertex class instead of this
  63985. // one to provide additional features like texture coordinates and vertex
  63986. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  63987. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  63988. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  63989. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  63990. // is not used anywhere else.
  63991. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  63992. var Vertex = /** @class */ (function () {
  63993. function Vertex(pos, normal, uv) {
  63994. this.pos = pos;
  63995. this.normal = normal;
  63996. this.uv = uv;
  63997. }
  63998. Vertex.prototype.clone = function () {
  63999. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  64000. };
  64001. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  64002. // orientation of a polygon is flipped.
  64003. Vertex.prototype.flip = function () {
  64004. this.normal = this.normal.scale(-1);
  64005. };
  64006. // Create a new vertex between this vertex and `other` by linearly
  64007. // interpolating all properties using a parameter of `t`. Subclasses should
  64008. // override this to interpolate additional properties.
  64009. Vertex.prototype.interpolate = function (other, t) {
  64010. 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));
  64011. };
  64012. return Vertex;
  64013. }());
  64014. // # class Plane
  64015. // Represents a plane in 3D space.
  64016. var Plane = /** @class */ (function () {
  64017. function Plane(normal, w) {
  64018. this.normal = normal;
  64019. this.w = w;
  64020. }
  64021. Plane.FromPoints = function (a, b, c) {
  64022. var v0 = c.subtract(a);
  64023. var v1 = b.subtract(a);
  64024. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64025. return null;
  64026. }
  64027. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64028. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64029. };
  64030. Plane.prototype.clone = function () {
  64031. return new Plane(this.normal.clone(), this.w);
  64032. };
  64033. Plane.prototype.flip = function () {
  64034. this.normal.scaleInPlace(-1);
  64035. this.w = -this.w;
  64036. };
  64037. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64038. // fragments in the appropriate lists. Coplanar polygons go into either
  64039. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64040. // respect to this plane. Polygons in front or in back of this plane go into
  64041. // either `front` or `back`.
  64042. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64043. var COPLANAR = 0;
  64044. var FRONT = 1;
  64045. var BACK = 2;
  64046. var SPANNING = 3;
  64047. // Classify each point as well as the entire polygon into one of the above
  64048. // four classes.
  64049. var polygonType = 0;
  64050. var types = [];
  64051. var i;
  64052. var t;
  64053. for (i = 0; i < polygon.vertices.length; i++) {
  64054. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64055. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64056. polygonType |= type;
  64057. types.push(type);
  64058. }
  64059. // Put the polygon in the correct list, splitting it when necessary.
  64060. switch (polygonType) {
  64061. case COPLANAR:
  64062. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64063. break;
  64064. case FRONT:
  64065. front.push(polygon);
  64066. break;
  64067. case BACK:
  64068. back.push(polygon);
  64069. break;
  64070. case SPANNING:
  64071. var f = [], b = [];
  64072. for (i = 0; i < polygon.vertices.length; i++) {
  64073. var j = (i + 1) % polygon.vertices.length;
  64074. var ti = types[i], tj = types[j];
  64075. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64076. if (ti !== BACK)
  64077. f.push(vi);
  64078. if (ti !== FRONT)
  64079. b.push(ti !== BACK ? vi.clone() : vi);
  64080. if ((ti | tj) === SPANNING) {
  64081. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  64082. var v = vi.interpolate(vj, t);
  64083. f.push(v);
  64084. b.push(v.clone());
  64085. }
  64086. }
  64087. var poly;
  64088. if (f.length >= 3) {
  64089. poly = new Polygon(f, polygon.shared);
  64090. if (poly.plane)
  64091. front.push(poly);
  64092. }
  64093. if (b.length >= 3) {
  64094. poly = new Polygon(b, polygon.shared);
  64095. if (poly.plane)
  64096. back.push(poly);
  64097. }
  64098. break;
  64099. }
  64100. };
  64101. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  64102. // point is on the plane.
  64103. Plane.EPSILON = 1e-5;
  64104. return Plane;
  64105. }());
  64106. // # class Polygon
  64107. // Represents a convex polygon. The vertices used to initialize a polygon must
  64108. // be coplanar and form a convex loop.
  64109. //
  64110. // Each convex polygon has a `shared` property, which is shared between all
  64111. // polygons that are clones of each other or were split from the same polygon.
  64112. // This can be used to define per-polygon properties (such as surface color).
  64113. var Polygon = /** @class */ (function () {
  64114. function Polygon(vertices, shared) {
  64115. this.vertices = vertices;
  64116. this.shared = shared;
  64117. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  64118. }
  64119. Polygon.prototype.clone = function () {
  64120. var vertices = this.vertices.map(function (v) { return v.clone(); });
  64121. return new Polygon(vertices, this.shared);
  64122. };
  64123. Polygon.prototype.flip = function () {
  64124. this.vertices.reverse().map(function (v) { v.flip(); });
  64125. this.plane.flip();
  64126. };
  64127. return Polygon;
  64128. }());
  64129. // # class Node
  64130. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  64131. // by picking a polygon to split along. That polygon (and all other coplanar
  64132. // polygons) are added directly to that node and the other polygons are added to
  64133. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  64134. // no distinction between internal and leaf nodes.
  64135. var Node = /** @class */ (function () {
  64136. function Node(polygons) {
  64137. this.plane = null;
  64138. this.front = null;
  64139. this.back = null;
  64140. this.polygons = new Array();
  64141. if (polygons) {
  64142. this.build(polygons);
  64143. }
  64144. }
  64145. Node.prototype.clone = function () {
  64146. var node = new Node();
  64147. node.plane = this.plane && this.plane.clone();
  64148. node.front = this.front && this.front.clone();
  64149. node.back = this.back && this.back.clone();
  64150. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  64151. return node;
  64152. };
  64153. // Convert solid space to empty space and empty space to solid space.
  64154. Node.prototype.invert = function () {
  64155. for (var i = 0; i < this.polygons.length; i++) {
  64156. this.polygons[i].flip();
  64157. }
  64158. if (this.plane) {
  64159. this.plane.flip();
  64160. }
  64161. if (this.front) {
  64162. this.front.invert();
  64163. }
  64164. if (this.back) {
  64165. this.back.invert();
  64166. }
  64167. var temp = this.front;
  64168. this.front = this.back;
  64169. this.back = temp;
  64170. };
  64171. // Recursively remove all polygons in `polygons` that are inside this BSP
  64172. // tree.
  64173. Node.prototype.clipPolygons = function (polygons) {
  64174. if (!this.plane)
  64175. return polygons.slice();
  64176. var front = new Array(), back = new Array();
  64177. for (var i = 0; i < polygons.length; i++) {
  64178. this.plane.splitPolygon(polygons[i], front, back, front, back);
  64179. }
  64180. if (this.front) {
  64181. front = this.front.clipPolygons(front);
  64182. }
  64183. if (this.back) {
  64184. back = this.back.clipPolygons(back);
  64185. }
  64186. else {
  64187. back = [];
  64188. }
  64189. return front.concat(back);
  64190. };
  64191. // Remove all polygons in this BSP tree that are inside the other BSP tree
  64192. // `bsp`.
  64193. Node.prototype.clipTo = function (bsp) {
  64194. this.polygons = bsp.clipPolygons(this.polygons);
  64195. if (this.front)
  64196. this.front.clipTo(bsp);
  64197. if (this.back)
  64198. this.back.clipTo(bsp);
  64199. };
  64200. // Return a list of all polygons in this BSP tree.
  64201. Node.prototype.allPolygons = function () {
  64202. var polygons = this.polygons.slice();
  64203. if (this.front)
  64204. polygons = polygons.concat(this.front.allPolygons());
  64205. if (this.back)
  64206. polygons = polygons.concat(this.back.allPolygons());
  64207. return polygons;
  64208. };
  64209. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  64210. // new polygons are filtered down to the bottom of the tree and become new
  64211. // nodes there. Each set of polygons is partitioned using the first polygon
  64212. // (no heuristic is used to pick a good split).
  64213. Node.prototype.build = function (polygons) {
  64214. if (!polygons.length)
  64215. return;
  64216. if (!this.plane)
  64217. this.plane = polygons[0].plane.clone();
  64218. var front = new Array(), back = new Array();
  64219. for (var i = 0; i < polygons.length; i++) {
  64220. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  64221. }
  64222. if (front.length) {
  64223. if (!this.front)
  64224. this.front = new Node();
  64225. this.front.build(front);
  64226. }
  64227. if (back.length) {
  64228. if (!this.back)
  64229. this.back = new Node();
  64230. this.back.build(back);
  64231. }
  64232. };
  64233. return Node;
  64234. }());
  64235. var CSG = /** @class */ (function () {
  64236. function CSG() {
  64237. this.polygons = new Array();
  64238. }
  64239. // Convert BABYLON.Mesh to BABYLON.CSG
  64240. CSG.FromMesh = function (mesh) {
  64241. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  64242. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  64243. if (mesh instanceof BABYLON.Mesh) {
  64244. mesh.computeWorldMatrix(true);
  64245. matrix = mesh.getWorldMatrix();
  64246. meshPosition = mesh.position.clone();
  64247. meshRotation = mesh.rotation.clone();
  64248. if (mesh.rotationQuaternion) {
  64249. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  64250. }
  64251. meshScaling = mesh.scaling.clone();
  64252. }
  64253. else {
  64254. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  64255. }
  64256. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64257. var subMeshes = mesh.subMeshes;
  64258. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  64259. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  64260. vertices = [];
  64261. for (var j = 0; j < 3; j++) {
  64262. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  64263. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  64264. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  64265. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  64266. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  64267. vertex = new Vertex(position, normal, uv);
  64268. vertices.push(vertex);
  64269. }
  64270. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  64271. // To handle the case of degenerated triangle
  64272. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  64273. if (polygon.plane)
  64274. polygons.push(polygon);
  64275. }
  64276. }
  64277. var csg = CSG.FromPolygons(polygons);
  64278. csg.matrix = matrix;
  64279. csg.position = meshPosition;
  64280. csg.rotation = meshRotation;
  64281. csg.scaling = meshScaling;
  64282. csg.rotationQuaternion = meshRotationQuaternion;
  64283. currentCSGMeshId++;
  64284. return csg;
  64285. };
  64286. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  64287. CSG.FromPolygons = function (polygons) {
  64288. var csg = new CSG();
  64289. csg.polygons = polygons;
  64290. return csg;
  64291. };
  64292. CSG.prototype.clone = function () {
  64293. var csg = new CSG();
  64294. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  64295. csg.copyTransformAttributes(this);
  64296. return csg;
  64297. };
  64298. CSG.prototype.union = function (csg) {
  64299. var a = new Node(this.clone().polygons);
  64300. var b = new Node(csg.clone().polygons);
  64301. a.clipTo(b);
  64302. b.clipTo(a);
  64303. b.invert();
  64304. b.clipTo(a);
  64305. b.invert();
  64306. a.build(b.allPolygons());
  64307. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64308. };
  64309. CSG.prototype.unionInPlace = function (csg) {
  64310. var a = new Node(this.polygons);
  64311. var b = new Node(csg.polygons);
  64312. a.clipTo(b);
  64313. b.clipTo(a);
  64314. b.invert();
  64315. b.clipTo(a);
  64316. b.invert();
  64317. a.build(b.allPolygons());
  64318. this.polygons = a.allPolygons();
  64319. };
  64320. CSG.prototype.subtract = function (csg) {
  64321. var a = new Node(this.clone().polygons);
  64322. var b = new Node(csg.clone().polygons);
  64323. a.invert();
  64324. a.clipTo(b);
  64325. b.clipTo(a);
  64326. b.invert();
  64327. b.clipTo(a);
  64328. b.invert();
  64329. a.build(b.allPolygons());
  64330. a.invert();
  64331. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64332. };
  64333. CSG.prototype.subtractInPlace = function (csg) {
  64334. var a = new Node(this.polygons);
  64335. var b = new Node(csg.polygons);
  64336. a.invert();
  64337. a.clipTo(b);
  64338. b.clipTo(a);
  64339. b.invert();
  64340. b.clipTo(a);
  64341. b.invert();
  64342. a.build(b.allPolygons());
  64343. a.invert();
  64344. this.polygons = a.allPolygons();
  64345. };
  64346. CSG.prototype.intersect = function (csg) {
  64347. var a = new Node(this.clone().polygons);
  64348. var b = new Node(csg.clone().polygons);
  64349. a.invert();
  64350. b.clipTo(a);
  64351. b.invert();
  64352. a.clipTo(b);
  64353. b.clipTo(a);
  64354. a.build(b.allPolygons());
  64355. a.invert();
  64356. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64357. };
  64358. CSG.prototype.intersectInPlace = function (csg) {
  64359. var a = new Node(this.polygons);
  64360. var b = new Node(csg.polygons);
  64361. a.invert();
  64362. b.clipTo(a);
  64363. b.invert();
  64364. a.clipTo(b);
  64365. b.clipTo(a);
  64366. a.build(b.allPolygons());
  64367. a.invert();
  64368. this.polygons = a.allPolygons();
  64369. };
  64370. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  64371. // not modified.
  64372. CSG.prototype.inverse = function () {
  64373. var csg = this.clone();
  64374. csg.inverseInPlace();
  64375. return csg;
  64376. };
  64377. CSG.prototype.inverseInPlace = function () {
  64378. this.polygons.map(function (p) { p.flip(); });
  64379. };
  64380. // This is used to keep meshes transformations so they can be restored
  64381. // when we build back a Babylon Mesh
  64382. // NB : All CSG operations are performed in world coordinates
  64383. CSG.prototype.copyTransformAttributes = function (csg) {
  64384. this.matrix = csg.matrix;
  64385. this.position = csg.position;
  64386. this.rotation = csg.rotation;
  64387. this.scaling = csg.scaling;
  64388. this.rotationQuaternion = csg.rotationQuaternion;
  64389. return this;
  64390. };
  64391. // Build Raw mesh from CSG
  64392. // Coordinates here are in world space
  64393. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  64394. var matrix = this.matrix.clone();
  64395. matrix.invert();
  64396. 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;
  64397. if (keepSubMeshes) {
  64398. // Sort Polygons, since subMeshes are indices range
  64399. polygons.sort(function (a, b) {
  64400. if (a.shared.meshId === b.shared.meshId) {
  64401. return a.shared.subMeshId - b.shared.subMeshId;
  64402. }
  64403. else {
  64404. return a.shared.meshId - b.shared.meshId;
  64405. }
  64406. });
  64407. }
  64408. for (var i = 0, il = polygons.length; i < il; i++) {
  64409. polygon = polygons[i];
  64410. // Building SubMeshes
  64411. if (!subMesh_dict[polygon.shared.meshId]) {
  64412. subMesh_dict[polygon.shared.meshId] = {};
  64413. }
  64414. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  64415. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  64416. indexStart: +Infinity,
  64417. indexEnd: -Infinity,
  64418. materialIndex: polygon.shared.materialIndex
  64419. };
  64420. }
  64421. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  64422. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  64423. polygonIndices[0] = 0;
  64424. polygonIndices[1] = j - 1;
  64425. polygonIndices[2] = j;
  64426. for (var k = 0; k < 3; k++) {
  64427. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  64428. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  64429. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  64430. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  64431. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  64432. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  64433. // Check if 2 points can be merged
  64434. if (!(typeof vertex_idx !== 'undefined' &&
  64435. normals[vertex_idx * 3] === localNormal.x &&
  64436. normals[vertex_idx * 3 + 1] === localNormal.y &&
  64437. normals[vertex_idx * 3 + 2] === localNormal.z &&
  64438. uvs[vertex_idx * 2] === uv.x &&
  64439. uvs[vertex_idx * 2 + 1] === uv.y)) {
  64440. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  64441. uvs.push(uv.x, uv.y);
  64442. normals.push(normal.x, normal.y, normal.z);
  64443. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  64444. }
  64445. indices.push(vertex_idx);
  64446. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  64447. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  64448. currentIndex++;
  64449. }
  64450. }
  64451. }
  64452. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  64453. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  64454. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  64455. mesh.setIndices(indices, null);
  64456. if (keepSubMeshes) {
  64457. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  64458. var materialIndexOffset = 0, materialMaxIndex;
  64459. mesh.subMeshes = new Array();
  64460. for (var m in subMesh_dict) {
  64461. materialMaxIndex = -1;
  64462. for (var sm in subMesh_dict[m]) {
  64463. subMesh_obj = subMesh_dict[m][sm];
  64464. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  64465. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  64466. }
  64467. materialIndexOffset += ++materialMaxIndex;
  64468. }
  64469. }
  64470. return mesh;
  64471. };
  64472. // Build Mesh from CSG taking material and transforms into account
  64473. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  64474. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  64475. mesh.material = material;
  64476. mesh.position.copyFrom(this.position);
  64477. mesh.rotation.copyFrom(this.rotation);
  64478. if (this.rotationQuaternion) {
  64479. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  64480. }
  64481. mesh.scaling.copyFrom(this.scaling);
  64482. mesh.computeWorldMatrix(true);
  64483. return mesh;
  64484. };
  64485. return CSG;
  64486. }());
  64487. BABYLON.CSG = CSG;
  64488. })(BABYLON || (BABYLON = {}));
  64489. //# sourceMappingURL=babylon.csg.js.map
  64490. var BABYLON;
  64491. (function (BABYLON) {
  64492. var LensFlare = /** @class */ (function () {
  64493. function LensFlare(size, position, color, imgUrl, system) {
  64494. this.size = size;
  64495. this.position = position;
  64496. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  64497. this.color = color || new BABYLON.Color3(1, 1, 1);
  64498. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  64499. this._system = system;
  64500. system.lensFlares.push(this);
  64501. }
  64502. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  64503. return new LensFlare(size, position, color, imgUrl, system);
  64504. };
  64505. LensFlare.prototype.dispose = function () {
  64506. if (this.texture) {
  64507. this.texture.dispose();
  64508. }
  64509. // Remove from scene
  64510. var index = this._system.lensFlares.indexOf(this);
  64511. this._system.lensFlares.splice(index, 1);
  64512. };
  64513. ;
  64514. return LensFlare;
  64515. }());
  64516. BABYLON.LensFlare = LensFlare;
  64517. })(BABYLON || (BABYLON = {}));
  64518. //# sourceMappingURL=babylon.lensFlare.js.map
  64519. var BABYLON;
  64520. (function (BABYLON) {
  64521. var LensFlareSystem = /** @class */ (function () {
  64522. function LensFlareSystem(name, emitter, scene) {
  64523. this.name = name;
  64524. this.lensFlares = new Array();
  64525. this.borderLimit = 300;
  64526. this.viewportBorder = 0;
  64527. this.layerMask = 0x0FFFFFFF;
  64528. this._vertexBuffers = {};
  64529. this._isEnabled = true;
  64530. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64531. this._emitter = emitter;
  64532. this.id = name;
  64533. scene.lensFlareSystems.push(this);
  64534. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  64535. var engine = scene.getEngine();
  64536. // VBO
  64537. var vertices = [];
  64538. vertices.push(1, 1);
  64539. vertices.push(-1, 1);
  64540. vertices.push(-1, -1);
  64541. vertices.push(1, -1);
  64542. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64543. // Indices
  64544. var indices = [];
  64545. indices.push(0);
  64546. indices.push(1);
  64547. indices.push(2);
  64548. indices.push(0);
  64549. indices.push(2);
  64550. indices.push(3);
  64551. this._indexBuffer = engine.createIndexBuffer(indices);
  64552. // Effects
  64553. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  64554. }
  64555. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  64556. get: function () {
  64557. return this._isEnabled;
  64558. },
  64559. set: function (value) {
  64560. this._isEnabled = value;
  64561. },
  64562. enumerable: true,
  64563. configurable: true
  64564. });
  64565. LensFlareSystem.prototype.getScene = function () {
  64566. return this._scene;
  64567. };
  64568. LensFlareSystem.prototype.getEmitter = function () {
  64569. return this._emitter;
  64570. };
  64571. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  64572. this._emitter = newEmitter;
  64573. };
  64574. LensFlareSystem.prototype.getEmitterPosition = function () {
  64575. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  64576. };
  64577. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  64578. var position = this.getEmitterPosition();
  64579. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  64580. this._positionX = position.x;
  64581. this._positionY = position.y;
  64582. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  64583. if (this.viewportBorder > 0) {
  64584. globalViewport.x -= this.viewportBorder;
  64585. globalViewport.y -= this.viewportBorder;
  64586. globalViewport.width += this.viewportBorder * 2;
  64587. globalViewport.height += this.viewportBorder * 2;
  64588. position.x += this.viewportBorder;
  64589. position.y += this.viewportBorder;
  64590. this._positionX += this.viewportBorder;
  64591. this._positionY += this.viewportBorder;
  64592. }
  64593. if (position.z > 0) {
  64594. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  64595. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  64596. return true;
  64597. }
  64598. return true;
  64599. }
  64600. return false;
  64601. };
  64602. LensFlareSystem.prototype._isVisible = function () {
  64603. if (!this._isEnabled || !this._scene.activeCamera) {
  64604. return false;
  64605. }
  64606. var emitterPosition = this.getEmitterPosition();
  64607. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  64608. var distance = direction.length();
  64609. direction.normalize();
  64610. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  64611. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  64612. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  64613. };
  64614. LensFlareSystem.prototype.render = function () {
  64615. if (!this._effect.isReady() || !this._scene.activeCamera)
  64616. return false;
  64617. var engine = this._scene.getEngine();
  64618. var viewport = this._scene.activeCamera.viewport;
  64619. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  64620. // Position
  64621. if (!this.computeEffectivePosition(globalViewport)) {
  64622. return false;
  64623. }
  64624. // Visibility
  64625. if (!this._isVisible()) {
  64626. return false;
  64627. }
  64628. // Intensity
  64629. var awayX;
  64630. var awayY;
  64631. if (this._positionX < this.borderLimit + globalViewport.x) {
  64632. awayX = this.borderLimit + globalViewport.x - this._positionX;
  64633. }
  64634. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  64635. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  64636. }
  64637. else {
  64638. awayX = 0;
  64639. }
  64640. if (this._positionY < this.borderLimit + globalViewport.y) {
  64641. awayY = this.borderLimit + globalViewport.y - this._positionY;
  64642. }
  64643. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  64644. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  64645. }
  64646. else {
  64647. awayY = 0;
  64648. }
  64649. var away = (awayX > awayY) ? awayX : awayY;
  64650. away -= this.viewportBorder;
  64651. if (away > this.borderLimit) {
  64652. away = this.borderLimit;
  64653. }
  64654. var intensity = 1.0 - (away / this.borderLimit);
  64655. if (intensity < 0) {
  64656. return false;
  64657. }
  64658. if (intensity > 1.0) {
  64659. intensity = 1.0;
  64660. }
  64661. if (this.viewportBorder > 0) {
  64662. globalViewport.x += this.viewportBorder;
  64663. globalViewport.y += this.viewportBorder;
  64664. globalViewport.width -= this.viewportBorder * 2;
  64665. globalViewport.height -= this.viewportBorder * 2;
  64666. this._positionX -= this.viewportBorder;
  64667. this._positionY -= this.viewportBorder;
  64668. }
  64669. // Position
  64670. var centerX = globalViewport.x + globalViewport.width / 2;
  64671. var centerY = globalViewport.y + globalViewport.height / 2;
  64672. var distX = centerX - this._positionX;
  64673. var distY = centerY - this._positionY;
  64674. // Effects
  64675. engine.enableEffect(this._effect);
  64676. engine.setState(false);
  64677. engine.setDepthBuffer(false);
  64678. // VBOs
  64679. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64680. // Flares
  64681. for (var index = 0; index < this.lensFlares.length; index++) {
  64682. var flare = this.lensFlares[index];
  64683. engine.setAlphaMode(flare.alphaMode);
  64684. var x = centerX - (distX * flare.position);
  64685. var y = centerY - (distY * flare.position);
  64686. var cw = flare.size;
  64687. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  64688. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  64689. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  64690. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  64691. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  64692. // Texture
  64693. this._effect.setTexture("textureSampler", flare.texture);
  64694. // Color
  64695. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  64696. // Draw order
  64697. engine.draw(true, 0, 6);
  64698. }
  64699. engine.setDepthBuffer(true);
  64700. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64701. return true;
  64702. };
  64703. LensFlareSystem.prototype.dispose = function () {
  64704. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64705. if (vertexBuffer) {
  64706. vertexBuffer.dispose();
  64707. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64708. }
  64709. if (this._indexBuffer) {
  64710. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64711. this._indexBuffer = null;
  64712. }
  64713. while (this.lensFlares.length) {
  64714. this.lensFlares[0].dispose();
  64715. }
  64716. // Remove from scene
  64717. var index = this._scene.lensFlareSystems.indexOf(this);
  64718. this._scene.lensFlareSystems.splice(index, 1);
  64719. };
  64720. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  64721. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  64722. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  64723. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  64724. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  64725. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  64726. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  64727. var parsedFlare = parsedLensFlareSystem.flares[index];
  64728. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  64729. }
  64730. return lensFlareSystem;
  64731. };
  64732. LensFlareSystem.prototype.serialize = function () {
  64733. var serializationObject = {};
  64734. serializationObject.id = this.id;
  64735. serializationObject.name = this.name;
  64736. serializationObject.emitterId = this.getEmitter().id;
  64737. serializationObject.borderLimit = this.borderLimit;
  64738. serializationObject.flares = [];
  64739. for (var index = 0; index < this.lensFlares.length; index++) {
  64740. var flare = this.lensFlares[index];
  64741. serializationObject.flares.push({
  64742. size: flare.size,
  64743. position: flare.position,
  64744. color: flare.color.asArray(),
  64745. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  64746. });
  64747. }
  64748. return serializationObject;
  64749. };
  64750. return LensFlareSystem;
  64751. }());
  64752. BABYLON.LensFlareSystem = LensFlareSystem;
  64753. })(BABYLON || (BABYLON = {}));
  64754. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  64755. var BABYLON;
  64756. (function (BABYLON) {
  64757. /**
  64758. * This is a holder class for the physics joint created by the physics plugin.
  64759. * It holds a set of functions to control the underlying joint.
  64760. */
  64761. var PhysicsJoint = /** @class */ (function () {
  64762. function PhysicsJoint(type, jointData) {
  64763. this.type = type;
  64764. this.jointData = jointData;
  64765. jointData.nativeParams = jointData.nativeParams || {};
  64766. }
  64767. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  64768. get: function () {
  64769. return this._physicsJoint;
  64770. },
  64771. set: function (newJoint) {
  64772. if (this._physicsJoint) {
  64773. //remove from the wolrd
  64774. }
  64775. this._physicsJoint = newJoint;
  64776. },
  64777. enumerable: true,
  64778. configurable: true
  64779. });
  64780. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  64781. set: function (physicsPlugin) {
  64782. this._physicsPlugin = physicsPlugin;
  64783. },
  64784. enumerable: true,
  64785. configurable: true
  64786. });
  64787. /**
  64788. * Execute a function that is physics-plugin specific.
  64789. * @param {Function} func the function that will be executed.
  64790. * It accepts two parameters: the physics world and the physics joint.
  64791. */
  64792. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  64793. func(this._physicsPlugin.world, this._physicsJoint);
  64794. };
  64795. //TODO check if the native joints are the same
  64796. //Joint Types
  64797. PhysicsJoint.DistanceJoint = 0;
  64798. PhysicsJoint.HingeJoint = 1;
  64799. PhysicsJoint.BallAndSocketJoint = 2;
  64800. PhysicsJoint.WheelJoint = 3;
  64801. PhysicsJoint.SliderJoint = 4;
  64802. //OIMO
  64803. PhysicsJoint.PrismaticJoint = 5;
  64804. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  64805. PhysicsJoint.UniversalJoint = 6;
  64806. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  64807. //Cannon
  64808. //Similar to a Ball-Joint. Different in params
  64809. PhysicsJoint.PointToPointJoint = 8;
  64810. //Cannon only at the moment
  64811. PhysicsJoint.SpringJoint = 9;
  64812. PhysicsJoint.LockJoint = 10;
  64813. return PhysicsJoint;
  64814. }());
  64815. BABYLON.PhysicsJoint = PhysicsJoint;
  64816. /**
  64817. * A class representing a physics distance joint.
  64818. */
  64819. var DistanceJoint = /** @class */ (function (_super) {
  64820. __extends(DistanceJoint, _super);
  64821. function DistanceJoint(jointData) {
  64822. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  64823. }
  64824. /**
  64825. * Update the predefined distance.
  64826. */
  64827. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  64828. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  64829. };
  64830. return DistanceJoint;
  64831. }(PhysicsJoint));
  64832. BABYLON.DistanceJoint = DistanceJoint;
  64833. var MotorEnabledJoint = /** @class */ (function (_super) {
  64834. __extends(MotorEnabledJoint, _super);
  64835. function MotorEnabledJoint(type, jointData) {
  64836. return _super.call(this, type, jointData) || this;
  64837. }
  64838. /**
  64839. * Set the motor values.
  64840. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64841. * @param {number} force the force to apply
  64842. * @param {number} maxForce max force for this motor.
  64843. */
  64844. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  64845. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  64846. };
  64847. /**
  64848. * Set the motor's limits.
  64849. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64850. */
  64851. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  64852. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  64853. };
  64854. return MotorEnabledJoint;
  64855. }(PhysicsJoint));
  64856. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  64857. /**
  64858. * This class represents a single hinge physics joint
  64859. */
  64860. var HingeJoint = /** @class */ (function (_super) {
  64861. __extends(HingeJoint, _super);
  64862. function HingeJoint(jointData) {
  64863. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  64864. }
  64865. /**
  64866. * Set the motor values.
  64867. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64868. * @param {number} force the force to apply
  64869. * @param {number} maxForce max force for this motor.
  64870. */
  64871. HingeJoint.prototype.setMotor = function (force, maxForce) {
  64872. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  64873. };
  64874. /**
  64875. * Set the motor's limits.
  64876. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64877. */
  64878. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  64879. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  64880. };
  64881. return HingeJoint;
  64882. }(MotorEnabledJoint));
  64883. BABYLON.HingeJoint = HingeJoint;
  64884. /**
  64885. * This class represents a dual hinge physics joint (same as wheel joint)
  64886. */
  64887. var Hinge2Joint = /** @class */ (function (_super) {
  64888. __extends(Hinge2Joint, _super);
  64889. function Hinge2Joint(jointData) {
  64890. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  64891. }
  64892. /**
  64893. * Set the motor values.
  64894. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64895. * @param {number} force the force to apply
  64896. * @param {number} maxForce max force for this motor.
  64897. * @param {motorIndex} the motor's index, 0 or 1.
  64898. */
  64899. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  64900. if (motorIndex === void 0) { motorIndex = 0; }
  64901. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  64902. };
  64903. /**
  64904. * Set the motor limits.
  64905. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64906. * @param {number} upperLimit the upper limit
  64907. * @param {number} lowerLimit lower limit
  64908. * @param {motorIndex} the motor's index, 0 or 1.
  64909. */
  64910. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  64911. if (motorIndex === void 0) { motorIndex = 0; }
  64912. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  64913. };
  64914. return Hinge2Joint;
  64915. }(MotorEnabledJoint));
  64916. BABYLON.Hinge2Joint = Hinge2Joint;
  64917. })(BABYLON || (BABYLON = {}));
  64918. //# sourceMappingURL=babylon.physicsJoint.js.map
  64919. var BABYLON;
  64920. (function (BABYLON) {
  64921. var PhysicsImpostor = /** @class */ (function () {
  64922. function PhysicsImpostor(object, type, _options, _scene) {
  64923. if (_options === void 0) { _options = { mass: 0 }; }
  64924. var _this = this;
  64925. this.object = object;
  64926. this.type = type;
  64927. this._options = _options;
  64928. this._scene = _scene;
  64929. this._bodyUpdateRequired = false;
  64930. this._onBeforePhysicsStepCallbacks = new Array();
  64931. this._onAfterPhysicsStepCallbacks = new Array();
  64932. this._onPhysicsCollideCallbacks = [];
  64933. this._deltaPosition = BABYLON.Vector3.Zero();
  64934. this._isDisposed = false;
  64935. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  64936. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  64937. /**
  64938. * this function is executed by the physics engine.
  64939. */
  64940. this.beforeStep = function () {
  64941. if (!_this._physicsEngine) {
  64942. return;
  64943. }
  64944. if (_this._options.ignoreParent && _this.object.parent) {
  64945. _this._tmpPositionWithDelta.copyFrom(_this.object.getAbsolutePosition());
  64946. //this.object.getAbsolutePosition().subtractToRef(this._deltaPosition, this._tmpPositionWithDelta);
  64947. }
  64948. else {
  64949. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  64950. }
  64951. //conjugate deltaRotation
  64952. if (_this.object.rotationQuaternion) {
  64953. if (_this._deltaRotationConjugated) {
  64954. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  64955. }
  64956. else {
  64957. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  64958. }
  64959. }
  64960. // Only if not disabled
  64961. if (!_this._options.disableBidirectionalTransformation) {
  64962. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  64963. }
  64964. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  64965. func(_this);
  64966. });
  64967. };
  64968. /**
  64969. * this function is executed by the physics engine.
  64970. */
  64971. this.afterStep = function () {
  64972. if (!_this._physicsEngine) {
  64973. return;
  64974. }
  64975. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  64976. func(_this);
  64977. });
  64978. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  64979. if (_this._options.ignoreParent && _this.object.parent) {
  64980. _this.object.position.subtractInPlace(_this.object.parent.getAbsolutePosition());
  64981. }
  64982. else {
  64983. _this.object.position.addInPlace(_this._deltaPosition);
  64984. }
  64985. if (_this._deltaRotation && _this.object.rotationQuaternion) {
  64986. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  64987. }
  64988. };
  64989. /**
  64990. * Legacy collision detection event support
  64991. */
  64992. this.onCollideEvent = null;
  64993. //event and body object due to cannon's event-based architecture.
  64994. this.onCollide = function (e) {
  64995. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  64996. return;
  64997. }
  64998. if (!_this._physicsEngine) {
  64999. return;
  65000. }
  65001. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  65002. if (otherImpostor) {
  65003. // Legacy collision detection event support
  65004. if (_this.onCollideEvent) {
  65005. _this.onCollideEvent(_this, otherImpostor);
  65006. }
  65007. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65008. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65009. }).forEach(function (obj) {
  65010. obj.callback(_this, otherImpostor);
  65011. });
  65012. }
  65013. };
  65014. //sanity check!
  65015. if (!this.object) {
  65016. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65017. return;
  65018. }
  65019. //legacy support for old syntax.
  65020. if (!this._scene && object.getScene) {
  65021. this._scene = object.getScene();
  65022. }
  65023. if (!this._scene) {
  65024. return;
  65025. }
  65026. this._physicsEngine = this._scene.getPhysicsEngine();
  65027. if (!this._physicsEngine) {
  65028. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65029. }
  65030. else {
  65031. //set the object's quaternion, if not set
  65032. if (!this.object.rotationQuaternion) {
  65033. if (this.object.rotation) {
  65034. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65035. }
  65036. else {
  65037. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65038. }
  65039. }
  65040. //default options params
  65041. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65042. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65043. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65044. this._joints = [];
  65045. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65046. if (!this.object.parent || this._options.ignoreParent) {
  65047. this._init();
  65048. }
  65049. else if (this.object.parent.physicsImpostor) {
  65050. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65051. }
  65052. }
  65053. }
  65054. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65055. get: function () {
  65056. return this._isDisposed;
  65057. },
  65058. enumerable: true,
  65059. configurable: true
  65060. });
  65061. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65062. get: function () {
  65063. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65064. },
  65065. set: function (value) {
  65066. this.setMass(value);
  65067. },
  65068. enumerable: true,
  65069. configurable: true
  65070. });
  65071. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65072. get: function () {
  65073. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65074. },
  65075. set: function (value) {
  65076. if (!this._physicsEngine) {
  65077. return;
  65078. }
  65079. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65080. },
  65081. enumerable: true,
  65082. configurable: true
  65083. });
  65084. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  65085. get: function () {
  65086. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  65087. },
  65088. set: function (value) {
  65089. if (!this._physicsEngine) {
  65090. return;
  65091. }
  65092. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  65093. },
  65094. enumerable: true,
  65095. configurable: true
  65096. });
  65097. /**
  65098. * This function will completly initialize this impostor.
  65099. * It will create a new body - but only if this mesh has no parent.
  65100. * If it has, this impostor will not be used other than to define the impostor
  65101. * of the child mesh.
  65102. */
  65103. PhysicsImpostor.prototype._init = function () {
  65104. if (!this._physicsEngine) {
  65105. return;
  65106. }
  65107. this._physicsEngine.removeImpostor(this);
  65108. this.physicsBody = null;
  65109. this._parent = this._parent || this._getPhysicsParent();
  65110. if (!this.parent || this._options.ignoreParent) {
  65111. this._physicsEngine.addImpostor(this);
  65112. }
  65113. };
  65114. PhysicsImpostor.prototype._getPhysicsParent = function () {
  65115. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  65116. var parentMesh = this.object.parent;
  65117. return parentMesh.physicsImpostor;
  65118. }
  65119. return null;
  65120. };
  65121. /**
  65122. * Should a new body be generated.
  65123. */
  65124. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  65125. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  65126. };
  65127. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  65128. this.forceUpdate();
  65129. };
  65130. /**
  65131. * Force a regeneration of this or the parent's impostor's body.
  65132. * Use under cautious - This will remove all joints already implemented.
  65133. */
  65134. PhysicsImpostor.prototype.forceUpdate = function () {
  65135. this._init();
  65136. if (this.parent && !this._options.ignoreParent) {
  65137. this.parent.forceUpdate();
  65138. }
  65139. };
  65140. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  65141. /*public get mesh(): AbstractMesh {
  65142. return this._mesh;
  65143. }*/
  65144. /**
  65145. * Gets the body that holds this impostor. Either its own, or its parent.
  65146. */
  65147. get: function () {
  65148. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  65149. },
  65150. /**
  65151. * Set the physics body. Used mainly by the physics engine/plugin
  65152. */
  65153. set: function (physicsBody) {
  65154. if (this._physicsBody && this._physicsEngine) {
  65155. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  65156. }
  65157. this._physicsBody = physicsBody;
  65158. this.resetUpdateFlags();
  65159. },
  65160. enumerable: true,
  65161. configurable: true
  65162. });
  65163. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  65164. get: function () {
  65165. return !this._options.ignoreParent && this._parent ? this._parent : null;
  65166. },
  65167. set: function (value) {
  65168. this._parent = value;
  65169. },
  65170. enumerable: true,
  65171. configurable: true
  65172. });
  65173. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  65174. this._bodyUpdateRequired = false;
  65175. };
  65176. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  65177. if (this.object.getBoundingInfo) {
  65178. var q = this.object.rotationQuaternion;
  65179. //reset rotation
  65180. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  65181. //calculate the world matrix with no rotation
  65182. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65183. var boundingInfo = this.object.getBoundingInfo();
  65184. var size = void 0;
  65185. if (boundingInfo) {
  65186. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  65187. }
  65188. else {
  65189. size = BABYLON.Vector3.Zero();
  65190. }
  65191. //bring back the rotation
  65192. this.object.rotationQuaternion = q;
  65193. //calculate the world matrix with the new rotation
  65194. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65195. return size;
  65196. }
  65197. else {
  65198. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  65199. }
  65200. };
  65201. PhysicsImpostor.prototype.getObjectCenter = function () {
  65202. if (this.object.getBoundingInfo) {
  65203. var boundingInfo = this.object.getBoundingInfo();
  65204. if (!boundingInfo) {
  65205. return this.object.position;
  65206. }
  65207. return boundingInfo.boundingBox.centerWorld;
  65208. }
  65209. else {
  65210. return this.object.position;
  65211. }
  65212. };
  65213. /**
  65214. * Get a specific parametes from the options parameter.
  65215. */
  65216. PhysicsImpostor.prototype.getParam = function (paramName) {
  65217. return this._options[paramName];
  65218. };
  65219. /**
  65220. * Sets a specific parameter in the options given to the physics plugin
  65221. */
  65222. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  65223. this._options[paramName] = value;
  65224. this._bodyUpdateRequired = true;
  65225. };
  65226. /**
  65227. * Specifically change the body's mass option. Won't recreate the physics body object
  65228. */
  65229. PhysicsImpostor.prototype.setMass = function (mass) {
  65230. if (this.getParam("mass") !== mass) {
  65231. this.setParam("mass", mass);
  65232. }
  65233. if (this._physicsEngine) {
  65234. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  65235. }
  65236. };
  65237. PhysicsImpostor.prototype.getLinearVelocity = function () {
  65238. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  65239. };
  65240. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  65241. if (this._physicsEngine) {
  65242. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  65243. }
  65244. };
  65245. PhysicsImpostor.prototype.getAngularVelocity = function () {
  65246. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  65247. };
  65248. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  65249. if (this._physicsEngine) {
  65250. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  65251. }
  65252. };
  65253. /**
  65254. * Execute a function with the physics plugin native code.
  65255. * Provide a function the will have two variables - the world object and the physics body object.
  65256. */
  65257. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  65258. if (this._physicsEngine) {
  65259. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  65260. }
  65261. };
  65262. /**
  65263. * Register a function that will be executed before the physics world is stepping forward.
  65264. */
  65265. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  65266. this._onBeforePhysicsStepCallbacks.push(func);
  65267. };
  65268. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  65269. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  65270. if (index > -1) {
  65271. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  65272. }
  65273. else {
  65274. BABYLON.Tools.Warn("Function to remove was not found");
  65275. }
  65276. };
  65277. /**
  65278. * Register a function that will be executed after the physics step
  65279. */
  65280. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  65281. this._onAfterPhysicsStepCallbacks.push(func);
  65282. };
  65283. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  65284. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  65285. if (index > -1) {
  65286. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  65287. }
  65288. else {
  65289. BABYLON.Tools.Warn("Function to remove was not found");
  65290. }
  65291. };
  65292. /**
  65293. * register a function that will be executed when this impostor collides against a different body.
  65294. */
  65295. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  65296. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65297. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  65298. };
  65299. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  65300. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65301. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  65302. if (index > -1) {
  65303. this._onPhysicsCollideCallbacks.splice(index, 1);
  65304. }
  65305. else {
  65306. BABYLON.Tools.Warn("Function to remove was not found");
  65307. }
  65308. };
  65309. /**
  65310. * Apply a force
  65311. */
  65312. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  65313. if (this._physicsEngine) {
  65314. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  65315. }
  65316. return this;
  65317. };
  65318. /**
  65319. * Apply an impulse
  65320. */
  65321. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  65322. if (this._physicsEngine) {
  65323. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  65324. }
  65325. return this;
  65326. };
  65327. /**
  65328. * A help function to create a joint.
  65329. */
  65330. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  65331. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  65332. this.addJoint(otherImpostor, joint);
  65333. return this;
  65334. };
  65335. /**
  65336. * Add a joint to this impostor with a different impostor.
  65337. */
  65338. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  65339. this._joints.push({
  65340. otherImpostor: otherImpostor,
  65341. joint: joint
  65342. });
  65343. if (this._physicsEngine) {
  65344. this._physicsEngine.addJoint(this, otherImpostor, joint);
  65345. }
  65346. return this;
  65347. };
  65348. /**
  65349. * Will keep this body still, in a sleep mode.
  65350. */
  65351. PhysicsImpostor.prototype.sleep = function () {
  65352. if (this._physicsEngine) {
  65353. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  65354. }
  65355. return this;
  65356. };
  65357. /**
  65358. * Wake the body up.
  65359. */
  65360. PhysicsImpostor.prototype.wakeUp = function () {
  65361. if (this._physicsEngine) {
  65362. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  65363. }
  65364. return this;
  65365. };
  65366. PhysicsImpostor.prototype.clone = function (newObject) {
  65367. if (!newObject)
  65368. return null;
  65369. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  65370. };
  65371. PhysicsImpostor.prototype.dispose = function () {
  65372. var _this = this;
  65373. //no dispose if no physics engine is available.
  65374. if (!this._physicsEngine) {
  65375. return;
  65376. }
  65377. this._joints.forEach(function (j) {
  65378. if (_this._physicsEngine) {
  65379. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  65380. }
  65381. });
  65382. //dispose the physics body
  65383. this._physicsEngine.removeImpostor(this);
  65384. if (this.parent) {
  65385. this.parent.forceUpdate();
  65386. }
  65387. else {
  65388. /*this._object.getChildMeshes().forEach(function(mesh) {
  65389. if (mesh.physicsImpostor) {
  65390. if (disposeChildren) {
  65391. mesh.physicsImpostor.dispose();
  65392. mesh.physicsImpostor = null;
  65393. }
  65394. }
  65395. })*/
  65396. }
  65397. this._isDisposed = true;
  65398. };
  65399. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  65400. this._deltaPosition.copyFrom(position);
  65401. };
  65402. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  65403. if (!this._deltaRotation) {
  65404. this._deltaRotation = new BABYLON.Quaternion();
  65405. }
  65406. this._deltaRotation.copyFrom(rotation);
  65407. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  65408. };
  65409. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  65410. if (this._physicsEngine) {
  65411. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  65412. }
  65413. return this;
  65414. };
  65415. PhysicsImpostor.prototype.getRadius = function () {
  65416. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  65417. };
  65418. /**
  65419. * Sync a bone with this impostor
  65420. * @param bone The bone to sync to the impostor.
  65421. * @param boneMesh The mesh that the bone is influencing.
  65422. * @param jointPivot The pivot of the joint / bone in local space.
  65423. * @param distToJoint Optional distance from the impostor to the joint.
  65424. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65425. */
  65426. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  65427. var tempVec = PhysicsImpostor._tmpVecs[0];
  65428. var mesh = this.object;
  65429. if (mesh.rotationQuaternion) {
  65430. if (adjustRotation) {
  65431. var tempQuat = PhysicsImpostor._tmpQuat;
  65432. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  65433. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  65434. }
  65435. else {
  65436. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  65437. }
  65438. }
  65439. tempVec.x = 0;
  65440. tempVec.y = 0;
  65441. tempVec.z = 0;
  65442. if (jointPivot) {
  65443. tempVec.x = jointPivot.x;
  65444. tempVec.y = jointPivot.y;
  65445. tempVec.z = jointPivot.z;
  65446. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  65447. if (distToJoint === undefined || distToJoint === null) {
  65448. distToJoint = jointPivot.length();
  65449. }
  65450. tempVec.x *= distToJoint;
  65451. tempVec.y *= distToJoint;
  65452. tempVec.z *= distToJoint;
  65453. }
  65454. if (bone.getParent()) {
  65455. tempVec.addInPlace(mesh.getAbsolutePosition());
  65456. bone.setAbsolutePosition(tempVec, boneMesh);
  65457. }
  65458. else {
  65459. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  65460. boneMesh.position.x -= tempVec.x;
  65461. boneMesh.position.y -= tempVec.y;
  65462. boneMesh.position.z -= tempVec.z;
  65463. }
  65464. };
  65465. /**
  65466. * Sync impostor to a bone
  65467. * @param bone The bone that the impostor will be synced to.
  65468. * @param boneMesh The mesh that the bone is influencing.
  65469. * @param jointPivot The pivot of the joint / bone in local space.
  65470. * @param distToJoint Optional distance from the impostor to the joint.
  65471. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65472. * @param boneAxis Optional vector3 axis the bone is aligned with
  65473. */
  65474. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  65475. var mesh = this.object;
  65476. if (mesh.rotationQuaternion) {
  65477. if (adjustRotation) {
  65478. var tempQuat = PhysicsImpostor._tmpQuat;
  65479. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  65480. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  65481. }
  65482. else {
  65483. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  65484. }
  65485. }
  65486. var pos = PhysicsImpostor._tmpVecs[0];
  65487. var boneDir = PhysicsImpostor._tmpVecs[1];
  65488. if (!boneAxis) {
  65489. boneAxis = PhysicsImpostor._tmpVecs[2];
  65490. boneAxis.x = 0;
  65491. boneAxis.y = 1;
  65492. boneAxis.z = 0;
  65493. }
  65494. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  65495. bone.getAbsolutePositionToRef(boneMesh, pos);
  65496. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  65497. distToJoint = jointPivot.length();
  65498. }
  65499. if (distToJoint !== undefined && distToJoint !== null) {
  65500. pos.x += boneDir.x * distToJoint;
  65501. pos.y += boneDir.y * distToJoint;
  65502. pos.z += boneDir.z * distToJoint;
  65503. }
  65504. mesh.setAbsolutePosition(pos);
  65505. };
  65506. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  65507. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  65508. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65509. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  65510. //Impostor types
  65511. PhysicsImpostor.NoImpostor = 0;
  65512. PhysicsImpostor.SphereImpostor = 1;
  65513. PhysicsImpostor.BoxImpostor = 2;
  65514. PhysicsImpostor.PlaneImpostor = 3;
  65515. PhysicsImpostor.MeshImpostor = 4;
  65516. PhysicsImpostor.CylinderImpostor = 7;
  65517. PhysicsImpostor.ParticleImpostor = 8;
  65518. PhysicsImpostor.HeightmapImpostor = 9;
  65519. return PhysicsImpostor;
  65520. }());
  65521. BABYLON.PhysicsImpostor = PhysicsImpostor;
  65522. })(BABYLON || (BABYLON = {}));
  65523. //# sourceMappingURL=babylon.physicsImpostor.js.map
  65524. var BABYLON;
  65525. (function (BABYLON) {
  65526. var PhysicsEngine = /** @class */ (function () {
  65527. function PhysicsEngine(gravity, _physicsPlugin) {
  65528. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  65529. this._physicsPlugin = _physicsPlugin;
  65530. //new methods and parameters
  65531. this._impostors = [];
  65532. this._joints = [];
  65533. if (!this._physicsPlugin.isSupported()) {
  65534. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  65535. + "Please make sure it is included.");
  65536. }
  65537. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  65538. this.setGravity(gravity);
  65539. this.setTimeStep();
  65540. }
  65541. PhysicsEngine.prototype.setGravity = function (gravity) {
  65542. this.gravity = gravity;
  65543. this._physicsPlugin.setGravity(this.gravity);
  65544. };
  65545. /**
  65546. * Set the time step of the physics engine.
  65547. * default is 1/60.
  65548. * To slow it down, enter 1/600 for example.
  65549. * To speed it up, 1/30
  65550. * @param {number} newTimeStep the new timestep to apply to this world.
  65551. */
  65552. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  65553. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  65554. this._physicsPlugin.setTimeStep(newTimeStep);
  65555. };
  65556. /**
  65557. * Get the time step of the physics engine.
  65558. */
  65559. PhysicsEngine.prototype.getTimeStep = function () {
  65560. return this._physicsPlugin.getTimeStep();
  65561. };
  65562. PhysicsEngine.prototype.dispose = function () {
  65563. this._impostors.forEach(function (impostor) {
  65564. impostor.dispose();
  65565. });
  65566. this._physicsPlugin.dispose();
  65567. };
  65568. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  65569. return this._physicsPlugin.name;
  65570. };
  65571. /**
  65572. * Adding a new impostor for the impostor tracking.
  65573. * This will be done by the impostor itself.
  65574. * @param {PhysicsImpostor} impostor the impostor to add
  65575. */
  65576. PhysicsEngine.prototype.addImpostor = function (impostor) {
  65577. impostor.uniqueId = this._impostors.push(impostor);
  65578. //if no parent, generate the body
  65579. if (!impostor.parent) {
  65580. this._physicsPlugin.generatePhysicsBody(impostor);
  65581. }
  65582. };
  65583. /**
  65584. * Remove an impostor from the engine.
  65585. * This impostor and its mesh will not longer be updated by the physics engine.
  65586. * @param {PhysicsImpostor} impostor the impostor to remove
  65587. */
  65588. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  65589. var index = this._impostors.indexOf(impostor);
  65590. if (index > -1) {
  65591. var removed = this._impostors.splice(index, 1);
  65592. //Is it needed?
  65593. if (removed.length) {
  65594. //this will also remove it from the world.
  65595. removed[0].physicsBody = null;
  65596. }
  65597. }
  65598. };
  65599. /**
  65600. * Add a joint to the physics engine
  65601. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  65602. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  65603. * @param {PhysicsJoint} the joint that will connect both impostors.
  65604. */
  65605. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  65606. var impostorJoint = {
  65607. mainImpostor: mainImpostor,
  65608. connectedImpostor: connectedImpostor,
  65609. joint: joint
  65610. };
  65611. joint.physicsPlugin = this._physicsPlugin;
  65612. this._joints.push(impostorJoint);
  65613. this._physicsPlugin.generateJoint(impostorJoint);
  65614. };
  65615. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  65616. var matchingJoints = this._joints.filter(function (impostorJoint) {
  65617. return (impostorJoint.connectedImpostor === connectedImpostor
  65618. && impostorJoint.joint === joint
  65619. && impostorJoint.mainImpostor === mainImpostor);
  65620. });
  65621. if (matchingJoints.length) {
  65622. this._physicsPlugin.removeJoint(matchingJoints[0]);
  65623. //TODO remove it from the list as well
  65624. }
  65625. };
  65626. /**
  65627. * Called by the scene. no need to call it.
  65628. */
  65629. PhysicsEngine.prototype._step = function (delta) {
  65630. var _this = this;
  65631. //check if any mesh has no body / requires an update
  65632. this._impostors.forEach(function (impostor) {
  65633. if (impostor.isBodyInitRequired()) {
  65634. _this._physicsPlugin.generatePhysicsBody(impostor);
  65635. }
  65636. });
  65637. if (delta > 0.1) {
  65638. delta = 0.1;
  65639. }
  65640. else if (delta <= 0) {
  65641. delta = 1.0 / 60.0;
  65642. }
  65643. this._physicsPlugin.executeStep(delta, this._impostors);
  65644. };
  65645. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  65646. return this._physicsPlugin;
  65647. };
  65648. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  65649. for (var i = 0; i < this._impostors.length; ++i) {
  65650. if (this._impostors[i].object === object) {
  65651. return this._impostors[i];
  65652. }
  65653. }
  65654. return null;
  65655. };
  65656. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  65657. for (var i = 0; i < this._impostors.length; ++i) {
  65658. if (this._impostors[i].physicsBody === body) {
  65659. return this._impostors[i];
  65660. }
  65661. }
  65662. return null;
  65663. };
  65664. // Statics
  65665. PhysicsEngine.Epsilon = 0.001;
  65666. return PhysicsEngine;
  65667. }());
  65668. BABYLON.PhysicsEngine = PhysicsEngine;
  65669. })(BABYLON || (BABYLON = {}));
  65670. //# sourceMappingURL=babylon.physicsEngine.js.map
  65671. var BABYLON;
  65672. (function (BABYLON) {
  65673. var CannonJSPlugin = /** @class */ (function () {
  65674. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  65675. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  65676. if (iterations === void 0) { iterations = 10; }
  65677. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  65678. this.name = "CannonJSPlugin";
  65679. this._physicsMaterials = new Array();
  65680. this._fixedTimeStep = 1 / 60;
  65681. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  65682. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  65683. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  65684. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  65685. this._tmpPosition = BABYLON.Vector3.Zero();
  65686. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  65687. this._tmpUnityRotation = new BABYLON.Quaternion();
  65688. if (!this.isSupported()) {
  65689. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  65690. return;
  65691. }
  65692. this.world = new this.BJSCANNON.World();
  65693. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  65694. this.world.solver.iterations = iterations;
  65695. }
  65696. CannonJSPlugin.prototype.setGravity = function (gravity) {
  65697. this.world.gravity.copy(gravity);
  65698. };
  65699. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  65700. this._fixedTimeStep = timeStep;
  65701. };
  65702. CannonJSPlugin.prototype.getTimeStep = function () {
  65703. return this._fixedTimeStep;
  65704. };
  65705. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  65706. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  65707. };
  65708. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  65709. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65710. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65711. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  65712. };
  65713. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  65714. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65715. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65716. impostor.physicsBody.applyForce(impulse, worldPoint);
  65717. };
  65718. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  65719. //parent-child relationship. Does this impostor has a parent impostor?
  65720. if (impostor.parent) {
  65721. if (impostor.physicsBody) {
  65722. this.removePhysicsBody(impostor);
  65723. //TODO is that needed?
  65724. impostor.forceUpdate();
  65725. }
  65726. return;
  65727. }
  65728. //should a new body be created for this impostor?
  65729. if (impostor.isBodyInitRequired()) {
  65730. var shape = this._createShape(impostor);
  65731. //unregister events, if body is being changed
  65732. var oldBody = impostor.physicsBody;
  65733. if (oldBody) {
  65734. this.removePhysicsBody(impostor);
  65735. }
  65736. //create the body and material
  65737. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  65738. var bodyCreationObject = {
  65739. mass: impostor.getParam("mass"),
  65740. material: material
  65741. };
  65742. // A simple extend, in case native options were used.
  65743. var nativeOptions = impostor.getParam("nativeOptions");
  65744. for (var key in nativeOptions) {
  65745. if (nativeOptions.hasOwnProperty(key)) {
  65746. bodyCreationObject[key] = nativeOptions[key];
  65747. }
  65748. }
  65749. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  65750. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  65751. this.world.addEventListener("preStep", impostor.beforeStep);
  65752. this.world.addEventListener("postStep", impostor.afterStep);
  65753. impostor.physicsBody.addShape(shape);
  65754. this.world.add(impostor.physicsBody);
  65755. //try to keep the body moving in the right direction by taking old properties.
  65756. //Should be tested!
  65757. if (oldBody) {
  65758. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  65759. impostor.physicsBody[param].copy(oldBody[param]);
  65760. });
  65761. }
  65762. this._processChildMeshes(impostor);
  65763. }
  65764. //now update the body's transformation
  65765. this._updatePhysicsBodyTransformation(impostor);
  65766. };
  65767. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  65768. var _this = this;
  65769. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  65770. var currentRotation = mainImpostor.object.rotationQuaternion;
  65771. if (meshChildren.length) {
  65772. var processMesh = function (localPosition, mesh) {
  65773. if (!currentRotation || !mesh.rotationQuaternion) {
  65774. return;
  65775. }
  65776. var childImpostor = mesh.getPhysicsImpostor();
  65777. if (childImpostor) {
  65778. var parent = childImpostor.parent;
  65779. if (parent !== mainImpostor) {
  65780. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  65781. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  65782. if (childImpostor.physicsBody) {
  65783. _this.removePhysicsBody(childImpostor);
  65784. childImpostor.physicsBody = null;
  65785. }
  65786. childImpostor.parent = mainImpostor;
  65787. childImpostor.resetUpdateFlags();
  65788. 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));
  65789. //Add the mass of the children.
  65790. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  65791. }
  65792. }
  65793. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  65794. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  65795. };
  65796. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  65797. }
  65798. };
  65799. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  65800. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  65801. this.world.removeEventListener("preStep", impostor.beforeStep);
  65802. this.world.removeEventListener("postStep", impostor.afterStep);
  65803. this.world.remove(impostor.physicsBody);
  65804. };
  65805. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  65806. var mainBody = impostorJoint.mainImpostor.physicsBody;
  65807. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  65808. if (!mainBody || !connectedBody) {
  65809. return;
  65810. }
  65811. var constraint;
  65812. var jointData = impostorJoint.joint.jointData;
  65813. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  65814. var constraintData = {
  65815. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  65816. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  65817. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  65818. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  65819. maxForce: jointData.nativeParams.maxForce,
  65820. collideConnected: !!jointData.collision
  65821. };
  65822. switch (impostorJoint.joint.type) {
  65823. case BABYLON.PhysicsJoint.HingeJoint:
  65824. case BABYLON.PhysicsJoint.Hinge2Joint:
  65825. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  65826. break;
  65827. case BABYLON.PhysicsJoint.DistanceJoint:
  65828. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  65829. break;
  65830. case BABYLON.PhysicsJoint.SpringJoint:
  65831. var springData = jointData;
  65832. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  65833. restLength: springData.length,
  65834. stiffness: springData.stiffness,
  65835. damping: springData.damping,
  65836. localAnchorA: constraintData.pivotA,
  65837. localAnchorB: constraintData.pivotB
  65838. });
  65839. break;
  65840. case BABYLON.PhysicsJoint.LockJoint:
  65841. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  65842. break;
  65843. case BABYLON.PhysicsJoint.PointToPointJoint:
  65844. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  65845. default:
  65846. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  65847. break;
  65848. }
  65849. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  65850. constraint.collideConnected = !!jointData.collision;
  65851. impostorJoint.joint.physicsJoint = constraint;
  65852. //don't add spring as constraint, as it is not one.
  65853. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  65854. this.world.addConstraint(constraint);
  65855. }
  65856. else {
  65857. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  65858. constraint.applyForce();
  65859. });
  65860. }
  65861. };
  65862. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  65863. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  65864. };
  65865. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  65866. var index;
  65867. var mat;
  65868. for (index = 0; index < this._physicsMaterials.length; index++) {
  65869. mat = this._physicsMaterials[index];
  65870. if (mat.friction === friction && mat.restitution === restitution) {
  65871. return mat;
  65872. }
  65873. }
  65874. var currentMat = new this.BJSCANNON.Material(name);
  65875. currentMat.friction = friction;
  65876. currentMat.restitution = restitution;
  65877. this._physicsMaterials.push(currentMat);
  65878. return currentMat;
  65879. };
  65880. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  65881. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  65882. };
  65883. CannonJSPlugin.prototype._createShape = function (impostor) {
  65884. var object = impostor.object;
  65885. var returnValue;
  65886. var extendSize = impostor.getObjectExtendSize();
  65887. switch (impostor.type) {
  65888. case BABYLON.PhysicsImpostor.SphereImpostor:
  65889. var radiusX = extendSize.x;
  65890. var radiusY = extendSize.y;
  65891. var radiusZ = extendSize.z;
  65892. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  65893. break;
  65894. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  65895. case BABYLON.PhysicsImpostor.CylinderImpostor:
  65896. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  65897. break;
  65898. case BABYLON.PhysicsImpostor.BoxImpostor:
  65899. var box = extendSize.scale(0.5);
  65900. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  65901. break;
  65902. case BABYLON.PhysicsImpostor.PlaneImpostor:
  65903. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  65904. returnValue = new this.BJSCANNON.Plane();
  65905. break;
  65906. case BABYLON.PhysicsImpostor.MeshImpostor:
  65907. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  65908. var rawFaces = object.getIndices ? object.getIndices() : [];
  65909. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  65910. returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces);
  65911. break;
  65912. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  65913. returnValue = this._createHeightmap(object);
  65914. break;
  65915. case BABYLON.PhysicsImpostor.ParticleImpostor:
  65916. returnValue = new this.BJSCANNON.Particle();
  65917. break;
  65918. }
  65919. return returnValue;
  65920. };
  65921. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  65922. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  65923. var matrix = new Array();
  65924. //For now pointDepth will not be used and will be automatically calculated.
  65925. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  65926. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  65927. var boundingInfo = (object.getBoundingInfo());
  65928. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.z);
  65929. var minY = boundingInfo.boundingBox.extendSizeWorld.y;
  65930. var elementSize = dim * 2 / arraySize;
  65931. for (var i = 0; i < pos.length; i = i + 3) {
  65932. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  65933. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  65934. var y = pos[i + 1] + minY;
  65935. if (!matrix[x]) {
  65936. matrix[x] = [];
  65937. }
  65938. if (!matrix[x][z]) {
  65939. matrix[x][z] = y;
  65940. }
  65941. matrix[x][z] = Math.max(y, matrix[x][z]);
  65942. }
  65943. for (var x = 0; x <= arraySize; ++x) {
  65944. if (!matrix[x]) {
  65945. var loc = 1;
  65946. while (!matrix[(x + loc) % arraySize]) {
  65947. loc++;
  65948. }
  65949. matrix[x] = matrix[(x + loc) % arraySize].slice();
  65950. //console.log("missing x", x);
  65951. }
  65952. for (var z = 0; z <= arraySize; ++z) {
  65953. if (!matrix[x][z]) {
  65954. var loc = 1;
  65955. var newValue;
  65956. while (newValue === undefined) {
  65957. newValue = matrix[x][(z + loc++) % arraySize];
  65958. }
  65959. matrix[x][z] = newValue;
  65960. }
  65961. }
  65962. }
  65963. var shape = new this.BJSCANNON.Heightfield(matrix, {
  65964. elementSize: elementSize
  65965. });
  65966. //For future reference, needed for body transformation
  65967. shape.minY = minY;
  65968. return shape;
  65969. };
  65970. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  65971. var object = impostor.object;
  65972. //make sure it is updated...
  65973. object.computeWorldMatrix && object.computeWorldMatrix(true);
  65974. // The delta between the mesh position and the mesh bounding box center
  65975. var center = impostor.getObjectCenter();
  65976. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  65977. this._tmpPosition.copyFrom(center);
  65978. var quaternion = object.rotationQuaternion;
  65979. if (!quaternion) {
  65980. return;
  65981. }
  65982. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  65983. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  65984. //-90 DEG in X, precalculated
  65985. quaternion = quaternion.multiply(this._minus90X);
  65986. //Invert! (Precalculated, 90 deg in X)
  65987. //No need to clone. this will never change.
  65988. impostor.setDeltaRotation(this._plus90X);
  65989. }
  65990. //If it is a heightfield, if should be centered.
  65991. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  65992. var mesh = object;
  65993. var boundingInfo = mesh.getBoundingInfo();
  65994. //calculate the correct body position:
  65995. var rotationQuaternion = mesh.rotationQuaternion;
  65996. mesh.rotationQuaternion = this._tmpUnityRotation;
  65997. mesh.computeWorldMatrix(true);
  65998. //get original center with no rotation
  65999. var c = center.clone();
  66000. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  66001. //rotation is back
  66002. mesh.rotationQuaternion = rotationQuaternion;
  66003. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  66004. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  66005. mesh.setPivotMatrix(p);
  66006. mesh.computeWorldMatrix(true);
  66007. //calculate the translation
  66008. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  66009. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  66010. //add it inverted to the delta
  66011. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66012. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66013. mesh.setPivotMatrix(oldPivot);
  66014. mesh.computeWorldMatrix(true);
  66015. }
  66016. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66017. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66018. this._tmpPosition.copyFrom(object.position);
  66019. }
  66020. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66021. //Now update the impostor object
  66022. impostor.physicsBody.position.copy(this._tmpPosition);
  66023. impostor.physicsBody.quaternion.copy(quaternion);
  66024. };
  66025. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66026. impostor.object.position.copyFrom(impostor.physicsBody.position);
  66027. if (impostor.object.rotationQuaternion) {
  66028. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  66029. }
  66030. };
  66031. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66032. impostor.physicsBody.position.copy(newPosition);
  66033. impostor.physicsBody.quaternion.copy(newRotation);
  66034. };
  66035. CannonJSPlugin.prototype.isSupported = function () {
  66036. return this.BJSCANNON !== undefined;
  66037. };
  66038. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66039. impostor.physicsBody.velocity.copy(velocity);
  66040. };
  66041. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66042. impostor.physicsBody.angularVelocity.copy(velocity);
  66043. };
  66044. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66045. var v = impostor.physicsBody.velocity;
  66046. if (!v) {
  66047. return null;
  66048. }
  66049. return new BABYLON.Vector3(v.x, v.y, v.z);
  66050. };
  66051. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66052. var v = impostor.physicsBody.angularVelocity;
  66053. if (!v) {
  66054. return null;
  66055. }
  66056. return new BABYLON.Vector3(v.x, v.y, v.z);
  66057. };
  66058. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66059. impostor.physicsBody.mass = mass;
  66060. impostor.physicsBody.updateMassProperties();
  66061. };
  66062. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  66063. return impostor.physicsBody.mass;
  66064. };
  66065. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  66066. return impostor.physicsBody.material.friction;
  66067. };
  66068. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66069. impostor.physicsBody.material.friction = friction;
  66070. };
  66071. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66072. return impostor.physicsBody.material.restitution;
  66073. };
  66074. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66075. impostor.physicsBody.material.restitution = restitution;
  66076. };
  66077. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  66078. impostor.physicsBody.sleep();
  66079. };
  66080. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  66081. impostor.physicsBody.wakeUp();
  66082. };
  66083. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66084. joint.physicsJoint.distance = maxDistance;
  66085. };
  66086. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66087. // if (!motorIndex) {
  66088. // joint.physicsJoint.enableMotor();
  66089. // }
  66090. // }
  66091. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66092. // if (!motorIndex) {
  66093. // joint.physicsJoint.disableMotor();
  66094. // }
  66095. // }
  66096. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66097. if (!motorIndex) {
  66098. joint.physicsJoint.enableMotor();
  66099. joint.physicsJoint.setMotorSpeed(speed);
  66100. if (maxForce) {
  66101. this.setLimit(joint, maxForce);
  66102. }
  66103. }
  66104. };
  66105. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  66106. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  66107. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  66108. };
  66109. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66110. var body = impostor.physicsBody;
  66111. mesh.position.x = body.position.x;
  66112. mesh.position.y = body.position.y;
  66113. mesh.position.z = body.position.z;
  66114. if (mesh.rotationQuaternion) {
  66115. mesh.rotationQuaternion.x = body.quaternion.x;
  66116. mesh.rotationQuaternion.y = body.quaternion.y;
  66117. mesh.rotationQuaternion.z = body.quaternion.z;
  66118. mesh.rotationQuaternion.w = body.quaternion.w;
  66119. }
  66120. };
  66121. CannonJSPlugin.prototype.getRadius = function (impostor) {
  66122. var shape = impostor.physicsBody.shapes[0];
  66123. return shape.boundingSphereRadius;
  66124. };
  66125. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66126. var shape = impostor.physicsBody.shapes[0];
  66127. result.x = shape.halfExtents.x * 2;
  66128. result.y = shape.halfExtents.y * 2;
  66129. result.z = shape.halfExtents.z * 2;
  66130. };
  66131. CannonJSPlugin.prototype.dispose = function () {
  66132. };
  66133. return CannonJSPlugin;
  66134. }());
  66135. BABYLON.CannonJSPlugin = CannonJSPlugin;
  66136. })(BABYLON || (BABYLON = {}));
  66137. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  66138. var BABYLON;
  66139. (function (BABYLON) {
  66140. var OimoJSPlugin = /** @class */ (function () {
  66141. function OimoJSPlugin(iterations) {
  66142. this.name = "OimoJSPlugin";
  66143. this._tmpImpostorsArray = [];
  66144. this._tmpPositionVector = BABYLON.Vector3.Zero();
  66145. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  66146. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  66147. this.world.worldscale(1);
  66148. this.world.clear();
  66149. //making sure no stats are calculated
  66150. this.world.isNoStat = true;
  66151. }
  66152. OimoJSPlugin.prototype.setGravity = function (gravity) {
  66153. this.world.gravity.copy(gravity);
  66154. };
  66155. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  66156. this.world.timeStep = timeStep;
  66157. };
  66158. OimoJSPlugin.prototype.getTimeStep = function () {
  66159. return this.world.timeStep;
  66160. };
  66161. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  66162. var _this = this;
  66163. impostors.forEach(function (impostor) {
  66164. impostor.beforeStep();
  66165. });
  66166. this.world.step();
  66167. impostors.forEach(function (impostor) {
  66168. impostor.afterStep();
  66169. //update the ordered impostors array
  66170. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  66171. });
  66172. //check for collisions
  66173. var contact = this.world.contacts;
  66174. while (contact !== null) {
  66175. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  66176. contact = contact.next;
  66177. continue;
  66178. }
  66179. //is this body colliding with any other? get the impostor
  66180. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  66181. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  66182. if (!mainImpostor || !collidingImpostor) {
  66183. contact = contact.next;
  66184. continue;
  66185. }
  66186. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  66187. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  66188. contact = contact.next;
  66189. }
  66190. };
  66191. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66192. var mass = impostor.physicsBody.massInfo.mass;
  66193. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  66194. };
  66195. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66196. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  66197. this.applyImpulse(impostor, force, contactPoint);
  66198. };
  66199. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66200. var _this = this;
  66201. //parent-child relationship. Does this impostor has a parent impostor?
  66202. if (impostor.parent) {
  66203. if (impostor.physicsBody) {
  66204. this.removePhysicsBody(impostor);
  66205. //TODO is that needed?
  66206. impostor.forceUpdate();
  66207. }
  66208. return;
  66209. }
  66210. if (impostor.isBodyInitRequired()) {
  66211. var bodyConfig = {
  66212. name: impostor.uniqueId,
  66213. //Oimo must have mass, also for static objects.
  66214. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  66215. size: [],
  66216. type: [],
  66217. pos: [],
  66218. rot: [],
  66219. move: impostor.getParam("mass") !== 0,
  66220. //Supporting older versions of Oimo
  66221. world: this.world
  66222. };
  66223. var impostors = [impostor];
  66224. var addToArray = function (parent) {
  66225. if (!parent.getChildMeshes)
  66226. return;
  66227. parent.getChildMeshes().forEach(function (m) {
  66228. if (m.physicsImpostor) {
  66229. impostors.push(m.physicsImpostor);
  66230. //m.physicsImpostor._init();
  66231. }
  66232. });
  66233. };
  66234. addToArray(impostor.object);
  66235. var checkWithEpsilon_1 = function (value) {
  66236. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  66237. };
  66238. impostors.forEach(function (i) {
  66239. if (!impostor.object.rotationQuaternion) {
  66240. return;
  66241. }
  66242. //get the correct bounding box
  66243. var oldQuaternion = i.object.rotationQuaternion;
  66244. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  66245. x: impostor.object.rotationQuaternion.x,
  66246. y: impostor.object.rotationQuaternion.y,
  66247. z: impostor.object.rotationQuaternion.z,
  66248. s: impostor.object.rotationQuaternion.w
  66249. });
  66250. var extendSize = i.getObjectExtendSize();
  66251. if (i === impostor) {
  66252. var center = impostor.getObjectCenter();
  66253. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  66254. //Can also use Array.prototype.push.apply
  66255. bodyConfig.pos.push(center.x);
  66256. bodyConfig.pos.push(center.y);
  66257. bodyConfig.pos.push(center.z);
  66258. //tmp solution
  66259. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66260. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66261. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66262. }
  66263. else {
  66264. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  66265. bodyConfig.pos.push(localPosition.x);
  66266. bodyConfig.pos.push(localPosition.y);
  66267. bodyConfig.pos.push(localPosition.z);
  66268. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  66269. bodyConfig.rot.push(0);
  66270. bodyConfig.rot.push(0);
  66271. bodyConfig.rot.push(0);
  66272. }
  66273. // register mesh
  66274. switch (i.type) {
  66275. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66276. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  66277. case BABYLON.PhysicsImpostor.SphereImpostor:
  66278. var radiusX = extendSize.x;
  66279. var radiusY = extendSize.y;
  66280. var radiusZ = extendSize.z;
  66281. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  66282. bodyConfig.type.push('sphere');
  66283. //due to the way oimo works with compounds, add 3 times
  66284. bodyConfig.size.push(size);
  66285. bodyConfig.size.push(size);
  66286. bodyConfig.size.push(size);
  66287. break;
  66288. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66289. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  66290. var sizeY = checkWithEpsilon_1(extendSize.y);
  66291. bodyConfig.type.push('cylinder');
  66292. bodyConfig.size.push(sizeX);
  66293. bodyConfig.size.push(sizeY);
  66294. //due to the way oimo works with compounds, add one more value.
  66295. bodyConfig.size.push(sizeY);
  66296. break;
  66297. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66298. case BABYLON.PhysicsImpostor.BoxImpostor:
  66299. default:
  66300. var sizeX = checkWithEpsilon_1(extendSize.x);
  66301. var sizeY = checkWithEpsilon_1(extendSize.y);
  66302. var sizeZ = checkWithEpsilon_1(extendSize.z);
  66303. bodyConfig.type.push('box');
  66304. bodyConfig.size.push(sizeX);
  66305. bodyConfig.size.push(sizeY);
  66306. bodyConfig.size.push(sizeZ);
  66307. break;
  66308. }
  66309. //actually not needed, but hey...
  66310. i.object.rotationQuaternion = oldQuaternion;
  66311. });
  66312. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  66313. }
  66314. else {
  66315. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  66316. }
  66317. impostor.setDeltaPosition(this._tmpPositionVector);
  66318. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  66319. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  66320. };
  66321. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66322. //impostor.physicsBody.dispose();
  66323. //Same as : (older oimo versions)
  66324. this.world.removeRigidBody(impostor.physicsBody);
  66325. };
  66326. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66327. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66328. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66329. if (!mainBody || !connectedBody) {
  66330. return;
  66331. }
  66332. var jointData = impostorJoint.joint.jointData;
  66333. var options = jointData.nativeParams || {};
  66334. var type;
  66335. var nativeJointData = {
  66336. body1: mainBody,
  66337. body2: connectedBody,
  66338. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  66339. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  66340. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  66341. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  66342. min: options.min,
  66343. max: options.max,
  66344. collision: options.collision || jointData.collision,
  66345. spring: options.spring,
  66346. //supporting older version of Oimo
  66347. world: this.world
  66348. };
  66349. switch (impostorJoint.joint.type) {
  66350. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66351. type = "jointBall";
  66352. break;
  66353. case BABYLON.PhysicsJoint.SpringJoint:
  66354. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  66355. var springData = jointData;
  66356. nativeJointData.min = springData.length || nativeJointData.min;
  66357. //Max should also be set, just make sure it is at least min
  66358. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  66359. case BABYLON.PhysicsJoint.DistanceJoint:
  66360. type = "jointDistance";
  66361. nativeJointData.max = jointData.maxDistance;
  66362. break;
  66363. case BABYLON.PhysicsJoint.PrismaticJoint:
  66364. type = "jointPrisme";
  66365. break;
  66366. case BABYLON.PhysicsJoint.SliderJoint:
  66367. type = "jointSlide";
  66368. break;
  66369. case BABYLON.PhysicsJoint.WheelJoint:
  66370. type = "jointWheel";
  66371. break;
  66372. case BABYLON.PhysicsJoint.HingeJoint:
  66373. default:
  66374. type = "jointHinge";
  66375. break;
  66376. }
  66377. nativeJointData.type = type;
  66378. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  66379. };
  66380. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66381. //Bug in Oimo prevents us from disposing a joint in the playground
  66382. //joint.joint.physicsJoint.dispose();
  66383. //So we will bruteforce it!
  66384. try {
  66385. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  66386. }
  66387. catch (e) {
  66388. BABYLON.Tools.Warn(e);
  66389. }
  66390. };
  66391. OimoJSPlugin.prototype.isSupported = function () {
  66392. return this.BJSOIMO !== undefined;
  66393. };
  66394. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66395. if (!impostor.physicsBody.sleeping) {
  66396. //TODO check that
  66397. if (impostor.physicsBody.shapes.next) {
  66398. var parentShape = this._getLastShape(impostor.physicsBody);
  66399. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  66400. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  66401. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  66402. }
  66403. else {
  66404. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  66405. }
  66406. if (impostor.object.rotationQuaternion) {
  66407. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  66408. impostor.object.rotationQuaternion.normalize();
  66409. }
  66410. }
  66411. };
  66412. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66413. var body = impostor.physicsBody;
  66414. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  66415. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  66416. body.syncShapes();
  66417. body.awake();
  66418. };
  66419. OimoJSPlugin.prototype._getLastShape = function (body) {
  66420. var lastShape = body.shapes;
  66421. while (lastShape.next) {
  66422. lastShape = lastShape.next;
  66423. }
  66424. return lastShape;
  66425. };
  66426. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66427. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  66428. };
  66429. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66430. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  66431. };
  66432. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66433. var v = impostor.physicsBody.linearVelocity;
  66434. if (!v) {
  66435. return null;
  66436. }
  66437. return new BABYLON.Vector3(v.x, v.y, v.z);
  66438. };
  66439. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66440. var v = impostor.physicsBody.angularVelocity;
  66441. if (!v) {
  66442. return null;
  66443. }
  66444. return new BABYLON.Vector3(v.x, v.y, v.z);
  66445. };
  66446. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66447. var staticBody = mass === 0;
  66448. //this will actually set the body's density and not its mass.
  66449. //But this is how oimo treats the mass variable.
  66450. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  66451. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  66452. };
  66453. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  66454. return impostor.physicsBody.shapes.density;
  66455. };
  66456. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  66457. return impostor.physicsBody.shapes.friction;
  66458. };
  66459. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66460. impostor.physicsBody.shapes.friction = friction;
  66461. };
  66462. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66463. return impostor.physicsBody.shapes.restitution;
  66464. };
  66465. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66466. impostor.physicsBody.shapes.restitution = restitution;
  66467. };
  66468. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  66469. impostor.physicsBody.sleep();
  66470. };
  66471. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  66472. impostor.physicsBody.awake();
  66473. };
  66474. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66475. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  66476. if (minDistance !== void 0) {
  66477. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  66478. }
  66479. };
  66480. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66481. //TODO separate rotational and transational motors.
  66482. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66483. if (motor) {
  66484. motor.setMotor(speed, maxForce);
  66485. }
  66486. };
  66487. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  66488. //TODO separate rotational and transational motors.
  66489. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66490. if (motor) {
  66491. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  66492. }
  66493. };
  66494. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66495. var body = impostor.physicsBody;
  66496. mesh.position.x = body.position.x;
  66497. mesh.position.y = body.position.y;
  66498. mesh.position.z = body.position.z;
  66499. if (mesh.rotationQuaternion) {
  66500. mesh.rotationQuaternion.x = body.orientation.x;
  66501. mesh.rotationQuaternion.y = body.orientation.y;
  66502. mesh.rotationQuaternion.z = body.orientation.z;
  66503. mesh.rotationQuaternion.w = body.orientation.s;
  66504. }
  66505. };
  66506. OimoJSPlugin.prototype.getRadius = function (impostor) {
  66507. return impostor.physicsBody.shapes.radius;
  66508. };
  66509. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66510. var shape = impostor.physicsBody.shapes;
  66511. result.x = shape.halfWidth * 2;
  66512. result.y = shape.halfHeight * 2;
  66513. result.z = shape.halfDepth * 2;
  66514. };
  66515. OimoJSPlugin.prototype.dispose = function () {
  66516. this.world.clear();
  66517. };
  66518. return OimoJSPlugin;
  66519. }());
  66520. BABYLON.OimoJSPlugin = OimoJSPlugin;
  66521. })(BABYLON || (BABYLON = {}));
  66522. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  66523. var BABYLON;
  66524. (function (BABYLON) {
  66525. var Internals;
  66526. (function (Internals) {
  66527. /*
  66528. * Based on jsTGALoader - Javascript loader for TGA file
  66529. * By Vincent Thibault
  66530. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  66531. */
  66532. var TGATools = /** @class */ (function () {
  66533. function TGATools() {
  66534. }
  66535. TGATools.GetTGAHeader = function (data) {
  66536. var offset = 0;
  66537. var header = {
  66538. id_length: data[offset++],
  66539. colormap_type: data[offset++],
  66540. image_type: data[offset++],
  66541. colormap_index: data[offset++] | data[offset++] << 8,
  66542. colormap_length: data[offset++] | data[offset++] << 8,
  66543. colormap_size: data[offset++],
  66544. origin: [
  66545. data[offset++] | data[offset++] << 8,
  66546. data[offset++] | data[offset++] << 8
  66547. ],
  66548. width: data[offset++] | data[offset++] << 8,
  66549. height: data[offset++] | data[offset++] << 8,
  66550. pixel_size: data[offset++],
  66551. flags: data[offset++]
  66552. };
  66553. return header;
  66554. };
  66555. TGATools.UploadContent = function (gl, data) {
  66556. // Not enough data to contain header ?
  66557. if (data.length < 19) {
  66558. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  66559. return;
  66560. }
  66561. // Read Header
  66562. var offset = 18;
  66563. var header = TGATools.GetTGAHeader(data);
  66564. // Assume it's a valid Targa file.
  66565. if (header.id_length + offset > data.length) {
  66566. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  66567. return;
  66568. }
  66569. // Skip not needed data
  66570. offset += header.id_length;
  66571. var use_rle = false;
  66572. var use_pal = false;
  66573. var use_rgb = false;
  66574. var use_grey = false;
  66575. // Get some informations.
  66576. switch (header.image_type) {
  66577. case TGATools._TYPE_RLE_INDEXED:
  66578. use_rle = true;
  66579. case TGATools._TYPE_INDEXED:
  66580. use_pal = true;
  66581. break;
  66582. case TGATools._TYPE_RLE_RGB:
  66583. use_rle = true;
  66584. case TGATools._TYPE_RGB:
  66585. use_rgb = true;
  66586. break;
  66587. case TGATools._TYPE_RLE_GREY:
  66588. use_rle = true;
  66589. case TGATools._TYPE_GREY:
  66590. use_grey = true;
  66591. break;
  66592. }
  66593. var pixel_data;
  66594. // var numAlphaBits = header.flags & 0xf;
  66595. var pixel_size = header.pixel_size >> 3;
  66596. var pixel_total = header.width * header.height * pixel_size;
  66597. // Read palettes
  66598. var palettes;
  66599. if (use_pal) {
  66600. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  66601. }
  66602. // Read LRE
  66603. if (use_rle) {
  66604. pixel_data = new Uint8Array(pixel_total);
  66605. var c, count, i;
  66606. var localOffset = 0;
  66607. var pixels = new Uint8Array(pixel_size);
  66608. while (offset < pixel_total && localOffset < pixel_total) {
  66609. c = data[offset++];
  66610. count = (c & 0x7f) + 1;
  66611. // RLE pixels
  66612. if (c & 0x80) {
  66613. // Bind pixel tmp array
  66614. for (i = 0; i < pixel_size; ++i) {
  66615. pixels[i] = data[offset++];
  66616. }
  66617. // Copy pixel array
  66618. for (i = 0; i < count; ++i) {
  66619. pixel_data.set(pixels, localOffset + i * pixel_size);
  66620. }
  66621. localOffset += pixel_size * count;
  66622. }
  66623. else {
  66624. count *= pixel_size;
  66625. for (i = 0; i < count; ++i) {
  66626. pixel_data[localOffset + i] = data[offset++];
  66627. }
  66628. localOffset += count;
  66629. }
  66630. }
  66631. }
  66632. else {
  66633. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  66634. }
  66635. // Load to texture
  66636. var x_start, y_start, x_step, y_step, y_end, x_end;
  66637. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  66638. default:
  66639. case TGATools._ORIGIN_UL:
  66640. x_start = 0;
  66641. x_step = 1;
  66642. x_end = header.width;
  66643. y_start = 0;
  66644. y_step = 1;
  66645. y_end = header.height;
  66646. break;
  66647. case TGATools._ORIGIN_BL:
  66648. x_start = 0;
  66649. x_step = 1;
  66650. x_end = header.width;
  66651. y_start = header.height - 1;
  66652. y_step = -1;
  66653. y_end = -1;
  66654. break;
  66655. case TGATools._ORIGIN_UR:
  66656. x_start = header.width - 1;
  66657. x_step = -1;
  66658. x_end = -1;
  66659. y_start = 0;
  66660. y_step = 1;
  66661. y_end = header.height;
  66662. break;
  66663. case TGATools._ORIGIN_BR:
  66664. x_start = header.width - 1;
  66665. x_step = -1;
  66666. x_end = -1;
  66667. y_start = header.height - 1;
  66668. y_step = -1;
  66669. y_end = -1;
  66670. break;
  66671. }
  66672. // Load the specify method
  66673. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  66674. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  66675. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  66676. };
  66677. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66678. var image = pixel_data, colormap = palettes;
  66679. var width = header.width, height = header.height;
  66680. var color, i = 0, x, y;
  66681. var imageData = new Uint8Array(width * height * 4);
  66682. for (y = y_start; y !== y_end; y += y_step) {
  66683. for (x = x_start; x !== x_end; x += x_step, i++) {
  66684. color = image[i];
  66685. imageData[(x + width * y) * 4 + 3] = 255;
  66686. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  66687. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  66688. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  66689. }
  66690. }
  66691. return imageData;
  66692. };
  66693. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66694. var image = pixel_data;
  66695. var width = header.width, height = header.height;
  66696. var color, i = 0, x, y;
  66697. var imageData = new Uint8Array(width * height * 4);
  66698. for (y = y_start; y !== y_end; y += y_step) {
  66699. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66700. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  66701. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  66702. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  66703. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  66704. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  66705. }
  66706. }
  66707. return imageData;
  66708. };
  66709. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66710. var image = pixel_data;
  66711. var width = header.width, height = header.height;
  66712. var i = 0, x, y;
  66713. var imageData = new Uint8Array(width * height * 4);
  66714. for (y = y_start; y !== y_end; y += y_step) {
  66715. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  66716. imageData[(x + width * y) * 4 + 3] = 255;
  66717. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66718. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66719. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66720. }
  66721. }
  66722. return imageData;
  66723. };
  66724. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66725. var image = pixel_data;
  66726. var width = header.width, height = header.height;
  66727. var i = 0, x, y;
  66728. var imageData = new Uint8Array(width * height * 4);
  66729. for (y = y_start; y !== y_end; y += y_step) {
  66730. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  66731. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66732. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66733. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66734. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  66735. }
  66736. }
  66737. return imageData;
  66738. };
  66739. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66740. var image = pixel_data;
  66741. var width = header.width, height = header.height;
  66742. var color, i = 0, x, y;
  66743. var imageData = new Uint8Array(width * height * 4);
  66744. for (y = y_start; y !== y_end; y += y_step) {
  66745. for (x = x_start; x !== x_end; x += x_step, i++) {
  66746. color = image[i];
  66747. imageData[(x + width * y) * 4 + 0] = color;
  66748. imageData[(x + width * y) * 4 + 1] = color;
  66749. imageData[(x + width * y) * 4 + 2] = color;
  66750. imageData[(x + width * y) * 4 + 3] = 255;
  66751. }
  66752. }
  66753. return imageData;
  66754. };
  66755. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66756. var image = pixel_data;
  66757. var width = header.width, height = header.height;
  66758. var i = 0, x, y;
  66759. var imageData = new Uint8Array(width * height * 4);
  66760. for (y = y_start; y !== y_end; y += y_step) {
  66761. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66762. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  66763. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  66764. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66765. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  66766. }
  66767. }
  66768. return imageData;
  66769. };
  66770. //private static _TYPE_NO_DATA = 0;
  66771. TGATools._TYPE_INDEXED = 1;
  66772. TGATools._TYPE_RGB = 2;
  66773. TGATools._TYPE_GREY = 3;
  66774. TGATools._TYPE_RLE_INDEXED = 9;
  66775. TGATools._TYPE_RLE_RGB = 10;
  66776. TGATools._TYPE_RLE_GREY = 11;
  66777. TGATools._ORIGIN_MASK = 0x30;
  66778. TGATools._ORIGIN_SHIFT = 0x04;
  66779. TGATools._ORIGIN_BL = 0x00;
  66780. TGATools._ORIGIN_BR = 0x01;
  66781. TGATools._ORIGIN_UL = 0x02;
  66782. TGATools._ORIGIN_UR = 0x03;
  66783. return TGATools;
  66784. }());
  66785. Internals.TGATools = TGATools;
  66786. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66787. })(BABYLON || (BABYLON = {}));
  66788. //# sourceMappingURL=babylon.tga.js.map
  66789. var BABYLON;
  66790. (function (BABYLON) {
  66791. var Internals;
  66792. (function (Internals) {
  66793. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  66794. // All values and structures referenced from:
  66795. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  66796. var DDS_MAGIC = 0x20534444;
  66797. var
  66798. //DDSD_CAPS = 0x1,
  66799. //DDSD_HEIGHT = 0x2,
  66800. //DDSD_WIDTH = 0x4,
  66801. //DDSD_PITCH = 0x8,
  66802. //DDSD_PIXELFORMAT = 0x1000,
  66803. DDSD_MIPMAPCOUNT = 0x20000;
  66804. //DDSD_LINEARSIZE = 0x80000,
  66805. //DDSD_DEPTH = 0x800000;
  66806. // var DDSCAPS_COMPLEX = 0x8,
  66807. // DDSCAPS_MIPMAP = 0x400000,
  66808. // DDSCAPS_TEXTURE = 0x1000;
  66809. var DDSCAPS2_CUBEMAP = 0x200;
  66810. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  66811. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  66812. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  66813. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  66814. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  66815. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  66816. // DDSCAPS2_VOLUME = 0x200000;
  66817. var
  66818. //DDPF_ALPHAPIXELS = 0x1,
  66819. //DDPF_ALPHA = 0x2,
  66820. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  66821. //DDPF_YUV = 0x200,
  66822. DDPF_LUMINANCE = 0x20000;
  66823. function FourCCToInt32(value) {
  66824. return value.charCodeAt(0) +
  66825. (value.charCodeAt(1) << 8) +
  66826. (value.charCodeAt(2) << 16) +
  66827. (value.charCodeAt(3) << 24);
  66828. }
  66829. function Int32ToFourCC(value) {
  66830. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  66831. }
  66832. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  66833. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  66834. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  66835. var FOURCC_DX10 = FourCCToInt32("DX10");
  66836. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  66837. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  66838. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  66839. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  66840. var headerLengthInt = 31; // The header length in 32 bit ints
  66841. // Offsets into the header array
  66842. var off_magic = 0;
  66843. var off_size = 1;
  66844. var off_flags = 2;
  66845. var off_height = 3;
  66846. var off_width = 4;
  66847. var off_mipmapCount = 7;
  66848. var off_pfFlags = 20;
  66849. var off_pfFourCC = 21;
  66850. var off_RGBbpp = 22;
  66851. // var off_RMask = 23;
  66852. // var off_GMask = 24;
  66853. // var off_BMask = 25;
  66854. // var off_AMask = 26;
  66855. // var off_caps1 = 27;
  66856. var off_caps2 = 28;
  66857. // var off_caps3 = 29;
  66858. // var off_caps4 = 30;
  66859. var off_dxgiFormat = 32;
  66860. ;
  66861. var DDSTools = /** @class */ (function () {
  66862. function DDSTools() {
  66863. }
  66864. DDSTools.GetDDSInfo = function (arrayBuffer) {
  66865. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  66866. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  66867. var mipmapCount = 1;
  66868. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  66869. mipmapCount = Math.max(1, header[off_mipmapCount]);
  66870. }
  66871. var fourCC = header[off_pfFourCC];
  66872. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  66873. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66874. switch (fourCC) {
  66875. case FOURCC_D3DFMT_R16G16B16A16F:
  66876. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66877. break;
  66878. case FOURCC_D3DFMT_R32G32B32A32F:
  66879. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66880. break;
  66881. case FOURCC_DX10:
  66882. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  66883. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66884. break;
  66885. }
  66886. }
  66887. return {
  66888. width: header[off_width],
  66889. height: header[off_height],
  66890. mipmapCount: mipmapCount,
  66891. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  66892. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  66893. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  66894. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  66895. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  66896. dxgiFormat: dxgiFormat,
  66897. textureType: textureType
  66898. };
  66899. };
  66900. DDSTools._ToHalfFloat = function (value) {
  66901. if (!DDSTools._FloatView) {
  66902. DDSTools._FloatView = new Float32Array(1);
  66903. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  66904. }
  66905. DDSTools._FloatView[0] = value;
  66906. var x = DDSTools._Int32View[0];
  66907. var bits = (x >> 16) & 0x8000; /* Get the sign */
  66908. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  66909. var e = (x >> 23) & 0xff; /* Using int is faster here */
  66910. /* If zero, or denormal, or exponent underflows too much for a denormal
  66911. * half, return signed zero. */
  66912. if (e < 103) {
  66913. return bits;
  66914. }
  66915. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  66916. if (e > 142) {
  66917. bits |= 0x7c00;
  66918. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  66919. * not Inf, so make sure we set one mantissa bit too. */
  66920. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  66921. return bits;
  66922. }
  66923. /* If exponent underflows but not too much, return a denormal */
  66924. if (e < 113) {
  66925. m |= 0x0800;
  66926. /* Extra rounding may overflow and set mantissa to 0 and exponent
  66927. * to 1, which is OK. */
  66928. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  66929. return bits;
  66930. }
  66931. bits |= ((e - 112) << 10) | (m >> 1);
  66932. bits += m & 1;
  66933. return bits;
  66934. };
  66935. DDSTools._FromHalfFloat = function (value) {
  66936. var s = (value & 0x8000) >> 15;
  66937. var e = (value & 0x7C00) >> 10;
  66938. var f = value & 0x03FF;
  66939. if (e === 0) {
  66940. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  66941. }
  66942. else if (e == 0x1F) {
  66943. return f ? NaN : ((s ? -1 : 1) * Infinity);
  66944. }
  66945. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  66946. };
  66947. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66948. var destArray = new Float32Array(dataLength);
  66949. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  66950. var index = 0;
  66951. for (var y = 0; y < height; y++) {
  66952. for (var x = 0; x < width; x++) {
  66953. var srcPos = (x + y * width) * 4;
  66954. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  66955. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  66956. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  66957. if (DDSTools.StoreLODInAlphaChannel) {
  66958. destArray[index + 3] = lod;
  66959. }
  66960. else {
  66961. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  66962. }
  66963. index += 4;
  66964. }
  66965. }
  66966. return destArray;
  66967. };
  66968. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66969. if (DDSTools.StoreLODInAlphaChannel) {
  66970. var destArray = new Uint16Array(dataLength);
  66971. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  66972. var index = 0;
  66973. for (var y = 0; y < height; y++) {
  66974. for (var x = 0; x < width; x++) {
  66975. var srcPos = (x + y * width) * 4;
  66976. destArray[index] = srcData[srcPos];
  66977. destArray[index + 1] = srcData[srcPos + 1];
  66978. destArray[index + 2] = srcData[srcPos + 2];
  66979. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  66980. index += 4;
  66981. }
  66982. }
  66983. return destArray;
  66984. }
  66985. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  66986. };
  66987. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66988. if (DDSTools.StoreLODInAlphaChannel) {
  66989. var destArray = new Float32Array(dataLength);
  66990. var srcData = new Float32Array(arrayBuffer, dataOffset);
  66991. var index = 0;
  66992. for (var y = 0; y < height; y++) {
  66993. for (var x = 0; x < width; x++) {
  66994. var srcPos = (x + y * width) * 4;
  66995. destArray[index] = srcData[srcPos];
  66996. destArray[index + 1] = srcData[srcPos + 1];
  66997. destArray[index + 2] = srcData[srcPos + 2];
  66998. destArray[index + 3] = lod;
  66999. index += 4;
  67000. }
  67001. }
  67002. return destArray;
  67003. }
  67004. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  67005. };
  67006. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67007. var destArray = new Uint8Array(dataLength);
  67008. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67009. var index = 0;
  67010. for (var y = 0; y < height; y++) {
  67011. for (var x = 0; x < width; x++) {
  67012. var srcPos = (x + y * width) * 4;
  67013. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67014. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67015. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67016. if (DDSTools.StoreLODInAlphaChannel) {
  67017. destArray[index + 3] = lod;
  67018. }
  67019. else {
  67020. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67021. }
  67022. index += 4;
  67023. }
  67024. }
  67025. return destArray;
  67026. };
  67027. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67028. var destArray = new Uint8Array(dataLength);
  67029. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67030. var index = 0;
  67031. for (var y = 0; y < height; y++) {
  67032. for (var x = 0; x < width; x++) {
  67033. var srcPos = (x + y * width) * 4;
  67034. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  67035. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  67036. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  67037. if (DDSTools.StoreLODInAlphaChannel) {
  67038. destArray[index + 3] = lod;
  67039. }
  67040. else {
  67041. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  67042. }
  67043. index += 4;
  67044. }
  67045. }
  67046. return destArray;
  67047. };
  67048. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67049. var byteArray = new Uint8Array(dataLength);
  67050. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67051. var index = 0;
  67052. for (var y = 0; y < height; y++) {
  67053. for (var x = 0; x < width; x++) {
  67054. var srcPos = (x + y * width) * 4;
  67055. byteArray[index] = srcData[srcPos + 2];
  67056. byteArray[index + 1] = srcData[srcPos + 1];
  67057. byteArray[index + 2] = srcData[srcPos];
  67058. byteArray[index + 3] = srcData[srcPos + 3];
  67059. index += 4;
  67060. }
  67061. }
  67062. return byteArray;
  67063. };
  67064. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67065. var byteArray = new Uint8Array(dataLength);
  67066. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67067. var index = 0;
  67068. for (var y = 0; y < height; y++) {
  67069. for (var x = 0; x < width; x++) {
  67070. var srcPos = (x + y * width) * 3;
  67071. byteArray[index] = srcData[srcPos + 2];
  67072. byteArray[index + 1] = srcData[srcPos + 1];
  67073. byteArray[index + 2] = srcData[srcPos];
  67074. index += 3;
  67075. }
  67076. }
  67077. return byteArray;
  67078. };
  67079. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67080. var byteArray = new Uint8Array(dataLength);
  67081. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67082. var index = 0;
  67083. for (var y = 0; y < height; y++) {
  67084. for (var x = 0; x < width; x++) {
  67085. var srcPos = (x + y * width);
  67086. byteArray[index] = srcData[srcPos];
  67087. index++;
  67088. }
  67089. }
  67090. return byteArray;
  67091. };
  67092. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  67093. if (lodIndex === void 0) { lodIndex = -1; }
  67094. var ext = engine.getCaps().s3tc;
  67095. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  67096. var internalFormat = 0;
  67097. var format = 0;
  67098. var blockBytes = 1;
  67099. if (header[off_magic] != DDS_MAGIC) {
  67100. BABYLON.Tools.Error("Invalid magic number in DDS header");
  67101. return;
  67102. }
  67103. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  67104. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  67105. return;
  67106. }
  67107. if (info.isCompressed && !ext) {
  67108. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  67109. return;
  67110. }
  67111. var bpp = header[off_RGBbpp];
  67112. dataOffset = header[off_size] + 4;
  67113. var computeFormats = false;
  67114. if (info.isFourCC) {
  67115. fourCC = header[off_pfFourCC];
  67116. switch (fourCC) {
  67117. case FOURCC_DXT1:
  67118. blockBytes = 8;
  67119. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  67120. break;
  67121. case FOURCC_DXT3:
  67122. blockBytes = 16;
  67123. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  67124. break;
  67125. case FOURCC_DXT5:
  67126. blockBytes = 16;
  67127. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  67128. break;
  67129. case FOURCC_D3DFMT_R16G16B16A16F:
  67130. computeFormats = true;
  67131. break;
  67132. case FOURCC_D3DFMT_R32G32B32A32F:
  67133. computeFormats = true;
  67134. break;
  67135. case FOURCC_DX10:
  67136. // There is an additionnal header so dataOffset need to be changed
  67137. dataOffset += 5 * 4; // 5 uints
  67138. var supported = false;
  67139. switch (info.dxgiFormat) {
  67140. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  67141. computeFormats = true;
  67142. supported = true;
  67143. break;
  67144. case DXGI_FORMAT_B8G8R8X8_UNORM:
  67145. info.isRGB = true;
  67146. info.isFourCC = false;
  67147. bpp = 32;
  67148. supported = true;
  67149. break;
  67150. }
  67151. if (supported) {
  67152. break;
  67153. }
  67154. default:
  67155. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  67156. return;
  67157. }
  67158. }
  67159. if (computeFormats) {
  67160. format = engine._getWebGLTextureType(info.textureType);
  67161. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67162. }
  67163. mipmapCount = 1;
  67164. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  67165. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67166. }
  67167. for (var face = 0; face < faces; face++) {
  67168. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67169. width = header[off_width];
  67170. height = header[off_height];
  67171. for (mip = 0; mip < mipmapCount; ++mip) {
  67172. if (lodIndex === -1 || lodIndex === mip) {
  67173. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  67174. var i = (lodIndex === -1) ? mip : 0;
  67175. if (!info.isCompressed && info.isFourCC) {
  67176. dataLength = width * height * 4;
  67177. var FloatArray = null;
  67178. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  67179. if (bpp === 128) {
  67180. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67181. }
  67182. else if (bpp === 64) {
  67183. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67184. }
  67185. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67186. format = engine._getWebGLTextureType(info.textureType);
  67187. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67188. }
  67189. else {
  67190. if (bpp === 128) {
  67191. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67192. }
  67193. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  67194. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67195. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67196. format = engine._getWebGLTextureType(info.textureType);
  67197. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67198. }
  67199. else {
  67200. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67201. }
  67202. }
  67203. if (FloatArray) {
  67204. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  67205. }
  67206. }
  67207. else if (info.isRGB) {
  67208. if (bpp === 24) {
  67209. dataLength = width * height * 3;
  67210. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67211. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  67212. }
  67213. else {
  67214. dataLength = width * height * 4;
  67215. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67216. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  67217. }
  67218. }
  67219. else if (info.isLuminance) {
  67220. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  67221. var unpaddedRowSize = width;
  67222. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  67223. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  67224. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67225. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  67226. }
  67227. else {
  67228. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  67229. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  67230. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  67231. }
  67232. }
  67233. dataOffset += width * height * (bpp / 8);
  67234. width *= 0.5;
  67235. height *= 0.5;
  67236. width = Math.max(1.0, width);
  67237. height = Math.max(1.0, height);
  67238. }
  67239. }
  67240. };
  67241. DDSTools.StoreLODInAlphaChannel = false;
  67242. return DDSTools;
  67243. }());
  67244. Internals.DDSTools = DDSTools;
  67245. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67246. })(BABYLON || (BABYLON = {}));
  67247. //# sourceMappingURL=babylon.dds.js.map
  67248. var BABYLON;
  67249. (function (BABYLON) {
  67250. var Internals;
  67251. (function (Internals) {
  67252. /**
  67253. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  67254. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  67255. */
  67256. var KhronosTextureContainer = /** @class */ (function () {
  67257. /**
  67258. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  67259. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  67260. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  67261. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  67262. */
  67263. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  67264. this.arrayBuffer = arrayBuffer;
  67265. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  67266. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  67267. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  67268. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  67269. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  67270. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  67271. BABYLON.Tools.Error("texture missing KTX identifier");
  67272. return;
  67273. }
  67274. // load the reset of the header in native 32 bit int
  67275. var header = new Int32Array(this.arrayBuffer, 12, 13);
  67276. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  67277. var oppositeEndianess = header[0] === 0x01020304;
  67278. // read all the header elements in order they exist in the file, without modification (sans endainness)
  67279. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  67280. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  67281. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  67282. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  67283. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  67284. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  67285. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  67286. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  67287. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  67288. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  67289. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  67290. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  67291. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  67292. if (this.glType !== 0) {
  67293. BABYLON.Tools.Error("only compressed formats currently supported");
  67294. return;
  67295. }
  67296. else {
  67297. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  67298. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  67299. }
  67300. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  67301. BABYLON.Tools.Error("only 2D textures currently supported");
  67302. return;
  67303. }
  67304. if (this.numberOfArrayElements !== 0) {
  67305. BABYLON.Tools.Error("texture arrays not currently supported");
  67306. return;
  67307. }
  67308. if (this.numberOfFaces !== facesExpected) {
  67309. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  67310. return;
  67311. }
  67312. // we now have a completely validated file, so could use existence of loadType as success
  67313. // would need to make this more elaborate & adjust checks above to support more than one load type
  67314. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  67315. }
  67316. // not as fast hardware based, but will probably never need to use
  67317. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  67318. return ((val & 0xFF) << 24)
  67319. | ((val & 0xFF00) << 8)
  67320. | ((val >> 8) & 0xFF00)
  67321. | ((val >> 24) & 0xFF);
  67322. };
  67323. /**
  67324. * It is assumed that the texture has already been created & is currently bound
  67325. */
  67326. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  67327. switch (this.loadType) {
  67328. case KhronosTextureContainer.COMPRESSED_2D:
  67329. this._upload2DCompressedLevels(gl, loadMipmaps);
  67330. break;
  67331. case KhronosTextureContainer.TEX_2D:
  67332. case KhronosTextureContainer.COMPRESSED_3D:
  67333. case KhronosTextureContainer.TEX_3D:
  67334. }
  67335. };
  67336. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  67337. // initialize width & height for level 1
  67338. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  67339. var width = this.pixelWidth;
  67340. var height = this.pixelHeight;
  67341. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  67342. for (var level = 0; level < mipmapCount; level++) {
  67343. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  67344. for (var face = 0; face < this.numberOfFaces; face++) {
  67345. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67346. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  67347. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  67348. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  67349. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  67350. }
  67351. width = Math.max(1.0, width * 0.5);
  67352. height = Math.max(1.0, height * 0.5);
  67353. }
  67354. };
  67355. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  67356. // load types
  67357. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  67358. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  67359. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  67360. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  67361. return KhronosTextureContainer;
  67362. }());
  67363. Internals.KhronosTextureContainer = KhronosTextureContainer;
  67364. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67365. })(BABYLON || (BABYLON = {}));
  67366. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  67367. var BABYLON;
  67368. (function (BABYLON) {
  67369. var Debug;
  67370. (function (Debug) {
  67371. /**
  67372. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  67373. */
  67374. var SkeletonViewer = /** @class */ (function () {
  67375. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  67376. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  67377. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  67378. this.skeleton = skeleton;
  67379. this.mesh = mesh;
  67380. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  67381. this.renderingGroupId = renderingGroupId;
  67382. this.color = BABYLON.Color3.White();
  67383. this._debugLines = new Array();
  67384. this._isEnabled = false;
  67385. this._scene = scene;
  67386. this.update();
  67387. this._renderFunction = this.update.bind(this);
  67388. }
  67389. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  67390. get: function () {
  67391. return this._isEnabled;
  67392. },
  67393. set: function (value) {
  67394. if (this._isEnabled === value) {
  67395. return;
  67396. }
  67397. this._isEnabled = value;
  67398. if (value) {
  67399. this._scene.registerBeforeRender(this._renderFunction);
  67400. }
  67401. else {
  67402. this._scene.unregisterBeforeRender(this._renderFunction);
  67403. }
  67404. },
  67405. enumerable: true,
  67406. configurable: true
  67407. });
  67408. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  67409. if (x === void 0) { x = 0; }
  67410. if (y === void 0) { y = 0; }
  67411. if (z === void 0) { z = 0; }
  67412. var tmat = BABYLON.Tmp.Matrix[0];
  67413. var parentBone = bone.getParent();
  67414. tmat.copyFrom(bone.getLocalMatrix());
  67415. if (x !== 0 || y !== 0 || z !== 0) {
  67416. var tmat2 = BABYLON.Tmp.Matrix[1];
  67417. BABYLON.Matrix.IdentityToRef(tmat2);
  67418. tmat2.m[12] = x;
  67419. tmat2.m[13] = y;
  67420. tmat2.m[14] = z;
  67421. tmat2.multiplyToRef(tmat, tmat);
  67422. }
  67423. if (parentBone) {
  67424. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  67425. }
  67426. tmat.multiplyToRef(meshMat, tmat);
  67427. position.x = tmat.m[12];
  67428. position.y = tmat.m[13];
  67429. position.z = tmat.m[14];
  67430. };
  67431. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  67432. var len = bones.length;
  67433. var meshPos = this.mesh.position;
  67434. for (var i = 0; i < len; i++) {
  67435. var bone = bones[i];
  67436. var points = this._debugLines[i];
  67437. if (!points) {
  67438. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67439. this._debugLines[i] = points;
  67440. }
  67441. this._getBonePosition(points[0], bone, meshMat);
  67442. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  67443. points[0].subtractInPlace(meshPos);
  67444. points[1].subtractInPlace(meshPos);
  67445. }
  67446. };
  67447. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  67448. var len = bones.length;
  67449. var boneNum = 0;
  67450. var meshPos = this.mesh.position;
  67451. for (var i = len - 1; i >= 0; i--) {
  67452. var childBone = bones[i];
  67453. var parentBone = childBone.getParent();
  67454. if (!parentBone) {
  67455. continue;
  67456. }
  67457. var points = this._debugLines[boneNum];
  67458. if (!points) {
  67459. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67460. this._debugLines[boneNum] = points;
  67461. }
  67462. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  67463. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  67464. points[0].subtractInPlace(meshPos);
  67465. points[1].subtractInPlace(meshPos);
  67466. boneNum++;
  67467. }
  67468. };
  67469. SkeletonViewer.prototype.update = function () {
  67470. if (this.autoUpdateBonesMatrices) {
  67471. this.skeleton.computeAbsoluteTransforms();
  67472. }
  67473. if (this.skeleton.bones[0].length === undefined) {
  67474. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67475. }
  67476. else {
  67477. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67478. }
  67479. if (!this._debugMesh) {
  67480. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  67481. this._debugMesh.renderingGroupId = this.renderingGroupId;
  67482. }
  67483. else {
  67484. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  67485. }
  67486. this._debugMesh.position.copyFrom(this.mesh.position);
  67487. this._debugMesh.color = this.color;
  67488. };
  67489. SkeletonViewer.prototype.dispose = function () {
  67490. if (this._debugMesh) {
  67491. this.isEnabled = false;
  67492. this._debugMesh.dispose();
  67493. this._debugMesh = null;
  67494. }
  67495. };
  67496. return SkeletonViewer;
  67497. }());
  67498. Debug.SkeletonViewer = SkeletonViewer;
  67499. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67500. })(BABYLON || (BABYLON = {}));
  67501. //# sourceMappingURL=babylon.skeletonViewer.js.map
  67502. var BABYLON;
  67503. (function (BABYLON) {
  67504. var Debug;
  67505. (function (Debug) {
  67506. var AxesViewer = /** @class */ (function () {
  67507. function AxesViewer(scene, scaleLines) {
  67508. if (scaleLines === void 0) { scaleLines = 1; }
  67509. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67510. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67511. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67512. this.scaleLines = 1;
  67513. this.scaleLines = scaleLines;
  67514. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  67515. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  67516. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  67517. this._xmesh.renderingGroupId = 2;
  67518. this._ymesh.renderingGroupId = 2;
  67519. this._zmesh.renderingGroupId = 2;
  67520. this._xmesh.material.checkReadyOnlyOnce = true;
  67521. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  67522. this._ymesh.material.checkReadyOnlyOnce = true;
  67523. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  67524. this._zmesh.material.checkReadyOnlyOnce = true;
  67525. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  67526. this.scene = scene;
  67527. }
  67528. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  67529. var scaleLines = this.scaleLines;
  67530. if (this._xmesh) {
  67531. this._xmesh.position.copyFrom(position);
  67532. }
  67533. if (this._ymesh) {
  67534. this._ymesh.position.copyFrom(position);
  67535. }
  67536. if (this._zmesh) {
  67537. this._zmesh.position.copyFrom(position);
  67538. }
  67539. var point2 = this._xline[1];
  67540. point2.x = xaxis.x * scaleLines;
  67541. point2.y = xaxis.y * scaleLines;
  67542. point2.z = xaxis.z * scaleLines;
  67543. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  67544. point2 = this._yline[1];
  67545. point2.x = yaxis.x * scaleLines;
  67546. point2.y = yaxis.y * scaleLines;
  67547. point2.z = yaxis.z * scaleLines;
  67548. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  67549. point2 = this._zline[1];
  67550. point2.x = zaxis.x * scaleLines;
  67551. point2.y = zaxis.y * scaleLines;
  67552. point2.z = zaxis.z * scaleLines;
  67553. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  67554. };
  67555. AxesViewer.prototype.dispose = function () {
  67556. if (this._xmesh) {
  67557. this._xmesh.dispose();
  67558. }
  67559. if (this._ymesh) {
  67560. this._ymesh.dispose();
  67561. }
  67562. if (this._zmesh) {
  67563. this._zmesh.dispose();
  67564. }
  67565. this._xmesh = null;
  67566. this._ymesh = null;
  67567. this._zmesh = null;
  67568. this.scene = null;
  67569. };
  67570. return AxesViewer;
  67571. }());
  67572. Debug.AxesViewer = AxesViewer;
  67573. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67574. })(BABYLON || (BABYLON = {}));
  67575. //# sourceMappingURL=babylon.axesViewer.js.map
  67576. var BABYLON;
  67577. (function (BABYLON) {
  67578. var Debug;
  67579. (function (Debug) {
  67580. var BoneAxesViewer = /** @class */ (function (_super) {
  67581. __extends(BoneAxesViewer, _super);
  67582. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  67583. if (scaleLines === void 0) { scaleLines = 1; }
  67584. var _this = _super.call(this, scene, scaleLines) || this;
  67585. _this.pos = BABYLON.Vector3.Zero();
  67586. _this.xaxis = BABYLON.Vector3.Zero();
  67587. _this.yaxis = BABYLON.Vector3.Zero();
  67588. _this.zaxis = BABYLON.Vector3.Zero();
  67589. _this.mesh = mesh;
  67590. _this.bone = bone;
  67591. return _this;
  67592. }
  67593. BoneAxesViewer.prototype.update = function () {
  67594. if (!this.mesh || !this.bone) {
  67595. return;
  67596. }
  67597. var bone = this.bone;
  67598. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  67599. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  67600. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  67601. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  67602. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  67603. };
  67604. BoneAxesViewer.prototype.dispose = function () {
  67605. if (this.mesh) {
  67606. this.mesh = null;
  67607. this.bone = null;
  67608. _super.prototype.dispose.call(this);
  67609. }
  67610. };
  67611. return BoneAxesViewer;
  67612. }(Debug.AxesViewer));
  67613. Debug.BoneAxesViewer = BoneAxesViewer;
  67614. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67615. })(BABYLON || (BABYLON = {}));
  67616. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  67617. var BABYLON;
  67618. (function (BABYLON) {
  67619. var RayHelper = /** @class */ (function () {
  67620. function RayHelper(ray) {
  67621. this.ray = ray;
  67622. }
  67623. RayHelper.CreateAndShow = function (ray, scene, color) {
  67624. var helper = new RayHelper(ray);
  67625. helper.show(scene, color);
  67626. return helper;
  67627. };
  67628. RayHelper.prototype.show = function (scene, color) {
  67629. if (!this._renderFunction && this.ray) {
  67630. var ray = this.ray;
  67631. this._renderFunction = this._render.bind(this);
  67632. this._scene = scene;
  67633. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  67634. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  67635. if (this._renderFunction) {
  67636. this._scene.registerBeforeRender(this._renderFunction);
  67637. }
  67638. }
  67639. if (color && this._renderLine) {
  67640. this._renderLine.color.copyFrom(color);
  67641. }
  67642. };
  67643. RayHelper.prototype.hide = function () {
  67644. if (this._renderFunction && this._scene) {
  67645. this._scene.unregisterBeforeRender(this._renderFunction);
  67646. this._scene = null;
  67647. this._renderFunction = null;
  67648. if (this._renderLine) {
  67649. this._renderLine.dispose();
  67650. this._renderLine = null;
  67651. }
  67652. this._renderPoints = [];
  67653. }
  67654. };
  67655. RayHelper.prototype._render = function () {
  67656. var ray = this.ray;
  67657. if (!ray) {
  67658. return;
  67659. }
  67660. var point = this._renderPoints[1];
  67661. var len = Math.min(ray.length, 1000000);
  67662. point.copyFrom(ray.direction);
  67663. point.scaleInPlace(len);
  67664. point.addInPlace(ray.origin);
  67665. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  67666. };
  67667. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  67668. this._attachedToMesh = mesh;
  67669. var ray = this.ray;
  67670. if (!ray) {
  67671. return;
  67672. }
  67673. if (!ray.direction) {
  67674. ray.direction = BABYLON.Vector3.Zero();
  67675. }
  67676. if (!ray.origin) {
  67677. ray.origin = BABYLON.Vector3.Zero();
  67678. }
  67679. if (length) {
  67680. ray.length = length;
  67681. }
  67682. if (!meshSpaceOrigin) {
  67683. meshSpaceOrigin = BABYLON.Vector3.Zero();
  67684. }
  67685. if (!meshSpaceDirection) {
  67686. // -1 so that this will work with Mesh.lookAt
  67687. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  67688. }
  67689. if (!this._meshSpaceDirection) {
  67690. this._meshSpaceDirection = meshSpaceDirection.clone();
  67691. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  67692. }
  67693. else {
  67694. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  67695. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  67696. }
  67697. if (!this._updateToMeshFunction) {
  67698. this._updateToMeshFunction = this._updateToMesh.bind(this);
  67699. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  67700. }
  67701. this._updateToMesh();
  67702. };
  67703. RayHelper.prototype.detachFromMesh = function () {
  67704. if (this._attachedToMesh) {
  67705. if (this._updateToMeshFunction) {
  67706. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  67707. }
  67708. this._attachedToMesh = null;
  67709. this._updateToMeshFunction = null;
  67710. }
  67711. };
  67712. RayHelper.prototype._updateToMesh = function () {
  67713. var ray = this.ray;
  67714. if (!this._attachedToMesh || !ray) {
  67715. return;
  67716. }
  67717. if (this._attachedToMesh._isDisposed) {
  67718. this.detachFromMesh();
  67719. return;
  67720. }
  67721. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  67722. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  67723. };
  67724. RayHelper.prototype.dispose = function () {
  67725. this.hide();
  67726. this.detachFromMesh();
  67727. this.ray = null;
  67728. };
  67729. return RayHelper;
  67730. }());
  67731. BABYLON.RayHelper = RayHelper;
  67732. })(BABYLON || (BABYLON = {}));
  67733. //# sourceMappingURL=babylon.rayHelper.js.map
  67734. var BABYLON;
  67735. (function (BABYLON) {
  67736. var DebugLayer = /** @class */ (function () {
  67737. function DebugLayer(scene) {
  67738. this._scene = scene;
  67739. }
  67740. /** Creates the inspector window. */
  67741. DebugLayer.prototype._createInspector = function (config) {
  67742. if (config === void 0) { config = {}; }
  67743. var popup = config.popup || false;
  67744. var initialTab = config.initialTab || 0;
  67745. var parentElement = config.parentElement || null;
  67746. if (!this._inspector) {
  67747. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  67748. } // else nothing to do,; instance is already existing
  67749. };
  67750. DebugLayer.prototype.isVisible = function () {
  67751. if (!this._inspector) {
  67752. return false;
  67753. }
  67754. return true;
  67755. };
  67756. DebugLayer.prototype.hide = function () {
  67757. if (this._inspector) {
  67758. try {
  67759. this._inspector.dispose();
  67760. }
  67761. catch (e) {
  67762. // If the inspector has been removed directly from the inspector tool
  67763. }
  67764. this._inspector = null;
  67765. }
  67766. };
  67767. DebugLayer.prototype.show = function (config) {
  67768. if (config === void 0) { config = {}; }
  67769. if (typeof INSPECTOR == 'undefined') {
  67770. // Load inspector and add it to the DOM
  67771. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  67772. }
  67773. else {
  67774. // Otherwise creates the inspector
  67775. this._createInspector(config);
  67776. }
  67777. };
  67778. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  67779. return DebugLayer;
  67780. }());
  67781. BABYLON.DebugLayer = DebugLayer;
  67782. })(BABYLON || (BABYLON = {}));
  67783. //# sourceMappingURL=babylon.debugLayer.js.map
  67784. var BABYLON;
  67785. (function (BABYLON) {
  67786. var Debug;
  67787. (function (Debug) {
  67788. var PhysicsViewer = /** @class */ (function () {
  67789. function PhysicsViewer(scene) {
  67790. this._impostors = [];
  67791. this._meshes = [];
  67792. this._numMeshes = 0;
  67793. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67794. var physicEngine = this._scene.getPhysicsEngine();
  67795. if (physicEngine) {
  67796. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  67797. }
  67798. }
  67799. PhysicsViewer.prototype._updateDebugMeshes = function () {
  67800. var plugin = this._physicsEnginePlugin;
  67801. for (var i = 0; i < this._numMeshes; i++) {
  67802. var impostor = this._impostors[i];
  67803. if (!impostor) {
  67804. continue;
  67805. }
  67806. if (impostor.isDisposed) {
  67807. this.hideImpostor(this._impostors[i--]);
  67808. }
  67809. else {
  67810. var mesh = this._meshes[i];
  67811. if (mesh && plugin) {
  67812. plugin.syncMeshWithImpostor(mesh, impostor);
  67813. }
  67814. }
  67815. }
  67816. };
  67817. PhysicsViewer.prototype.showImpostor = function (impostor) {
  67818. if (!this._scene) {
  67819. return;
  67820. }
  67821. for (var i = 0; i < this._numMeshes; i++) {
  67822. if (this._impostors[i] == impostor) {
  67823. return;
  67824. }
  67825. }
  67826. var debugMesh = this._getDebugMesh(impostor, this._scene);
  67827. if (debugMesh) {
  67828. this._impostors[this._numMeshes] = impostor;
  67829. this._meshes[this._numMeshes] = debugMesh;
  67830. if (this._numMeshes === 0) {
  67831. this._renderFunction = this._updateDebugMeshes.bind(this);
  67832. this._scene.registerBeforeRender(this._renderFunction);
  67833. }
  67834. this._numMeshes++;
  67835. }
  67836. };
  67837. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  67838. if (!impostor || !this._scene) {
  67839. return;
  67840. }
  67841. var removed = false;
  67842. for (var i = 0; i < this._numMeshes; i++) {
  67843. if (this._impostors[i] == impostor) {
  67844. var mesh = this._meshes[i];
  67845. if (!mesh) {
  67846. continue;
  67847. }
  67848. this._scene.removeMesh(mesh);
  67849. mesh.dispose();
  67850. this._numMeshes--;
  67851. if (this._numMeshes > 0) {
  67852. this._meshes[i] = this._meshes[this._numMeshes];
  67853. this._impostors[i] = this._impostors[this._numMeshes];
  67854. this._meshes[this._numMeshes] = null;
  67855. this._impostors[this._numMeshes] = null;
  67856. }
  67857. else {
  67858. this._meshes[0] = null;
  67859. this._impostors[0] = null;
  67860. }
  67861. removed = true;
  67862. break;
  67863. }
  67864. }
  67865. if (removed && this._numMeshes === 0) {
  67866. this._scene.unregisterBeforeRender(this._renderFunction);
  67867. }
  67868. };
  67869. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  67870. if (!this._debugMaterial) {
  67871. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  67872. this._debugMaterial.wireframe = true;
  67873. }
  67874. return this._debugMaterial;
  67875. };
  67876. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  67877. if (!this._debugBoxMesh) {
  67878. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  67879. this._debugBoxMesh.renderingGroupId = 1;
  67880. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67881. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  67882. scene.removeMesh(this._debugBoxMesh);
  67883. }
  67884. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  67885. };
  67886. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  67887. if (!this._debugSphereMesh) {
  67888. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  67889. this._debugSphereMesh.renderingGroupId = 1;
  67890. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67891. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  67892. scene.removeMesh(this._debugSphereMesh);
  67893. }
  67894. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  67895. };
  67896. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  67897. var mesh = null;
  67898. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  67899. mesh = this._getDebugBoxMesh(scene);
  67900. impostor.getBoxSizeToRef(mesh.scaling);
  67901. }
  67902. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  67903. mesh = this._getDebugSphereMesh(scene);
  67904. var radius = impostor.getRadius();
  67905. mesh.scaling.x = radius * 2;
  67906. mesh.scaling.y = radius * 2;
  67907. mesh.scaling.z = radius * 2;
  67908. }
  67909. return mesh;
  67910. };
  67911. PhysicsViewer.prototype.dispose = function () {
  67912. for (var i = 0; i < this._numMeshes; i++) {
  67913. this.hideImpostor(this._impostors[i]);
  67914. }
  67915. if (this._debugBoxMesh) {
  67916. this._debugBoxMesh.dispose();
  67917. }
  67918. if (this._debugSphereMesh) {
  67919. this._debugSphereMesh.dispose();
  67920. }
  67921. if (this._debugMaterial) {
  67922. this._debugMaterial.dispose();
  67923. }
  67924. this._impostors.length = 0;
  67925. this._scene = null;
  67926. this._physicsEnginePlugin = null;
  67927. };
  67928. return PhysicsViewer;
  67929. }());
  67930. Debug.PhysicsViewer = PhysicsViewer;
  67931. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67932. })(BABYLON || (BABYLON = {}));
  67933. //# sourceMappingURL=babylon.physicsViewer.js.map
  67934. var BABYLON;
  67935. (function (BABYLON) {
  67936. var BoundingBoxRenderer = /** @class */ (function () {
  67937. function BoundingBoxRenderer(scene) {
  67938. this.frontColor = new BABYLON.Color3(1, 1, 1);
  67939. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  67940. this.showBackLines = true;
  67941. this.renderList = new BABYLON.SmartArray(32);
  67942. this._vertexBuffers = {};
  67943. this._scene = scene;
  67944. }
  67945. BoundingBoxRenderer.prototype._prepareRessources = function () {
  67946. if (this._colorShader) {
  67947. return;
  67948. }
  67949. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  67950. attributes: [BABYLON.VertexBuffer.PositionKind],
  67951. uniforms: ["world", "viewProjection", "color"]
  67952. });
  67953. var engine = this._scene.getEngine();
  67954. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  67955. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  67956. this._createIndexBuffer();
  67957. };
  67958. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  67959. var engine = this._scene.getEngine();
  67960. 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]);
  67961. };
  67962. BoundingBoxRenderer.prototype._rebuild = function () {
  67963. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67964. if (vb) {
  67965. vb._rebuild();
  67966. }
  67967. this._createIndexBuffer();
  67968. };
  67969. BoundingBoxRenderer.prototype.reset = function () {
  67970. this.renderList.reset();
  67971. };
  67972. BoundingBoxRenderer.prototype.render = function () {
  67973. if (this.renderList.length === 0) {
  67974. return;
  67975. }
  67976. this._prepareRessources();
  67977. if (!this._colorShader.isReady()) {
  67978. return;
  67979. }
  67980. var engine = this._scene.getEngine();
  67981. engine.setDepthWrite(false);
  67982. this._colorShader._preBind();
  67983. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  67984. var boundingBox = this.renderList.data[boundingBoxIndex];
  67985. var min = boundingBox.minimum;
  67986. var max = boundingBox.maximum;
  67987. var diff = max.subtract(min);
  67988. var median = min.add(diff.scale(0.5));
  67989. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  67990. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  67991. .multiply(boundingBox.getWorldMatrix());
  67992. // VBOs
  67993. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  67994. if (this.showBackLines) {
  67995. // Back
  67996. engine.setDepthFunctionToGreaterOrEqual();
  67997. this._scene.resetCachedMaterial();
  67998. this._colorShader.setColor4("color", this.backColor.toColor4());
  67999. this._colorShader.bind(worldMatrix);
  68000. // Draw order
  68001. engine.draw(false, 0, 24);
  68002. }
  68003. // Front
  68004. engine.setDepthFunctionToLess();
  68005. this._scene.resetCachedMaterial();
  68006. this._colorShader.setColor4("color", this.frontColor.toColor4());
  68007. this._colorShader.bind(worldMatrix);
  68008. // Draw order
  68009. engine.draw(false, 0, 24);
  68010. }
  68011. this._colorShader.unbind();
  68012. engine.setDepthFunctionToLessOrEqual();
  68013. engine.setDepthWrite(true);
  68014. };
  68015. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68016. this._prepareRessources();
  68017. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68018. return;
  68019. }
  68020. var engine = this._scene.getEngine();
  68021. engine.setDepthWrite(false);
  68022. engine.setColorWrite(false);
  68023. this._colorShader._preBind();
  68024. var boundingBox = mesh._boundingInfo.boundingBox;
  68025. var min = boundingBox.minimum;
  68026. var max = boundingBox.maximum;
  68027. var diff = max.subtract(min);
  68028. var median = min.add(diff.scale(0.5));
  68029. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68030. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68031. .multiply(boundingBox.getWorldMatrix());
  68032. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68033. engine.setDepthFunctionToLess();
  68034. this._scene.resetCachedMaterial();
  68035. this._colorShader.bind(worldMatrix);
  68036. engine.draw(false, 0, 24);
  68037. this._colorShader.unbind();
  68038. engine.setDepthFunctionToLessOrEqual();
  68039. engine.setDepthWrite(true);
  68040. engine.setColorWrite(true);
  68041. };
  68042. BoundingBoxRenderer.prototype.dispose = function () {
  68043. if (!this._colorShader) {
  68044. return;
  68045. }
  68046. this.renderList.dispose();
  68047. this._colorShader.dispose();
  68048. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68049. if (buffer) {
  68050. buffer.dispose();
  68051. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68052. }
  68053. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68054. };
  68055. return BoundingBoxRenderer;
  68056. }());
  68057. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  68058. })(BABYLON || (BABYLON = {}));
  68059. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  68060. var BABYLON;
  68061. (function (BABYLON) {
  68062. var MorphTarget = /** @class */ (function () {
  68063. function MorphTarget(name, influence) {
  68064. if (influence === void 0) { influence = 0; }
  68065. this.name = name;
  68066. this.animations = new Array();
  68067. this.onInfluenceChanged = new BABYLON.Observable();
  68068. this.influence = influence;
  68069. }
  68070. Object.defineProperty(MorphTarget.prototype, "influence", {
  68071. get: function () {
  68072. return this._influence;
  68073. },
  68074. set: function (influence) {
  68075. if (this._influence === influence) {
  68076. return;
  68077. }
  68078. var previous = this._influence;
  68079. this._influence = influence;
  68080. if (this.onInfluenceChanged.hasObservers) {
  68081. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  68082. }
  68083. },
  68084. enumerable: true,
  68085. configurable: true
  68086. });
  68087. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  68088. get: function () {
  68089. return this._normals !== undefined;
  68090. },
  68091. enumerable: true,
  68092. configurable: true
  68093. });
  68094. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  68095. get: function () {
  68096. return this._tangents !== undefined;
  68097. },
  68098. enumerable: true,
  68099. configurable: true
  68100. });
  68101. MorphTarget.prototype.setPositions = function (data) {
  68102. this._positions = new Float32Array(data);
  68103. };
  68104. MorphTarget.prototype.getPositions = function () {
  68105. return this._positions;
  68106. };
  68107. MorphTarget.prototype.setNormals = function (data) {
  68108. this._normals = new Float32Array(data);
  68109. };
  68110. MorphTarget.prototype.getNormals = function () {
  68111. return this._normals;
  68112. };
  68113. MorphTarget.prototype.setTangents = function (data) {
  68114. this._tangents = new Float32Array(data);
  68115. };
  68116. MorphTarget.prototype.getTangents = function () {
  68117. return this._tangents;
  68118. };
  68119. /**
  68120. * Serializes the current target into a Serialization object.
  68121. * Returns the serialized object.
  68122. */
  68123. MorphTarget.prototype.serialize = function () {
  68124. var serializationObject = {};
  68125. serializationObject.name = this.name;
  68126. serializationObject.influence = this.influence;
  68127. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  68128. if (this.hasNormals) {
  68129. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  68130. }
  68131. if (this.hasTangents) {
  68132. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  68133. }
  68134. // Animations
  68135. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  68136. return serializationObject;
  68137. };
  68138. // Statics
  68139. MorphTarget.Parse = function (serializationObject) {
  68140. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  68141. result.setPositions(serializationObject.positions);
  68142. if (serializationObject.normals) {
  68143. result.setNormals(serializationObject.normals);
  68144. }
  68145. if (serializationObject.tangents) {
  68146. result.setTangents(serializationObject.tangents);
  68147. }
  68148. // Animations
  68149. if (serializationObject.animations) {
  68150. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  68151. var parsedAnimation = serializationObject.animations[animationIndex];
  68152. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68153. }
  68154. }
  68155. return result;
  68156. };
  68157. MorphTarget.FromMesh = function (mesh, name, influence) {
  68158. if (!name) {
  68159. name = mesh.name;
  68160. }
  68161. var result = new MorphTarget(name, influence);
  68162. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68163. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68164. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  68165. }
  68166. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  68167. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  68168. }
  68169. return result;
  68170. };
  68171. return MorphTarget;
  68172. }());
  68173. BABYLON.MorphTarget = MorphTarget;
  68174. })(BABYLON || (BABYLON = {}));
  68175. //# sourceMappingURL=babylon.morphTarget.js.map
  68176. var BABYLON;
  68177. (function (BABYLON) {
  68178. var MorphTargetManager = /** @class */ (function () {
  68179. function MorphTargetManager(scene) {
  68180. if (scene === void 0) { scene = null; }
  68181. this._targets = new Array();
  68182. this._targetObservable = new Array();
  68183. this._activeTargets = new BABYLON.SmartArray(16);
  68184. this._supportsNormals = false;
  68185. this._supportsTangents = false;
  68186. this._vertexCount = 0;
  68187. this._uniqueId = 0;
  68188. this._tempInfluences = new Array();
  68189. if (!scene) {
  68190. scene = BABYLON.Engine.LastCreatedScene;
  68191. }
  68192. this._scene = scene;
  68193. if (this._scene) {
  68194. this._scene.morphTargetManagers.push(this);
  68195. this._uniqueId = this._scene.getUniqueId();
  68196. }
  68197. }
  68198. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  68199. get: function () {
  68200. return this._uniqueId;
  68201. },
  68202. enumerable: true,
  68203. configurable: true
  68204. });
  68205. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  68206. get: function () {
  68207. return this._vertexCount;
  68208. },
  68209. enumerable: true,
  68210. configurable: true
  68211. });
  68212. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  68213. get: function () {
  68214. return this._supportsNormals;
  68215. },
  68216. enumerable: true,
  68217. configurable: true
  68218. });
  68219. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  68220. get: function () {
  68221. return this._supportsTangents;
  68222. },
  68223. enumerable: true,
  68224. configurable: true
  68225. });
  68226. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  68227. get: function () {
  68228. return this._targets.length;
  68229. },
  68230. enumerable: true,
  68231. configurable: true
  68232. });
  68233. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  68234. get: function () {
  68235. return this._activeTargets.length;
  68236. },
  68237. enumerable: true,
  68238. configurable: true
  68239. });
  68240. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  68241. get: function () {
  68242. return this._influences;
  68243. },
  68244. enumerable: true,
  68245. configurable: true
  68246. });
  68247. MorphTargetManager.prototype.getActiveTarget = function (index) {
  68248. return this._activeTargets.data[index];
  68249. };
  68250. MorphTargetManager.prototype.getTarget = function (index) {
  68251. return this._targets[index];
  68252. };
  68253. MorphTargetManager.prototype.addTarget = function (target) {
  68254. var _this = this;
  68255. if (this._vertexCount) {
  68256. if (this._vertexCount !== target.getPositions().length / 3) {
  68257. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  68258. return;
  68259. }
  68260. }
  68261. this._targets.push(target);
  68262. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  68263. _this._syncActiveTargets(needUpdate);
  68264. }));
  68265. this._syncActiveTargets(true);
  68266. };
  68267. MorphTargetManager.prototype.removeTarget = function (target) {
  68268. var index = this._targets.indexOf(target);
  68269. if (index >= 0) {
  68270. this._targets.splice(index, 1);
  68271. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  68272. this._vertexCount = 0;
  68273. this._syncActiveTargets(true);
  68274. }
  68275. };
  68276. /**
  68277. * Serializes the current manager into a Serialization object.
  68278. * Returns the serialized object.
  68279. */
  68280. MorphTargetManager.prototype.serialize = function () {
  68281. var serializationObject = {};
  68282. serializationObject.id = this.uniqueId;
  68283. serializationObject.targets = [];
  68284. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68285. var target = _a[_i];
  68286. serializationObject.targets.push(target.serialize());
  68287. }
  68288. return serializationObject;
  68289. };
  68290. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  68291. var influenceCount = 0;
  68292. this._activeTargets.reset();
  68293. this._supportsNormals = true;
  68294. this._supportsTangents = true;
  68295. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68296. var target = _a[_i];
  68297. if (target.influence > 0) {
  68298. this._activeTargets.push(target);
  68299. this._tempInfluences[influenceCount++] = target.influence;
  68300. this._supportsNormals = this._supportsNormals && target.hasNormals;
  68301. this._supportsTangents = this._supportsTangents && target.hasTangents;
  68302. if (this._vertexCount === 0) {
  68303. this._vertexCount = target.getPositions().length / 3;
  68304. }
  68305. }
  68306. }
  68307. if (!this._influences || this._influences.length !== influenceCount) {
  68308. this._influences = new Float32Array(influenceCount);
  68309. }
  68310. for (var index = 0; index < influenceCount; index++) {
  68311. this._influences[index] = this._tempInfluences[index];
  68312. }
  68313. if (needUpdate && this._scene) {
  68314. // Flag meshes as dirty to resync with the active targets
  68315. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  68316. var mesh = _c[_b];
  68317. if (mesh.morphTargetManager === this) {
  68318. mesh._syncGeometryWithMorphTargetManager();
  68319. }
  68320. }
  68321. }
  68322. };
  68323. // Statics
  68324. MorphTargetManager.Parse = function (serializationObject, scene) {
  68325. var result = new MorphTargetManager(scene);
  68326. result._uniqueId = serializationObject.id;
  68327. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  68328. var targetData = _a[_i];
  68329. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  68330. }
  68331. return result;
  68332. };
  68333. return MorphTargetManager;
  68334. }());
  68335. BABYLON.MorphTargetManager = MorphTargetManager;
  68336. })(BABYLON || (BABYLON = {}));
  68337. //# sourceMappingURL=babylon.morphTargetManager.js.map
  68338. var BABYLON;
  68339. (function (BABYLON) {
  68340. var Octree = /** @class */ (function () {
  68341. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  68342. if (maxDepth === void 0) { maxDepth = 2; }
  68343. this.maxDepth = maxDepth;
  68344. this.dynamicContent = new Array();
  68345. this._maxBlockCapacity = maxBlockCapacity || 64;
  68346. this._selectionContent = new BABYLON.SmartArray(1024);
  68347. this._creationFunc = creationFunc;
  68348. }
  68349. // Methods
  68350. Octree.prototype.update = function (worldMin, worldMax, entries) {
  68351. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  68352. };
  68353. Octree.prototype.addMesh = function (entry) {
  68354. for (var index = 0; index < this.blocks.length; index++) {
  68355. var block = this.blocks[index];
  68356. block.addEntry(entry);
  68357. }
  68358. };
  68359. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  68360. this._selectionContent.reset();
  68361. for (var index = 0; index < this.blocks.length; index++) {
  68362. var block = this.blocks[index];
  68363. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  68364. }
  68365. if (allowDuplicate) {
  68366. this._selectionContent.concat(this.dynamicContent);
  68367. }
  68368. else {
  68369. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68370. }
  68371. return this._selectionContent;
  68372. };
  68373. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  68374. this._selectionContent.reset();
  68375. for (var index = 0; index < this.blocks.length; index++) {
  68376. var block = this.blocks[index];
  68377. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  68378. }
  68379. if (allowDuplicate) {
  68380. this._selectionContent.concat(this.dynamicContent);
  68381. }
  68382. else {
  68383. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68384. }
  68385. return this._selectionContent;
  68386. };
  68387. Octree.prototype.intersectsRay = function (ray) {
  68388. this._selectionContent.reset();
  68389. for (var index = 0; index < this.blocks.length; index++) {
  68390. var block = this.blocks[index];
  68391. block.intersectsRay(ray, this._selectionContent);
  68392. }
  68393. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68394. return this._selectionContent;
  68395. };
  68396. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  68397. target.blocks = new Array();
  68398. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  68399. // Segmenting space
  68400. for (var x = 0; x < 2; x++) {
  68401. for (var y = 0; y < 2; y++) {
  68402. for (var z = 0; z < 2; z++) {
  68403. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  68404. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  68405. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  68406. block.addEntries(entries);
  68407. target.blocks.push(block);
  68408. }
  68409. }
  68410. }
  68411. };
  68412. Octree.CreationFuncForMeshes = function (entry, block) {
  68413. var boundingInfo = entry.getBoundingInfo();
  68414. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68415. block.entries.push(entry);
  68416. }
  68417. };
  68418. Octree.CreationFuncForSubMeshes = function (entry, block) {
  68419. var boundingInfo = entry.getBoundingInfo();
  68420. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68421. block.entries.push(entry);
  68422. }
  68423. };
  68424. return Octree;
  68425. }());
  68426. BABYLON.Octree = Octree;
  68427. })(BABYLON || (BABYLON = {}));
  68428. //# sourceMappingURL=babylon.octree.js.map
  68429. var BABYLON;
  68430. (function (BABYLON) {
  68431. var OctreeBlock = /** @class */ (function () {
  68432. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  68433. this.entries = new Array();
  68434. this._boundingVectors = new Array();
  68435. this._capacity = capacity;
  68436. this._depth = depth;
  68437. this._maxDepth = maxDepth;
  68438. this._creationFunc = creationFunc;
  68439. this._minPoint = minPoint;
  68440. this._maxPoint = maxPoint;
  68441. this._boundingVectors.push(minPoint.clone());
  68442. this._boundingVectors.push(maxPoint.clone());
  68443. this._boundingVectors.push(minPoint.clone());
  68444. this._boundingVectors[2].x = maxPoint.x;
  68445. this._boundingVectors.push(minPoint.clone());
  68446. this._boundingVectors[3].y = maxPoint.y;
  68447. this._boundingVectors.push(minPoint.clone());
  68448. this._boundingVectors[4].z = maxPoint.z;
  68449. this._boundingVectors.push(maxPoint.clone());
  68450. this._boundingVectors[5].z = minPoint.z;
  68451. this._boundingVectors.push(maxPoint.clone());
  68452. this._boundingVectors[6].x = minPoint.x;
  68453. this._boundingVectors.push(maxPoint.clone());
  68454. this._boundingVectors[7].y = minPoint.y;
  68455. }
  68456. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  68457. // Property
  68458. get: function () {
  68459. return this._capacity;
  68460. },
  68461. enumerable: true,
  68462. configurable: true
  68463. });
  68464. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  68465. get: function () {
  68466. return this._minPoint;
  68467. },
  68468. enumerable: true,
  68469. configurable: true
  68470. });
  68471. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  68472. get: function () {
  68473. return this._maxPoint;
  68474. },
  68475. enumerable: true,
  68476. configurable: true
  68477. });
  68478. // Methods
  68479. OctreeBlock.prototype.addEntry = function (entry) {
  68480. if (this.blocks) {
  68481. for (var index = 0; index < this.blocks.length; index++) {
  68482. var block = this.blocks[index];
  68483. block.addEntry(entry);
  68484. }
  68485. return;
  68486. }
  68487. this._creationFunc(entry, this);
  68488. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  68489. this.createInnerBlocks();
  68490. }
  68491. };
  68492. OctreeBlock.prototype.addEntries = function (entries) {
  68493. for (var index = 0; index < entries.length; index++) {
  68494. var mesh = entries[index];
  68495. this.addEntry(mesh);
  68496. }
  68497. };
  68498. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  68499. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  68500. if (this.blocks) {
  68501. for (var index = 0; index < this.blocks.length; index++) {
  68502. var block = this.blocks[index];
  68503. block.select(frustumPlanes, selection, allowDuplicate);
  68504. }
  68505. return;
  68506. }
  68507. if (allowDuplicate) {
  68508. selection.concat(this.entries);
  68509. }
  68510. else {
  68511. selection.concatWithNoDuplicate(this.entries);
  68512. }
  68513. }
  68514. };
  68515. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  68516. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  68517. if (this.blocks) {
  68518. for (var index = 0; index < this.blocks.length; index++) {
  68519. var block = this.blocks[index];
  68520. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  68521. }
  68522. return;
  68523. }
  68524. if (allowDuplicate) {
  68525. selection.concat(this.entries);
  68526. }
  68527. else {
  68528. selection.concatWithNoDuplicate(this.entries);
  68529. }
  68530. }
  68531. };
  68532. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  68533. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  68534. if (this.blocks) {
  68535. for (var index = 0; index < this.blocks.length; index++) {
  68536. var block = this.blocks[index];
  68537. block.intersectsRay(ray, selection);
  68538. }
  68539. return;
  68540. }
  68541. selection.concatWithNoDuplicate(this.entries);
  68542. }
  68543. };
  68544. OctreeBlock.prototype.createInnerBlocks = function () {
  68545. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  68546. };
  68547. return OctreeBlock;
  68548. }());
  68549. BABYLON.OctreeBlock = OctreeBlock;
  68550. })(BABYLON || (BABYLON = {}));
  68551. //# sourceMappingURL=babylon.octreeBlock.js.map
  68552. var BABYLON;
  68553. (function (BABYLON) {
  68554. var SIMDVector3 = /** @class */ (function () {
  68555. function SIMDVector3() {
  68556. }
  68557. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  68558. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  68559. };
  68560. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  68561. var m = transformation.m;
  68562. var m0 = SIMD.Float32x4.load(m, 0);
  68563. var m1 = SIMD.Float32x4.load(m, 4);
  68564. var m2 = SIMD.Float32x4.load(m, 8);
  68565. var m3 = SIMD.Float32x4.load(m, 12);
  68566. 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));
  68567. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  68568. result.x = SIMD.Float32x4.extractLane(r, 0);
  68569. result.y = SIMD.Float32x4.extractLane(r, 1);
  68570. result.z = SIMD.Float32x4.extractLane(r, 2);
  68571. };
  68572. return SIMDVector3;
  68573. }());
  68574. var SIMDMatrix = /** @class */ (function () {
  68575. function SIMDMatrix() {
  68576. }
  68577. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  68578. var tm = this.m;
  68579. var om = other.m;
  68580. var m0 = SIMD.Float32x4.load(om, 0);
  68581. var m1 = SIMD.Float32x4.load(om, 4);
  68582. var m2 = SIMD.Float32x4.load(om, 8);
  68583. var m3 = SIMD.Float32x4.load(om, 12);
  68584. for (var i = 0; i < 16; i += 4) {
  68585. 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)))));
  68586. }
  68587. return this;
  68588. };
  68589. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  68590. var src = this.m;
  68591. var dest = other.m;
  68592. // Load the 4 rows
  68593. var src0 = SIMD.Float32x4.load(src, 0);
  68594. var src1 = SIMD.Float32x4.load(src, 4);
  68595. var src2 = SIMD.Float32x4.load(src, 8);
  68596. var src3 = SIMD.Float32x4.load(src, 12);
  68597. // Transpose the source matrix. Sort of. Not a true transpose operation
  68598. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  68599. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  68600. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  68601. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  68602. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  68603. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  68604. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  68605. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  68606. // This is a true transposition, but it will lead to an incorrect result
  68607. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  68608. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  68609. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68610. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68611. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  68612. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  68613. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68614. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68615. // ----
  68616. tmp1 = SIMD.Float32x4.mul(row2, row3);
  68617. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68618. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  68619. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  68620. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68621. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  68622. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  68623. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  68624. // ----
  68625. tmp1 = SIMD.Float32x4.mul(row1, row2);
  68626. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68627. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  68628. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  68629. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68630. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  68631. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  68632. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  68633. // ----
  68634. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  68635. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68636. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  68637. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  68638. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  68639. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68640. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  68641. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  68642. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  68643. // ----
  68644. tmp1 = SIMD.Float32x4.mul(row0, row1);
  68645. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68646. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68647. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  68648. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68649. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68650. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  68651. // ----
  68652. tmp1 = SIMD.Float32x4.mul(row0, row3);
  68653. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68654. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  68655. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  68656. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68657. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  68658. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  68659. // ----
  68660. tmp1 = SIMD.Float32x4.mul(row0, row2);
  68661. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68662. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  68663. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  68664. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68665. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  68666. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  68667. // Compute determinant
  68668. var det = SIMD.Float32x4.mul(row0, minor0);
  68669. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  68670. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  68671. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  68672. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  68673. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  68674. // These shuffles aren't necessary if the faulty transposition is done
  68675. // up at the top of this function.
  68676. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  68677. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  68678. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  68679. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  68680. // Compute final values by multiplying with 1/det
  68681. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  68682. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  68683. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  68684. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  68685. return this;
  68686. };
  68687. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  68688. var out = result.m;
  68689. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  68690. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  68691. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  68692. // cc.kmVec3Subtract(f, pCenter, pEye);
  68693. var f = SIMD.Float32x4.sub(center, eye);
  68694. // cc.kmVec3Normalize(f, f);
  68695. var tmp = SIMD.Float32x4.mul(f, f);
  68696. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68697. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68698. // cc.kmVec3Assign(up, pUp);
  68699. // cc.kmVec3Normalize(up, up);
  68700. tmp = SIMD.Float32x4.mul(up, up);
  68701. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68702. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68703. // cc.kmVec3Cross(s, f, up);
  68704. 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)));
  68705. // cc.kmVec3Normalize(s, s);
  68706. tmp = SIMD.Float32x4.mul(s, s);
  68707. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68708. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68709. // cc.kmVec3Cross(u, s, f);
  68710. 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)));
  68711. // cc.kmVec3Normalize(s, s);
  68712. tmp = SIMD.Float32x4.mul(s, s);
  68713. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68714. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68715. var zero = SIMD.Float32x4.splat(0.0);
  68716. s = SIMD.Float32x4.neg(s);
  68717. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  68718. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  68719. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  68720. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  68721. 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);
  68722. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  68723. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  68724. 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)))));
  68725. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  68726. 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)))));
  68727. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  68728. 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)))));
  68729. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  68730. 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)))));
  68731. };
  68732. return SIMDMatrix;
  68733. }());
  68734. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  68735. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  68736. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  68737. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  68738. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  68739. var SIMDHelper = /** @class */ (function () {
  68740. function SIMDHelper() {
  68741. }
  68742. Object.defineProperty(SIMDHelper, "IsEnabled", {
  68743. get: function () {
  68744. return SIMDHelper._isEnabled;
  68745. },
  68746. enumerable: true,
  68747. configurable: true
  68748. });
  68749. SIMDHelper.DisableSIMD = function () {
  68750. // Replace functions
  68751. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  68752. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  68753. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  68754. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  68755. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  68756. SIMDHelper._isEnabled = false;
  68757. };
  68758. SIMDHelper.EnableSIMD = function () {
  68759. if (self.SIMD === undefined) {
  68760. return;
  68761. }
  68762. // check if polyfills needed
  68763. if (!self.Math.fround) {
  68764. self.Math.fround = (function (array) { return function (x) {
  68765. return array[0] = x, array[0];
  68766. }; })(new Float32Array(1));
  68767. }
  68768. if (!self.Math.imul) {
  68769. self.Math.imul = function (a, b) {
  68770. var ah = (a >>> 16) & 0xffff;
  68771. var al = a & 0xffff;
  68772. var bh = (b >>> 16) & 0xffff;
  68773. var bl = b & 0xffff;
  68774. // the shift by 0 fixes the sign on the high part
  68775. // the final |0 converts the unsigned value into a signed value
  68776. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  68777. };
  68778. }
  68779. // Replace functions
  68780. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  68781. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  68782. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  68783. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  68784. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  68785. SIMDHelper._isEnabled = true;
  68786. };
  68787. SIMDHelper._isEnabled = false;
  68788. return SIMDHelper;
  68789. }());
  68790. BABYLON.SIMDHelper = SIMDHelper;
  68791. })(BABYLON || (BABYLON = {}));
  68792. //# sourceMappingURL=babylon.math.SIMD.js.map
  68793. var BABYLON;
  68794. (function (BABYLON) {
  68795. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  68796. __extends(VRDistortionCorrectionPostProcess, _super);
  68797. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  68798. var _this = _super.call(this, name, "vrDistortionCorrection", [
  68799. 'LensCenter',
  68800. 'Scale',
  68801. 'ScaleIn',
  68802. 'HmdWarpParam'
  68803. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  68804. _this._isRightEye = isRightEye;
  68805. _this._distortionFactors = vrMetrics.distortionK;
  68806. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  68807. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  68808. _this.adaptScaleToCurrentViewport = true;
  68809. _this.onSizeChangedObservable.add(function () {
  68810. _this.aspectRatio = _this.width * .5 / _this.height;
  68811. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  68812. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  68813. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  68814. });
  68815. _this.onApplyObservable.add(function (effect) {
  68816. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  68817. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  68818. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  68819. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  68820. });
  68821. return _this;
  68822. }
  68823. return VRDistortionCorrectionPostProcess;
  68824. }(BABYLON.PostProcess));
  68825. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  68826. })(BABYLON || (BABYLON = {}));
  68827. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  68828. var BABYLON;
  68829. (function (BABYLON) {
  68830. var AnaglyphPostProcess = /** @class */ (function (_super) {
  68831. __extends(AnaglyphPostProcess, _super);
  68832. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  68833. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  68834. _this._passedProcess = rigCameras[0]._rigPostProcess;
  68835. _this.onApplyObservable.add(function (effect) {
  68836. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  68837. });
  68838. return _this;
  68839. }
  68840. return AnaglyphPostProcess;
  68841. }(BABYLON.PostProcess));
  68842. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  68843. })(BABYLON || (BABYLON = {}));
  68844. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  68845. var BABYLON;
  68846. (function (BABYLON) {
  68847. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  68848. __extends(StereoscopicInterlacePostProcess, _super);
  68849. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  68850. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  68851. _this._passedProcess = rigCameras[0]._rigPostProcess;
  68852. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  68853. _this.onSizeChangedObservable.add(function () {
  68854. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  68855. });
  68856. _this.onApplyObservable.add(function (effect) {
  68857. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  68858. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  68859. });
  68860. return _this;
  68861. }
  68862. return StereoscopicInterlacePostProcess;
  68863. }(BABYLON.PostProcess));
  68864. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  68865. })(BABYLON || (BABYLON = {}));
  68866. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  68867. var BABYLON;
  68868. (function (BABYLON) {
  68869. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  68870. function FreeCameraDeviceOrientationInput() {
  68871. var _this = this;
  68872. this._screenOrientationAngle = 0;
  68873. this._screenQuaternion = new BABYLON.Quaternion();
  68874. this._alpha = 0;
  68875. this._beta = 0;
  68876. this._gamma = 0;
  68877. this._orientationChanged = function () {
  68878. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  68879. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  68880. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  68881. };
  68882. this._deviceOrientation = function (evt) {
  68883. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  68884. _this._beta = evt.beta !== null ? evt.beta : 0;
  68885. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  68886. };
  68887. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  68888. this._orientationChanged();
  68889. }
  68890. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  68891. get: function () {
  68892. return this._camera;
  68893. },
  68894. set: function (camera) {
  68895. this._camera = camera;
  68896. if (this._camera != null && !this._camera.rotationQuaternion) {
  68897. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  68898. }
  68899. },
  68900. enumerable: true,
  68901. configurable: true
  68902. });
  68903. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  68904. window.addEventListener("orientationchange", this._orientationChanged);
  68905. window.addEventListener("deviceorientation", this._deviceOrientation);
  68906. //In certain cases, the attach control is called AFTER orientation was changed,
  68907. //So this is needed.
  68908. this._orientationChanged();
  68909. };
  68910. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  68911. window.removeEventListener("orientationchange", this._orientationChanged);
  68912. window.removeEventListener("deviceorientation", this._deviceOrientation);
  68913. };
  68914. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  68915. //if no device orientation provided, don't update the rotation.
  68916. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  68917. if (!this._alpha)
  68918. return;
  68919. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  68920. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  68921. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  68922. //Mirror on XY Plane
  68923. this._camera.rotationQuaternion.z *= -1;
  68924. this._camera.rotationQuaternion.w *= -1;
  68925. };
  68926. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  68927. return "FreeCameraDeviceOrientationInput";
  68928. };
  68929. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  68930. return "deviceOrientation";
  68931. };
  68932. return FreeCameraDeviceOrientationInput;
  68933. }());
  68934. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  68935. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  68936. })(BABYLON || (BABYLON = {}));
  68937. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  68938. var BABYLON;
  68939. (function (BABYLON) {
  68940. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  68941. function ArcRotateCameraVRDeviceOrientationInput() {
  68942. this.alphaCorrection = 1;
  68943. this.betaCorrection = 1;
  68944. this.gammaCorrection = 1;
  68945. this._alpha = 0;
  68946. this._beta = 0;
  68947. this._gamma = 0;
  68948. this._dirty = false;
  68949. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  68950. }
  68951. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  68952. this.camera.attachControl(element, noPreventDefault);
  68953. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  68954. };
  68955. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  68956. if (evt.alpha !== null) {
  68957. this._alpha = +evt.alpha | 0;
  68958. }
  68959. if (evt.beta !== null) {
  68960. this._beta = +evt.beta | 0;
  68961. }
  68962. if (evt.gamma !== null) {
  68963. this._gamma = +evt.gamma | 0;
  68964. }
  68965. this._dirty = true;
  68966. };
  68967. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  68968. if (this._dirty) {
  68969. this._dirty = false;
  68970. if (this._gamma < 0) {
  68971. this._gamma = 180 + this._gamma;
  68972. }
  68973. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  68974. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  68975. }
  68976. };
  68977. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  68978. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  68979. };
  68980. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  68981. return "ArcRotateCameraVRDeviceOrientationInput";
  68982. };
  68983. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  68984. return "VRDeviceOrientation";
  68985. };
  68986. return ArcRotateCameraVRDeviceOrientationInput;
  68987. }());
  68988. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  68989. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  68990. })(BABYLON || (BABYLON = {}));
  68991. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  68992. var BABYLON;
  68993. (function (BABYLON) {
  68994. var VRCameraMetrics = /** @class */ (function () {
  68995. function VRCameraMetrics() {
  68996. this.compensateDistortion = true;
  68997. }
  68998. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  68999. get: function () {
  69000. return this.hResolution / (2 * this.vResolution);
  69001. },
  69002. enumerable: true,
  69003. configurable: true
  69004. });
  69005. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  69006. get: function () {
  69007. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  69008. },
  69009. enumerable: true,
  69010. configurable: true
  69011. });
  69012. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  69013. get: function () {
  69014. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69015. var h = (4 * meters) / this.hScreenSize;
  69016. return BABYLON.Matrix.Translation(h, 0, 0);
  69017. },
  69018. enumerable: true,
  69019. configurable: true
  69020. });
  69021. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  69022. get: function () {
  69023. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69024. var h = (4 * meters) / this.hScreenSize;
  69025. return BABYLON.Matrix.Translation(-h, 0, 0);
  69026. },
  69027. enumerable: true,
  69028. configurable: true
  69029. });
  69030. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  69031. get: function () {
  69032. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  69033. },
  69034. enumerable: true,
  69035. configurable: true
  69036. });
  69037. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  69038. get: function () {
  69039. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  69040. },
  69041. enumerable: true,
  69042. configurable: true
  69043. });
  69044. VRCameraMetrics.GetDefault = function () {
  69045. var result = new VRCameraMetrics();
  69046. result.hResolution = 1280;
  69047. result.vResolution = 800;
  69048. result.hScreenSize = 0.149759993;
  69049. result.vScreenSize = 0.0935999975;
  69050. result.vScreenCenter = 0.0467999987;
  69051. result.eyeToScreenDistance = 0.0410000011;
  69052. result.lensSeparationDistance = 0.0635000020;
  69053. result.interpupillaryDistance = 0.0640000030;
  69054. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  69055. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  69056. result.postProcessScaleFactor = 1.714605507808412;
  69057. result.lensCenterOffset = 0.151976421;
  69058. return result;
  69059. };
  69060. return VRCameraMetrics;
  69061. }());
  69062. BABYLON.VRCameraMetrics = VRCameraMetrics;
  69063. })(BABYLON || (BABYLON = {}));
  69064. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  69065. var BABYLON;
  69066. (function (BABYLON) {
  69067. var WebVRFreeCamera = /** @class */ (function (_super) {
  69068. __extends(WebVRFreeCamera, _super);
  69069. function WebVRFreeCamera(name, position, scene, webVROptions) {
  69070. if (webVROptions === void 0) { webVROptions = {}; }
  69071. var _this = _super.call(this, name, position, scene) || this;
  69072. _this.webVROptions = webVROptions;
  69073. _this._vrDevice = null;
  69074. _this.rawPose = null;
  69075. _this._specsVersion = "1.1";
  69076. _this._attached = false;
  69077. _this._descendants = [];
  69078. _this.devicePosition = BABYLON.Vector3.Zero();
  69079. _this.deviceScaleFactor = 1;
  69080. _this.controllers = [];
  69081. _this.onControllersAttachedObservable = new BABYLON.Observable();
  69082. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  69083. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  69084. _this.minZ = 0.1;
  69085. //legacy support - the compensation boolean was removed.
  69086. if (arguments.length === 5) {
  69087. _this.webVROptions = arguments[4];
  69088. }
  69089. // default webVR options
  69090. if (_this.webVROptions.trackPosition == undefined) {
  69091. _this.webVROptions.trackPosition = true;
  69092. }
  69093. if (_this.webVROptions.controllerMeshes == undefined) {
  69094. _this.webVROptions.controllerMeshes = true;
  69095. }
  69096. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  69097. _this.webVROptions.defaultLightingOnControllers = true;
  69098. }
  69099. _this.rotationQuaternion = new BABYLON.Quaternion();
  69100. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69101. if (_this.webVROptions && _this.webVROptions.positionScale) {
  69102. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  69103. }
  69104. //enable VR
  69105. var engine = _this.getEngine();
  69106. _this._onVREnabled = function (success) { if (success) {
  69107. _this.initControllers();
  69108. } };
  69109. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  69110. engine.initWebVR().add(function (event) {
  69111. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  69112. return;
  69113. }
  69114. _this._vrDevice = event.vrDisplay;
  69115. //reset the rig parameters.
  69116. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  69117. if (_this._attached) {
  69118. _this.getEngine().enableVR();
  69119. }
  69120. });
  69121. if (typeof (VRFrameData) !== "undefined")
  69122. _this._frameData = new VRFrameData();
  69123. /**
  69124. * The idea behind the following lines:
  69125. * objects that have the camera as parent should actually have the rig cameras as a parent.
  69126. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  69127. * the second will not show it correctly.
  69128. *
  69129. * To solve this - each object that has the camera as parent will be added to a protected array.
  69130. * When the rig camera renders, it will take this array and set all of those to be its children.
  69131. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  69132. * Amazing!
  69133. */
  69134. scene.onBeforeCameraRenderObservable.add(function (camera) {
  69135. if (camera.parent === _this && _this.rigParenting) {
  69136. _this._descendants = _this.getDescendants(true, function (n) {
  69137. // don't take the cameras or the controllers!
  69138. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  69139. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  69140. return !isController && !isRigCamera;
  69141. });
  69142. _this._descendants.forEach(function (node) {
  69143. node.parent = camera;
  69144. });
  69145. }
  69146. });
  69147. scene.onAfterCameraRenderObservable.add(function (camera) {
  69148. if (camera.parent === _this && _this.rigParenting) {
  69149. _this._descendants.forEach(function (node) {
  69150. node.parent = _this;
  69151. });
  69152. }
  69153. });
  69154. return _this;
  69155. }
  69156. WebVRFreeCamera.prototype.dispose = function () {
  69157. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  69158. _super.prototype.dispose.call(this);
  69159. };
  69160. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  69161. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  69162. var gp = _a[_i];
  69163. if (gp.hand === name) {
  69164. return gp;
  69165. }
  69166. }
  69167. return null;
  69168. };
  69169. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  69170. get: function () {
  69171. if (!this._leftController) {
  69172. this._leftController = this.getControllerByName("left");
  69173. }
  69174. return this._leftController;
  69175. },
  69176. enumerable: true,
  69177. configurable: true
  69178. });
  69179. ;
  69180. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  69181. get: function () {
  69182. if (!this._rightController) {
  69183. this._rightController = this.getControllerByName("right");
  69184. }
  69185. return this._rightController;
  69186. },
  69187. enumerable: true,
  69188. configurable: true
  69189. });
  69190. ;
  69191. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  69192. if (length === void 0) { length = 100; }
  69193. if (this.leftCamera) {
  69194. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  69195. }
  69196. else {
  69197. return _super.prototype.getForwardRay.call(this, length);
  69198. }
  69199. };
  69200. WebVRFreeCamera.prototype._checkInputs = function () {
  69201. if (this._vrDevice && this._vrDevice.isPresenting) {
  69202. this._vrDevice.getFrameData(this._frameData);
  69203. this.updateFromDevice(this._frameData.pose);
  69204. }
  69205. _super.prototype._checkInputs.call(this);
  69206. };
  69207. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  69208. if (poseData && poseData.orientation) {
  69209. this.rawPose = poseData;
  69210. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  69211. if (this.getScene().useRightHandedSystem) {
  69212. this.deviceRotationQuaternion.z *= -1;
  69213. this.deviceRotationQuaternion.w *= -1;
  69214. }
  69215. if (this.webVROptions.trackPosition && this.rawPose.position) {
  69216. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  69217. if (this.getScene().useRightHandedSystem) {
  69218. this.devicePosition.z *= -1;
  69219. }
  69220. }
  69221. }
  69222. };
  69223. /**
  69224. * WebVR's attach control will start broadcasting frames to the device.
  69225. * Note that in certain browsers (chrome for example) this function must be called
  69226. * within a user-interaction callback. Example:
  69227. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  69228. *
  69229. * @param {HTMLElement} element
  69230. * @param {boolean} [noPreventDefault]
  69231. *
  69232. * @memberOf WebVRFreeCamera
  69233. */
  69234. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  69235. _super.prototype.attachControl.call(this, element, noPreventDefault);
  69236. this._attached = true;
  69237. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  69238. if (this._vrDevice) {
  69239. this.getEngine().enableVR();
  69240. }
  69241. };
  69242. WebVRFreeCamera.prototype.detachControl = function (element) {
  69243. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69244. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69245. _super.prototype.detachControl.call(this, element);
  69246. this._attached = false;
  69247. this.getEngine().disableVR();
  69248. };
  69249. WebVRFreeCamera.prototype.getClassName = function () {
  69250. return "WebVRFreeCamera";
  69251. };
  69252. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  69253. //uses the vrDisplay's "resetPose()".
  69254. //pitch and roll won't be affected.
  69255. this._vrDevice.resetPose();
  69256. };
  69257. WebVRFreeCamera.prototype._updateRigCameras = function () {
  69258. var camLeft = this._rigCameras[0];
  69259. var camRight = this._rigCameras[1];
  69260. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69261. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69262. camLeft.position.copyFrom(this.devicePosition);
  69263. camRight.position.copyFrom(this.devicePosition);
  69264. };
  69265. /**
  69266. * This function is called by the two RIG cameras.
  69267. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  69268. */
  69269. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  69270. var _this = this;
  69271. //WebVR 1.1
  69272. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  69273. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  69274. if (!this.getScene().useRightHandedSystem) {
  69275. [2, 6, 8, 9, 14].forEach(function (num) {
  69276. _this._webvrViewMatrix.m[num] *= -1;
  69277. });
  69278. }
  69279. // update the camera rotation matrix
  69280. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  69281. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  69282. // Computing target and final matrix
  69283. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  69284. var parentCamera = this._cameraRigParams["parentCamera"];
  69285. // should the view matrix be updated with scale and position offset?
  69286. if (parentCamera.deviceScaleFactor !== 1) {
  69287. this._webvrViewMatrix.invert();
  69288. // scale the position, if set
  69289. if (parentCamera.deviceScaleFactor) {
  69290. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  69291. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  69292. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  69293. }
  69294. this._webvrViewMatrix.invert();
  69295. }
  69296. return this._webvrViewMatrix;
  69297. };
  69298. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  69299. var _this = this;
  69300. var parentCamera = this.parent;
  69301. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  69302. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  69303. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  69304. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  69305. //babylon compatible matrix
  69306. if (!this.getScene().useRightHandedSystem) {
  69307. [8, 9, 10, 11].forEach(function (num) {
  69308. _this._projectionMatrix.m[num] *= -1;
  69309. });
  69310. }
  69311. return this._projectionMatrix;
  69312. };
  69313. WebVRFreeCamera.prototype.initControllers = function () {
  69314. var _this = this;
  69315. this.controllers = [];
  69316. var manager = this.getScene().gamepadManager;
  69317. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69318. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69319. var webVrController = gamepad;
  69320. if (webVrController.defaultModel) {
  69321. webVrController.defaultModel.setEnabled(false);
  69322. }
  69323. }
  69324. });
  69325. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69326. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69327. var webVrController_1 = gamepad;
  69328. if (_this.webVROptions.controllerMeshes) {
  69329. if (webVrController_1.defaultModel) {
  69330. webVrController_1.defaultModel.setEnabled(true);
  69331. }
  69332. else {
  69333. // Load the meshes
  69334. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  69335. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  69336. if (_this.webVROptions.defaultLightingOnControllers) {
  69337. if (!_this._lightOnControllers) {
  69338. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  69339. }
  69340. var activateLightOnSubMeshes_1 = function (mesh, light) {
  69341. var children = mesh.getChildren();
  69342. if (children.length !== 0) {
  69343. children.forEach(function (mesh) {
  69344. light.includedOnlyMeshes.push(mesh);
  69345. activateLightOnSubMeshes_1(mesh, light);
  69346. });
  69347. }
  69348. };
  69349. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  69350. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  69351. }
  69352. });
  69353. }
  69354. }
  69355. webVrController_1.attachToPoseControlledCamera(_this);
  69356. // since this is async - sanity check. Is the controller already stored?
  69357. if (_this.controllers.indexOf(webVrController_1) === -1) {
  69358. //add to the controllers array
  69359. _this.controllers.push(webVrController_1);
  69360. //did we find enough controllers? Great! let the developer know.
  69361. if (_this.controllers.length >= 2) {
  69362. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  69363. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  69364. // So we're overriding setting left & right manually to be sure
  69365. var firstViveWandDetected = false;
  69366. for (var i = 0; i < _this.controllers.length; i++) {
  69367. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  69368. if (!firstViveWandDetected) {
  69369. firstViveWandDetected = true;
  69370. _this.controllers[i].hand = "left";
  69371. }
  69372. else {
  69373. _this.controllers[i].hand = "right";
  69374. }
  69375. }
  69376. }
  69377. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  69378. }
  69379. }
  69380. }
  69381. });
  69382. };
  69383. return WebVRFreeCamera;
  69384. }(BABYLON.FreeCamera));
  69385. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  69386. })(BABYLON || (BABYLON = {}));
  69387. //# sourceMappingURL=babylon.webVRCamera.js.map
  69388. var BABYLON;
  69389. (function (BABYLON) {
  69390. // We're mainly based on the logic defined into the FreeCamera code
  69391. var DeviceOrientationCamera = /** @class */ (function (_super) {
  69392. __extends(DeviceOrientationCamera, _super);
  69393. function DeviceOrientationCamera(name, position, scene) {
  69394. var _this = _super.call(this, name, position, scene) || this;
  69395. _this._quaternionCache = new BABYLON.Quaternion();
  69396. _this.inputs.addDeviceOrientation();
  69397. return _this;
  69398. }
  69399. DeviceOrientationCamera.prototype.getClassName = function () {
  69400. return "DeviceOrientationCamera";
  69401. };
  69402. DeviceOrientationCamera.prototype._checkInputs = function () {
  69403. _super.prototype._checkInputs.call(this);
  69404. this._quaternionCache.copyFrom(this.rotationQuaternion);
  69405. if (this._initialQuaternion) {
  69406. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69407. }
  69408. };
  69409. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  69410. var _this = this;
  69411. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  69412. //can only work if this camera has a rotation quaternion already.
  69413. if (!this.rotationQuaternion)
  69414. return;
  69415. if (!this._initialQuaternion) {
  69416. this._initialQuaternion = new BABYLON.Quaternion();
  69417. }
  69418. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  69419. ['x', 'y', 'z'].forEach(function (axisName) {
  69420. if (!axis[axisName]) {
  69421. _this._initialQuaternion[axisName] = 0;
  69422. }
  69423. else {
  69424. _this._initialQuaternion[axisName] *= -1;
  69425. }
  69426. });
  69427. this._initialQuaternion.normalize();
  69428. //force rotation update
  69429. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69430. };
  69431. return DeviceOrientationCamera;
  69432. }(BABYLON.FreeCamera));
  69433. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  69434. })(BABYLON || (BABYLON = {}));
  69435. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  69436. var BABYLON;
  69437. (function (BABYLON) {
  69438. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  69439. __extends(VRDeviceOrientationFreeCamera, _super);
  69440. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69441. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69442. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69443. var _this = _super.call(this, name, position, scene) || this;
  69444. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69445. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69446. return _this;
  69447. }
  69448. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  69449. return "VRDeviceOrientationFreeCamera";
  69450. };
  69451. return VRDeviceOrientationFreeCamera;
  69452. }(BABYLON.DeviceOrientationCamera));
  69453. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  69454. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  69455. __extends(VRDeviceOrientationGamepadCamera, _super);
  69456. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69457. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69458. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69459. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  69460. _this.inputs.addGamepad();
  69461. return _this;
  69462. }
  69463. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  69464. return "VRDeviceOrientationGamepadCamera";
  69465. };
  69466. return VRDeviceOrientationGamepadCamera;
  69467. }(VRDeviceOrientationFreeCamera));
  69468. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  69469. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  69470. __extends(VRDeviceOrientationArcRotateCamera, _super);
  69471. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  69472. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69473. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69474. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69475. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69476. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69477. _this.inputs.addVRDeviceOrientation();
  69478. return _this;
  69479. }
  69480. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  69481. return "VRDeviceOrientationArcRotateCamera";
  69482. };
  69483. return VRDeviceOrientationArcRotateCamera;
  69484. }(BABYLON.ArcRotateCamera));
  69485. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  69486. })(BABYLON || (BABYLON = {}));
  69487. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  69488. var BABYLON;
  69489. (function (BABYLON) {
  69490. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  69491. __extends(AnaglyphFreeCamera, _super);
  69492. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  69493. var _this = _super.call(this, name, position, scene) || this;
  69494. _this.interaxialDistance = interaxialDistance;
  69495. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69496. return _this;
  69497. }
  69498. AnaglyphFreeCamera.prototype.getClassName = function () {
  69499. return "AnaglyphFreeCamera";
  69500. };
  69501. return AnaglyphFreeCamera;
  69502. }(BABYLON.FreeCamera));
  69503. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  69504. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  69505. __extends(AnaglyphArcRotateCamera, _super);
  69506. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  69507. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69508. _this.interaxialDistance = interaxialDistance;
  69509. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69510. return _this;
  69511. }
  69512. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  69513. return "AnaglyphArcRotateCamera";
  69514. };
  69515. return AnaglyphArcRotateCamera;
  69516. }(BABYLON.ArcRotateCamera));
  69517. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  69518. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  69519. __extends(AnaglyphGamepadCamera, _super);
  69520. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  69521. var _this = _super.call(this, name, position, scene) || this;
  69522. _this.interaxialDistance = interaxialDistance;
  69523. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69524. return _this;
  69525. }
  69526. AnaglyphGamepadCamera.prototype.getClassName = function () {
  69527. return "AnaglyphGamepadCamera";
  69528. };
  69529. return AnaglyphGamepadCamera;
  69530. }(BABYLON.GamepadCamera));
  69531. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  69532. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  69533. __extends(AnaglyphUniversalCamera, _super);
  69534. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  69535. var _this = _super.call(this, name, position, scene) || this;
  69536. _this.interaxialDistance = interaxialDistance;
  69537. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69538. return _this;
  69539. }
  69540. AnaglyphUniversalCamera.prototype.getClassName = function () {
  69541. return "AnaglyphUniversalCamera";
  69542. };
  69543. return AnaglyphUniversalCamera;
  69544. }(BABYLON.UniversalCamera));
  69545. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  69546. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  69547. __extends(StereoscopicFreeCamera, _super);
  69548. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69549. var _this = _super.call(this, name, position, scene) || this;
  69550. _this.interaxialDistance = interaxialDistance;
  69551. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69552. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69553. return _this;
  69554. }
  69555. StereoscopicFreeCamera.prototype.getClassName = function () {
  69556. return "StereoscopicFreeCamera";
  69557. };
  69558. return StereoscopicFreeCamera;
  69559. }(BABYLON.FreeCamera));
  69560. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  69561. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  69562. __extends(StereoscopicArcRotateCamera, _super);
  69563. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  69564. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69565. _this.interaxialDistance = interaxialDistance;
  69566. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69567. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69568. return _this;
  69569. }
  69570. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  69571. return "StereoscopicArcRotateCamera";
  69572. };
  69573. return StereoscopicArcRotateCamera;
  69574. }(BABYLON.ArcRotateCamera));
  69575. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  69576. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  69577. __extends(StereoscopicGamepadCamera, _super);
  69578. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69579. var _this = _super.call(this, name, position, scene) || this;
  69580. _this.interaxialDistance = interaxialDistance;
  69581. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69582. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69583. return _this;
  69584. }
  69585. StereoscopicGamepadCamera.prototype.getClassName = function () {
  69586. return "StereoscopicGamepadCamera";
  69587. };
  69588. return StereoscopicGamepadCamera;
  69589. }(BABYLON.GamepadCamera));
  69590. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  69591. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  69592. __extends(StereoscopicUniversalCamera, _super);
  69593. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69594. var _this = _super.call(this, name, position, scene) || this;
  69595. _this.interaxialDistance = interaxialDistance;
  69596. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69597. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69598. return _this;
  69599. }
  69600. StereoscopicUniversalCamera.prototype.getClassName = function () {
  69601. return "StereoscopicUniversalCamera";
  69602. };
  69603. return StereoscopicUniversalCamera;
  69604. }(BABYLON.UniversalCamera));
  69605. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  69606. })(BABYLON || (BABYLON = {}));
  69607. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  69608. var BABYLON;
  69609. (function (BABYLON) {
  69610. var VRExperienceHelper = /** @class */ (function () {
  69611. function VRExperienceHelper(scene, webVROptions) {
  69612. if (webVROptions === void 0) { webVROptions = {}; }
  69613. var _this = this;
  69614. this.webVROptions = webVROptions;
  69615. // Can the system support WebVR, even if a headset isn't plugged in?
  69616. this._webVRsupported = false;
  69617. // If WebVR is supported, is a headset plugged in and are we ready to present?
  69618. this._webVRready = false;
  69619. // Are we waiting for the requestPresent callback to complete?
  69620. this._webVRrequesting = false;
  69621. // Are we presenting to the headset right now?
  69622. this._webVRpresenting = false;
  69623. // Are we presenting in the fullscreen fallback?
  69624. this._fullscreenVRpresenting = false;
  69625. this._scene = scene;
  69626. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  69627. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  69628. }
  69629. else {
  69630. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  69631. if (scene.activeCamera.rotation) {
  69632. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  69633. }
  69634. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  69635. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  69636. }
  69637. this._scene.activeCamera = this._deviceOrientationCamera;
  69638. this._position = this._scene.activeCamera.position;
  69639. this._canvas = scene.getEngine().getRenderingCanvas();
  69640. if (this._canvas) {
  69641. this._scene.activeCamera.attachControl(this._canvas);
  69642. }
  69643. this._btnVR = document.createElement("BUTTON");
  69644. this._btnVR.className = "babylonVRicon";
  69645. this._btnVR.id = "babylonVRiconbtn";
  69646. this._btnVR.title = "Click to switch to VR";
  69647. 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) }";
  69648. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  69649. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  69650. // css += ".babylonVRicon.vrdisplaysupported { }";
  69651. // css += ".babylonVRicon.vrdisplayready { }";
  69652. // css += ".babylonVRicon.vrdisplayrequesting { }";
  69653. var style = document.createElement('style');
  69654. style.appendChild(document.createTextNode(css));
  69655. document.getElementsByTagName('head')[0].appendChild(style);
  69656. if (this._canvas) {
  69657. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69658. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69659. this._btnVR.addEventListener("click", function () {
  69660. _this.enterVR();
  69661. });
  69662. window.addEventListener("resize", function () {
  69663. if (_this._canvas) {
  69664. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  69665. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  69666. }
  69667. if (_this._fullscreenVRpresenting && _this._webVRready) {
  69668. _this.exitVR();
  69669. }
  69670. });
  69671. }
  69672. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69673. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69674. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69675. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69676. document.body.appendChild(this._btnVR);
  69677. // Exiting VR mode using 'ESC' key on desktop
  69678. this._onKeyDown = function (event) {
  69679. if (event.keyCode === 27 && _this.isInVRMode()) {
  69680. _this.exitVR();
  69681. }
  69682. };
  69683. document.addEventListener("keydown", this._onKeyDown);
  69684. // Exiting VR mode double tapping the touch screen
  69685. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  69686. if (_this.isInVRMode()) {
  69687. _this.exitVR();
  69688. if (_this._fullscreenVRpresenting) {
  69689. _this._scene.getEngine().switchFullscreen(true);
  69690. }
  69691. }
  69692. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  69693. // Listen for WebVR display changes
  69694. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  69695. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  69696. this._onVRRequestPresentStart = function () {
  69697. _this._webVRrequesting = true;
  69698. _this.updateButtonVisibility();
  69699. };
  69700. this._onVRRequestPresentComplete = function (success) {
  69701. _this._webVRrequesting = false;
  69702. _this.updateButtonVisibility();
  69703. };
  69704. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  69705. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  69706. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  69707. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69708. // Create the cameras
  69709. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  69710. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  69711. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  69712. this.updateButtonVisibility();
  69713. }
  69714. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  69715. if (this.onControllerMeshLoaded) {
  69716. this.onControllerMeshLoaded(webVRController);
  69717. }
  69718. };
  69719. VRExperienceHelper.prototype._onFullscreenChange = function () {
  69720. if (document.fullscreen !== undefined) {
  69721. this._fullscreenVRpresenting = document.fullscreen;
  69722. }
  69723. else if (document.mozFullScreen !== undefined) {
  69724. this._fullscreenVRpresenting = document.mozFullScreen;
  69725. }
  69726. else if (document.webkitIsFullScreen !== undefined) {
  69727. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  69728. }
  69729. else if (document.msIsFullScreen !== undefined) {
  69730. this._fullscreenVRpresenting = document.msIsFullScreen;
  69731. }
  69732. if (!this._fullscreenVRpresenting && this._canvas) {
  69733. this.exitVR();
  69734. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69735. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69736. }
  69737. };
  69738. VRExperienceHelper.prototype.isInVRMode = function () {
  69739. return this._webVRpresenting || this._fullscreenVRpresenting;
  69740. };
  69741. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  69742. var vrDisplay = this._scene.getEngine().getVRDevice();
  69743. if (vrDisplay) {
  69744. var wasPresenting = this._webVRpresenting;
  69745. // A VR display is connected
  69746. this._webVRpresenting = vrDisplay.isPresenting;
  69747. if (wasPresenting && !this._webVRpresenting)
  69748. this.exitVR();
  69749. }
  69750. else {
  69751. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  69752. }
  69753. this.updateButtonVisibility();
  69754. };
  69755. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  69756. this._webVRsupported = eventArgs.vrSupported;
  69757. this._webVRready = !!eventArgs.vrDisplay;
  69758. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  69759. this.updateButtonVisibility();
  69760. };
  69761. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  69762. if (!this._btnVR) {
  69763. return;
  69764. }
  69765. this._btnVR.className = "babylonVRicon";
  69766. if (this.isInVRMode()) {
  69767. this._btnVR.className += " vrdisplaypresenting";
  69768. }
  69769. else {
  69770. if (this._webVRready)
  69771. this._btnVR.className += " vrdisplayready";
  69772. if (this._webVRsupported)
  69773. this._btnVR.className += " vrdisplaysupported";
  69774. if (this._webVRrequesting)
  69775. this._btnVR.className += " vrdisplayrequesting";
  69776. }
  69777. };
  69778. /**
  69779. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  69780. * Otherwise, will use the fullscreen API.
  69781. */
  69782. VRExperienceHelper.prototype.enterVR = function () {
  69783. if (this.onEnteringVR) {
  69784. this.onEnteringVR();
  69785. }
  69786. if (this._webVRrequesting)
  69787. return;
  69788. // If WebVR is supported and a headset is connected
  69789. if (this._webVRready) {
  69790. if (!this._webVRpresenting) {
  69791. this._webVRCamera.position = this._position;
  69792. this._scene.activeCamera = this._webVRCamera;
  69793. }
  69794. }
  69795. else {
  69796. this._vrDeviceOrientationCamera.position = this._position;
  69797. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  69798. this._scene.getEngine().switchFullscreen(true);
  69799. this.updateButtonVisibility();
  69800. }
  69801. if (this._scene.activeCamera && this._canvas) {
  69802. this._scene.activeCamera.attachControl(this._canvas);
  69803. }
  69804. };
  69805. /**
  69806. * Attempt to exit VR, or fullscreen.
  69807. */
  69808. VRExperienceHelper.prototype.exitVR = function () {
  69809. if (this.onExitingVR) {
  69810. this.onExitingVR();
  69811. }
  69812. if (this._webVRpresenting) {
  69813. this._scene.getEngine().disableVR();
  69814. }
  69815. if (this._scene.activeCamera) {
  69816. this._position = this._scene.activeCamera.position;
  69817. }
  69818. this._deviceOrientationCamera.position = this._position;
  69819. this._scene.activeCamera = this._deviceOrientationCamera;
  69820. if (this._canvas) {
  69821. this._scene.activeCamera.attachControl(this._canvas);
  69822. }
  69823. this.updateButtonVisibility();
  69824. };
  69825. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  69826. get: function () {
  69827. return this._position;
  69828. },
  69829. set: function (value) {
  69830. this._position = value;
  69831. if (this._scene.activeCamera) {
  69832. this._scene.activeCamera.position = value;
  69833. }
  69834. },
  69835. enumerable: true,
  69836. configurable: true
  69837. });
  69838. VRExperienceHelper.prototype.dispose = function () {
  69839. if (this.isInVRMode()) {
  69840. this.exitVR();
  69841. }
  69842. this._deviceOrientationCamera.dispose();
  69843. if (this._webVRCamera) {
  69844. this._webVRCamera.dispose();
  69845. }
  69846. if (this._vrDeviceOrientationCamera) {
  69847. this._vrDeviceOrientationCamera.dispose();
  69848. }
  69849. document.body.removeChild(this._btnVR);
  69850. document.removeEventListener("keydown", this._onKeyDown);
  69851. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69852. };
  69853. VRExperienceHelper.prototype.getClassName = function () {
  69854. return "VRExperienceHelper";
  69855. };
  69856. return VRExperienceHelper;
  69857. }());
  69858. BABYLON.VRExperienceHelper = VRExperienceHelper;
  69859. })(BABYLON || (BABYLON = {}));
  69860. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  69861. // Mainly based on these 2 articles :
  69862. // 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
  69863. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  69864. var BABYLON;
  69865. (function (BABYLON) {
  69866. var JoystickAxis;
  69867. (function (JoystickAxis) {
  69868. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  69869. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  69870. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  69871. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  69872. var VirtualJoystick = /** @class */ (function () {
  69873. function VirtualJoystick(leftJoystick) {
  69874. var _this = this;
  69875. if (leftJoystick) {
  69876. this._leftJoystick = true;
  69877. }
  69878. else {
  69879. this._leftJoystick = false;
  69880. }
  69881. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  69882. VirtualJoystick._globalJoystickIndex++;
  69883. // By default left & right arrow keys are moving the X
  69884. // and up & down keys are moving the Y
  69885. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  69886. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  69887. this.reverseLeftRight = false;
  69888. this.reverseUpDown = false;
  69889. // collections of pointers
  69890. this._touches = new BABYLON.StringDictionary();
  69891. this.deltaPosition = BABYLON.Vector3.Zero();
  69892. this._joystickSensibility = 25;
  69893. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  69894. this._rotationSpeed = 25;
  69895. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  69896. this._rotateOnAxisRelativeToMesh = false;
  69897. this._onResize = function (evt) {
  69898. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  69899. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  69900. if (VirtualJoystick.vjCanvas) {
  69901. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  69902. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  69903. }
  69904. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  69905. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  69906. };
  69907. // injecting a canvas element on top of the canvas 3D game
  69908. if (!VirtualJoystick.vjCanvas) {
  69909. window.addEventListener("resize", this._onResize, false);
  69910. VirtualJoystick.vjCanvas = document.createElement("canvas");
  69911. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  69912. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  69913. VirtualJoystick.vjCanvas.width = window.innerWidth;
  69914. VirtualJoystick.vjCanvas.height = window.innerHeight;
  69915. VirtualJoystick.vjCanvas.style.width = "100%";
  69916. VirtualJoystick.vjCanvas.style.height = "100%";
  69917. VirtualJoystick.vjCanvas.style.position = "absolute";
  69918. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  69919. VirtualJoystick.vjCanvas.style.top = "0px";
  69920. VirtualJoystick.vjCanvas.style.left = "0px";
  69921. VirtualJoystick.vjCanvas.style.zIndex = "5";
  69922. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  69923. // Support for jQuery PEP polyfill
  69924. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  69925. var context = VirtualJoystick.vjCanvas.getContext('2d');
  69926. if (!context) {
  69927. throw new Error("Unable to create canvas for virtual joystick");
  69928. }
  69929. VirtualJoystick.vjCanvasContext = context;
  69930. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  69931. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  69932. document.body.appendChild(VirtualJoystick.vjCanvas);
  69933. }
  69934. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  69935. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  69936. this.pressed = false;
  69937. // default joystick color
  69938. this._joystickColor = "cyan";
  69939. this._joystickPointerID = -1;
  69940. // current joystick position
  69941. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  69942. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  69943. // origin joystick position
  69944. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  69945. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  69946. this._onPointerDownHandlerRef = function (evt) {
  69947. _this._onPointerDown(evt);
  69948. };
  69949. this._onPointerMoveHandlerRef = function (evt) {
  69950. _this._onPointerMove(evt);
  69951. };
  69952. this._onPointerOutHandlerRef = function (evt) {
  69953. _this._onPointerUp(evt);
  69954. };
  69955. this._onPointerUpHandlerRef = function (evt) {
  69956. _this._onPointerUp(evt);
  69957. };
  69958. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  69959. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  69960. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  69961. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  69962. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  69963. evt.preventDefault(); // Disables system menu
  69964. }, false);
  69965. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  69966. }
  69967. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  69968. this._joystickSensibility = newJoystickSensibility;
  69969. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  69970. };
  69971. VirtualJoystick.prototype._onPointerDown = function (e) {
  69972. var positionOnScreenCondition;
  69973. e.preventDefault();
  69974. if (this._leftJoystick === true) {
  69975. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  69976. }
  69977. else {
  69978. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  69979. }
  69980. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  69981. // First contact will be dedicated to the virtual joystick
  69982. this._joystickPointerID = e.pointerId;
  69983. this._joystickPointerStartPos.x = e.clientX;
  69984. this._joystickPointerStartPos.y = e.clientY;
  69985. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  69986. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  69987. this._deltaJoystickVector.x = 0;
  69988. this._deltaJoystickVector.y = 0;
  69989. this.pressed = true;
  69990. this._touches.add(e.pointerId.toString(), e);
  69991. }
  69992. else {
  69993. // You can only trigger the action buttons with a joystick declared
  69994. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  69995. this._action();
  69996. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  69997. }
  69998. }
  69999. };
  70000. VirtualJoystick.prototype._onPointerMove = function (e) {
  70001. // If the current pointer is the one associated to the joystick (first touch contact)
  70002. if (this._joystickPointerID == e.pointerId) {
  70003. this._joystickPointerPos.x = e.clientX;
  70004. this._joystickPointerPos.y = e.clientY;
  70005. this._deltaJoystickVector = this._joystickPointerPos.clone();
  70006. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  70007. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  70008. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  70009. switch (this._axisTargetedByLeftAndRight) {
  70010. case JoystickAxis.X:
  70011. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  70012. break;
  70013. case JoystickAxis.Y:
  70014. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  70015. break;
  70016. case JoystickAxis.Z:
  70017. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  70018. break;
  70019. }
  70020. var directionUpDown = this.reverseUpDown ? 1 : -1;
  70021. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  70022. switch (this._axisTargetedByUpAndDown) {
  70023. case JoystickAxis.X:
  70024. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  70025. break;
  70026. case JoystickAxis.Y:
  70027. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  70028. break;
  70029. case JoystickAxis.Z:
  70030. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  70031. break;
  70032. }
  70033. }
  70034. else {
  70035. var data = this._touches.get(e.pointerId.toString());
  70036. if (data) {
  70037. data.x = e.clientX;
  70038. data.y = e.clientY;
  70039. }
  70040. }
  70041. };
  70042. VirtualJoystick.prototype._onPointerUp = function (e) {
  70043. if (this._joystickPointerID == e.pointerId) {
  70044. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  70045. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  70046. this._joystickPointerID = -1;
  70047. this.pressed = false;
  70048. }
  70049. else {
  70050. var touch = this._touches.get(e.pointerId.toString());
  70051. if (touch) {
  70052. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70053. }
  70054. }
  70055. this._deltaJoystickVector.x = 0;
  70056. this._deltaJoystickVector.y = 0;
  70057. this._touches.remove(e.pointerId.toString());
  70058. };
  70059. /**
  70060. * Change the color of the virtual joystick
  70061. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  70062. */
  70063. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  70064. this._joystickColor = newColor;
  70065. };
  70066. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  70067. this._action = action;
  70068. };
  70069. // Define which axis you'd like to control for left & right
  70070. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  70071. switch (axis) {
  70072. case JoystickAxis.X:
  70073. case JoystickAxis.Y:
  70074. case JoystickAxis.Z:
  70075. this._axisTargetedByLeftAndRight = axis;
  70076. break;
  70077. default:
  70078. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70079. break;
  70080. }
  70081. };
  70082. // Define which axis you'd like to control for up & down
  70083. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  70084. switch (axis) {
  70085. case JoystickAxis.X:
  70086. case JoystickAxis.Y:
  70087. case JoystickAxis.Z:
  70088. this._axisTargetedByUpAndDown = axis;
  70089. break;
  70090. default:
  70091. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70092. break;
  70093. }
  70094. };
  70095. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  70096. var _this = this;
  70097. if (this.pressed) {
  70098. this._touches.forEach(function (key, touch) {
  70099. if (touch.pointerId === _this._joystickPointerID) {
  70100. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  70101. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  70102. VirtualJoystick.vjCanvasContext.beginPath();
  70103. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70104. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70105. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  70106. VirtualJoystick.vjCanvasContext.stroke();
  70107. VirtualJoystick.vjCanvasContext.closePath();
  70108. VirtualJoystick.vjCanvasContext.beginPath();
  70109. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70110. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70111. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  70112. VirtualJoystick.vjCanvasContext.stroke();
  70113. VirtualJoystick.vjCanvasContext.closePath();
  70114. VirtualJoystick.vjCanvasContext.beginPath();
  70115. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70116. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  70117. VirtualJoystick.vjCanvasContext.stroke();
  70118. VirtualJoystick.vjCanvasContext.closePath();
  70119. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  70120. }
  70121. else {
  70122. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70123. VirtualJoystick.vjCanvasContext.beginPath();
  70124. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  70125. VirtualJoystick.vjCanvasContext.beginPath();
  70126. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  70127. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70128. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  70129. VirtualJoystick.vjCanvasContext.stroke();
  70130. VirtualJoystick.vjCanvasContext.closePath();
  70131. touch.prevX = touch.x;
  70132. touch.prevY = touch.y;
  70133. }
  70134. ;
  70135. });
  70136. }
  70137. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70138. };
  70139. VirtualJoystick.prototype.releaseCanvas = function () {
  70140. if (VirtualJoystick.vjCanvas) {
  70141. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  70142. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  70143. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  70144. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  70145. window.removeEventListener("resize", this._onResize);
  70146. document.body.removeChild(VirtualJoystick.vjCanvas);
  70147. VirtualJoystick.vjCanvas = null;
  70148. }
  70149. };
  70150. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  70151. VirtualJoystick._globalJoystickIndex = 0;
  70152. return VirtualJoystick;
  70153. }());
  70154. BABYLON.VirtualJoystick = VirtualJoystick;
  70155. })(BABYLON || (BABYLON = {}));
  70156. //# sourceMappingURL=babylon.virtualJoystick.js.map
  70157. var BABYLON;
  70158. (function (BABYLON) {
  70159. // We're mainly based on the logic defined into the FreeCamera code
  70160. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  70161. __extends(VirtualJoysticksCamera, _super);
  70162. function VirtualJoysticksCamera(name, position, scene) {
  70163. var _this = _super.call(this, name, position, scene) || this;
  70164. _this.inputs.addVirtualJoystick();
  70165. return _this;
  70166. }
  70167. VirtualJoysticksCamera.prototype.getClassName = function () {
  70168. return "VirtualJoysticksCamera";
  70169. };
  70170. return VirtualJoysticksCamera;
  70171. }(BABYLON.FreeCamera));
  70172. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  70173. })(BABYLON || (BABYLON = {}));
  70174. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  70175. var BABYLON;
  70176. (function (BABYLON) {
  70177. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  70178. function FreeCameraVirtualJoystickInput() {
  70179. }
  70180. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  70181. return this._leftjoystick;
  70182. };
  70183. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  70184. return this._rightjoystick;
  70185. };
  70186. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  70187. if (this._leftjoystick) {
  70188. var camera = this.camera;
  70189. var speed = camera._computeLocalCameraSpeed() * 50;
  70190. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  70191. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  70192. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  70193. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  70194. if (!this._leftjoystick.pressed) {
  70195. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  70196. }
  70197. if (!this._rightjoystick.pressed) {
  70198. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  70199. }
  70200. }
  70201. };
  70202. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  70203. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  70204. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  70205. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  70206. this._leftjoystick.setJoystickSensibility(0.15);
  70207. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  70208. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  70209. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  70210. this._rightjoystick.reverseUpDown = true;
  70211. this._rightjoystick.setJoystickSensibility(0.05);
  70212. this._rightjoystick.setJoystickColor("yellow");
  70213. };
  70214. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  70215. this._leftjoystick.releaseCanvas();
  70216. this._rightjoystick.releaseCanvas();
  70217. };
  70218. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  70219. return "FreeCameraVirtualJoystickInput";
  70220. };
  70221. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  70222. return "virtualJoystick";
  70223. };
  70224. return FreeCameraVirtualJoystickInput;
  70225. }());
  70226. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  70227. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  70228. })(BABYLON || (BABYLON = {}));
  70229. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  70230. var BABYLON;
  70231. (function (BABYLON) {
  70232. var SimplificationSettings = /** @class */ (function () {
  70233. function SimplificationSettings(quality, distance, optimizeMesh) {
  70234. this.quality = quality;
  70235. this.distance = distance;
  70236. this.optimizeMesh = optimizeMesh;
  70237. }
  70238. return SimplificationSettings;
  70239. }());
  70240. BABYLON.SimplificationSettings = SimplificationSettings;
  70241. var SimplificationQueue = /** @class */ (function () {
  70242. function SimplificationQueue() {
  70243. this.running = false;
  70244. this._simplificationArray = [];
  70245. }
  70246. SimplificationQueue.prototype.addTask = function (task) {
  70247. this._simplificationArray.push(task);
  70248. };
  70249. SimplificationQueue.prototype.executeNext = function () {
  70250. var task = this._simplificationArray.pop();
  70251. if (task) {
  70252. this.running = true;
  70253. this.runSimplification(task);
  70254. }
  70255. else {
  70256. this.running = false;
  70257. }
  70258. };
  70259. SimplificationQueue.prototype.runSimplification = function (task) {
  70260. var _this = this;
  70261. if (task.parallelProcessing) {
  70262. //parallel simplifier
  70263. task.settings.forEach(function (setting) {
  70264. var simplifier = _this.getSimplifier(task);
  70265. simplifier.simplify(setting, function (newMesh) {
  70266. task.mesh.addLODLevel(setting.distance, newMesh);
  70267. newMesh.isVisible = true;
  70268. //check if it is the last
  70269. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  70270. //all done, run the success callback.
  70271. task.successCallback();
  70272. }
  70273. _this.executeNext();
  70274. });
  70275. });
  70276. }
  70277. else {
  70278. //single simplifier.
  70279. var simplifier = this.getSimplifier(task);
  70280. var runDecimation = function (setting, callback) {
  70281. simplifier.simplify(setting, function (newMesh) {
  70282. task.mesh.addLODLevel(setting.distance, newMesh);
  70283. newMesh.isVisible = true;
  70284. //run the next quality level
  70285. callback();
  70286. });
  70287. };
  70288. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  70289. runDecimation(task.settings[loop.index], function () {
  70290. loop.executeNext();
  70291. });
  70292. }, function () {
  70293. //execution ended, run the success callback.
  70294. if (task.successCallback) {
  70295. task.successCallback();
  70296. }
  70297. _this.executeNext();
  70298. });
  70299. }
  70300. };
  70301. SimplificationQueue.prototype.getSimplifier = function (task) {
  70302. switch (task.simplificationType) {
  70303. case SimplificationType.QUADRATIC:
  70304. default:
  70305. return new QuadraticErrorSimplification(task.mesh);
  70306. }
  70307. };
  70308. return SimplificationQueue;
  70309. }());
  70310. BABYLON.SimplificationQueue = SimplificationQueue;
  70311. /**
  70312. * The implemented types of simplification.
  70313. * At the moment only Quadratic Error Decimation is implemented.
  70314. */
  70315. var SimplificationType;
  70316. (function (SimplificationType) {
  70317. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  70318. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  70319. var DecimationTriangle = /** @class */ (function () {
  70320. function DecimationTriangle(vertices) {
  70321. this.vertices = vertices;
  70322. this.error = new Array(4);
  70323. this.deleted = false;
  70324. this.isDirty = false;
  70325. this.deletePending = false;
  70326. this.borderFactor = 0;
  70327. }
  70328. return DecimationTriangle;
  70329. }());
  70330. BABYLON.DecimationTriangle = DecimationTriangle;
  70331. var DecimationVertex = /** @class */ (function () {
  70332. function DecimationVertex(position, id) {
  70333. this.position = position;
  70334. this.id = id;
  70335. this.isBorder = true;
  70336. this.q = new QuadraticMatrix();
  70337. this.triangleCount = 0;
  70338. this.triangleStart = 0;
  70339. this.originalOffsets = [];
  70340. }
  70341. DecimationVertex.prototype.updatePosition = function (newPosition) {
  70342. this.position.copyFrom(newPosition);
  70343. };
  70344. return DecimationVertex;
  70345. }());
  70346. BABYLON.DecimationVertex = DecimationVertex;
  70347. var QuadraticMatrix = /** @class */ (function () {
  70348. function QuadraticMatrix(data) {
  70349. this.data = new Array(10);
  70350. for (var i = 0; i < 10; ++i) {
  70351. if (data && data[i]) {
  70352. this.data[i] = data[i];
  70353. }
  70354. else {
  70355. this.data[i] = 0;
  70356. }
  70357. }
  70358. }
  70359. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  70360. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  70361. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  70362. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  70363. return det;
  70364. };
  70365. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  70366. for (var i = 0; i < 10; ++i) {
  70367. this.data[i] += matrix.data[i];
  70368. }
  70369. };
  70370. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  70371. for (var i = 0; i < 10; ++i) {
  70372. this.data[i] += data[i];
  70373. }
  70374. };
  70375. QuadraticMatrix.prototype.add = function (matrix) {
  70376. var m = new QuadraticMatrix();
  70377. for (var i = 0; i < 10; ++i) {
  70378. m.data[i] = this.data[i] + matrix.data[i];
  70379. }
  70380. return m;
  70381. };
  70382. QuadraticMatrix.FromData = function (a, b, c, d) {
  70383. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  70384. };
  70385. //returning an array to avoid garbage collection
  70386. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  70387. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  70388. };
  70389. return QuadraticMatrix;
  70390. }());
  70391. BABYLON.QuadraticMatrix = QuadraticMatrix;
  70392. var Reference = /** @class */ (function () {
  70393. function Reference(vertexId, triangleId) {
  70394. this.vertexId = vertexId;
  70395. this.triangleId = triangleId;
  70396. }
  70397. return Reference;
  70398. }());
  70399. BABYLON.Reference = Reference;
  70400. /**
  70401. * An implementation of the Quadratic Error simplification algorithm.
  70402. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  70403. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  70404. * @author RaananW
  70405. */
  70406. var QuadraticErrorSimplification = /** @class */ (function () {
  70407. function QuadraticErrorSimplification(_mesh) {
  70408. this._mesh = _mesh;
  70409. this.initialized = false;
  70410. this.syncIterations = 5000;
  70411. this.aggressiveness = 7;
  70412. this.decimationIterations = 100;
  70413. this.boundingBoxEpsilon = BABYLON.Epsilon;
  70414. }
  70415. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  70416. var _this = this;
  70417. this.initDecimatedMesh();
  70418. //iterating through the submeshes array, one after the other.
  70419. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  70420. _this.initWithMesh(loop.index, function () {
  70421. _this.runDecimation(settings, loop.index, function () {
  70422. loop.executeNext();
  70423. });
  70424. }, settings.optimizeMesh);
  70425. }, function () {
  70426. setTimeout(function () {
  70427. successCallback(_this._reconstructedMesh);
  70428. }, 0);
  70429. });
  70430. };
  70431. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  70432. var _this = this;
  70433. var targetCount = ~~(this.triangles.length * settings.quality);
  70434. var deletedTriangles = 0;
  70435. var triangleCount = this.triangles.length;
  70436. var iterationFunction = function (iteration, callback) {
  70437. setTimeout(function () {
  70438. if (iteration % 5 === 0) {
  70439. _this.updateMesh(iteration === 0);
  70440. }
  70441. for (var i = 0; i < _this.triangles.length; ++i) {
  70442. _this.triangles[i].isDirty = false;
  70443. }
  70444. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  70445. var trianglesIterator = function (i) {
  70446. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  70447. var t = _this.triangles[tIdx];
  70448. if (!t)
  70449. return;
  70450. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  70451. return;
  70452. }
  70453. for (var j = 0; j < 3; ++j) {
  70454. if (t.error[j] < threshold) {
  70455. var deleted0 = [];
  70456. var deleted1 = [];
  70457. var v0 = t.vertices[j];
  70458. var v1 = t.vertices[(j + 1) % 3];
  70459. if (v0.isBorder || v1.isBorder)
  70460. continue;
  70461. var p = BABYLON.Vector3.Zero();
  70462. var n = BABYLON.Vector3.Zero();
  70463. var uv = BABYLON.Vector2.Zero();
  70464. var color = new BABYLON.Color4(0, 0, 0, 1);
  70465. _this.calculateError(v0, v1, p, n, uv, color);
  70466. var delTr = new Array();
  70467. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  70468. continue;
  70469. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  70470. continue;
  70471. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  70472. continue;
  70473. var uniqueArray = new Array();
  70474. delTr.forEach(function (deletedT) {
  70475. if (uniqueArray.indexOf(deletedT) === -1) {
  70476. deletedT.deletePending = true;
  70477. uniqueArray.push(deletedT);
  70478. }
  70479. });
  70480. if (uniqueArray.length % 2 !== 0) {
  70481. continue;
  70482. }
  70483. v0.q = v1.q.add(v0.q);
  70484. v0.updatePosition(p);
  70485. var tStart = _this.references.length;
  70486. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  70487. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  70488. var tCount = _this.references.length - tStart;
  70489. if (tCount <= v0.triangleCount) {
  70490. if (tCount) {
  70491. for (var c = 0; c < tCount; c++) {
  70492. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  70493. }
  70494. }
  70495. }
  70496. else {
  70497. v0.triangleStart = tStart;
  70498. }
  70499. v0.triangleCount = tCount;
  70500. break;
  70501. }
  70502. }
  70503. };
  70504. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  70505. }, 0);
  70506. };
  70507. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  70508. if (triangleCount - deletedTriangles <= targetCount)
  70509. loop.breakLoop();
  70510. else {
  70511. iterationFunction(loop.index, function () {
  70512. loop.executeNext();
  70513. });
  70514. }
  70515. }, function () {
  70516. setTimeout(function () {
  70517. //reconstruct this part of the mesh
  70518. _this.reconstructMesh(submeshIndex);
  70519. successCallback();
  70520. }, 0);
  70521. });
  70522. };
  70523. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  70524. var _this = this;
  70525. this.vertices = [];
  70526. this.triangles = [];
  70527. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70528. var indices = this._mesh.getIndices();
  70529. var submesh = this._mesh.subMeshes[submeshIndex];
  70530. var findInVertices = function (positionToSearch) {
  70531. if (optimizeMesh) {
  70532. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  70533. if (_this.vertices[ii].position.equals(positionToSearch)) {
  70534. return _this.vertices[ii];
  70535. }
  70536. }
  70537. }
  70538. return null;
  70539. };
  70540. var vertexReferences = [];
  70541. var vertexInit = function (i) {
  70542. if (!positionData) {
  70543. return;
  70544. }
  70545. var offset = i + submesh.verticesStart;
  70546. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  70547. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  70548. vertex.originalOffsets.push(offset);
  70549. if (vertex.id === _this.vertices.length) {
  70550. _this.vertices.push(vertex);
  70551. }
  70552. vertexReferences.push(vertex.id);
  70553. };
  70554. //var totalVertices = mesh.getTotalVertices();
  70555. var totalVertices = submesh.verticesCount;
  70556. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  70557. var indicesInit = function (i) {
  70558. if (!indices) {
  70559. return;
  70560. }
  70561. var offset = (submesh.indexStart / 3) + i;
  70562. var pos = (offset * 3);
  70563. var i0 = indices[pos + 0];
  70564. var i1 = indices[pos + 1];
  70565. var i2 = indices[pos + 2];
  70566. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  70567. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  70568. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  70569. var triangle = new DecimationTriangle([v0, v1, v2]);
  70570. triangle.originalOffset = pos;
  70571. _this.triangles.push(triangle);
  70572. };
  70573. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  70574. _this.init(callback);
  70575. });
  70576. });
  70577. };
  70578. QuadraticErrorSimplification.prototype.init = function (callback) {
  70579. var _this = this;
  70580. var triangleInit1 = function (i) {
  70581. var t = _this.triangles[i];
  70582. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  70583. for (var j = 0; j < 3; j++) {
  70584. 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))));
  70585. }
  70586. };
  70587. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  70588. var triangleInit2 = function (i) {
  70589. var t = _this.triangles[i];
  70590. for (var j = 0; j < 3; ++j) {
  70591. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  70592. }
  70593. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70594. };
  70595. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  70596. _this.initialized = true;
  70597. callback();
  70598. });
  70599. });
  70600. };
  70601. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  70602. var newTriangles = [];
  70603. var i;
  70604. for (i = 0; i < this.vertices.length; ++i) {
  70605. this.vertices[i].triangleCount = 0;
  70606. }
  70607. var t;
  70608. var j;
  70609. for (i = 0; i < this.triangles.length; ++i) {
  70610. if (!this.triangles[i].deleted) {
  70611. t = this.triangles[i];
  70612. for (j = 0; j < 3; ++j) {
  70613. t.vertices[j].triangleCount = 1;
  70614. }
  70615. newTriangles.push(t);
  70616. }
  70617. }
  70618. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  70619. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  70620. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  70621. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  70622. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70623. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70624. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  70625. var vertexCount = 0;
  70626. for (i = 0; i < this.vertices.length; ++i) {
  70627. var vertex = this.vertices[i];
  70628. vertex.id = vertexCount;
  70629. if (vertex.triangleCount) {
  70630. vertex.originalOffsets.forEach(function (originalOffset) {
  70631. if (!normalData) {
  70632. return;
  70633. }
  70634. newPositionData.push(vertex.position.x);
  70635. newPositionData.push(vertex.position.y);
  70636. newPositionData.push(vertex.position.z);
  70637. newNormalData.push(normalData[originalOffset * 3]);
  70638. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  70639. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  70640. if (uvs && uvs.length) {
  70641. newUVsData.push(uvs[(originalOffset * 2)]);
  70642. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  70643. }
  70644. else if (colorsData && colorsData.length) {
  70645. newColorsData.push(colorsData[(originalOffset * 4)]);
  70646. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  70647. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  70648. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  70649. }
  70650. ++vertexCount;
  70651. });
  70652. }
  70653. }
  70654. var startingIndex = this._reconstructedMesh.getTotalIndices();
  70655. var startingVertex = this._reconstructedMesh.getTotalVertices();
  70656. var submeshesArray = this._reconstructedMesh.subMeshes;
  70657. this._reconstructedMesh.subMeshes = [];
  70658. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  70659. var originalIndices = this._mesh.getIndices();
  70660. for (i = 0; i < newTriangles.length; ++i) {
  70661. t = newTriangles[i]; //now get the new referencing point for each vertex
  70662. [0, 1, 2].forEach(function (idx) {
  70663. var id = originalIndices[t.originalOffset + idx];
  70664. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  70665. if (offset < 0)
  70666. offset = 0;
  70667. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  70668. });
  70669. }
  70670. //overwriting the old vertex buffers and indices.
  70671. this._reconstructedMesh.setIndices(newIndicesArray);
  70672. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  70673. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  70674. if (newUVsData.length > 0)
  70675. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  70676. if (newColorsData.length > 0)
  70677. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  70678. //create submesh
  70679. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  70680. if (submeshIndex > 0) {
  70681. this._reconstructedMesh.subMeshes = [];
  70682. submeshesArray.forEach(function (submesh) {
  70683. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  70684. });
  70685. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  70686. }
  70687. };
  70688. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  70689. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  70690. this._reconstructedMesh.material = this._mesh.material;
  70691. this._reconstructedMesh.parent = this._mesh.parent;
  70692. this._reconstructedMesh.isVisible = false;
  70693. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  70694. };
  70695. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  70696. for (var i = 0; i < vertex1.triangleCount; ++i) {
  70697. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  70698. if (t.deleted)
  70699. continue;
  70700. var s = this.references[vertex1.triangleStart + i].vertexId;
  70701. var v1 = t.vertices[(s + 1) % 3];
  70702. var v2 = t.vertices[(s + 2) % 3];
  70703. if ((v1 === vertex2 || v2 === vertex2)) {
  70704. deletedArray[i] = true;
  70705. delTr.push(t);
  70706. continue;
  70707. }
  70708. var d1 = v1.position.subtract(point);
  70709. d1 = d1.normalize();
  70710. var d2 = v2.position.subtract(point);
  70711. d2 = d2.normalize();
  70712. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  70713. return true;
  70714. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  70715. deletedArray[i] = false;
  70716. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  70717. return true;
  70718. }
  70719. return false;
  70720. };
  70721. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  70722. var newDeleted = deletedTriangles;
  70723. for (var i = 0; i < vertex.triangleCount; ++i) {
  70724. var ref = this.references[vertex.triangleStart + i];
  70725. var t = this.triangles[ref.triangleId];
  70726. if (t.deleted)
  70727. continue;
  70728. if (deletedArray[i] && t.deletePending) {
  70729. t.deleted = true;
  70730. newDeleted++;
  70731. continue;
  70732. }
  70733. t.vertices[ref.vertexId] = origVertex;
  70734. t.isDirty = true;
  70735. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  70736. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  70737. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  70738. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70739. this.references.push(ref);
  70740. }
  70741. return newDeleted;
  70742. };
  70743. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  70744. for (var i = 0; i < this.vertices.length; ++i) {
  70745. var vCount = [];
  70746. var vId = [];
  70747. var v = this.vertices[i];
  70748. var j;
  70749. for (j = 0; j < v.triangleCount; ++j) {
  70750. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  70751. for (var ii = 0; ii < 3; ii++) {
  70752. var ofs = 0;
  70753. var vv = triangle.vertices[ii];
  70754. while (ofs < vCount.length) {
  70755. if (vId[ofs] === vv.id)
  70756. break;
  70757. ++ofs;
  70758. }
  70759. if (ofs === vCount.length) {
  70760. vCount.push(1);
  70761. vId.push(vv.id);
  70762. }
  70763. else {
  70764. vCount[ofs]++;
  70765. }
  70766. }
  70767. }
  70768. for (j = 0; j < vCount.length; ++j) {
  70769. if (vCount[j] === 1) {
  70770. this.vertices[vId[j]].isBorder = true;
  70771. }
  70772. else {
  70773. this.vertices[vId[j]].isBorder = false;
  70774. }
  70775. }
  70776. }
  70777. };
  70778. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  70779. if (identifyBorders === void 0) { identifyBorders = false; }
  70780. var i;
  70781. if (!identifyBorders) {
  70782. var newTrianglesVector = [];
  70783. for (i = 0; i < this.triangles.length; ++i) {
  70784. if (!this.triangles[i].deleted) {
  70785. newTrianglesVector.push(this.triangles[i]);
  70786. }
  70787. }
  70788. this.triangles = newTrianglesVector;
  70789. }
  70790. for (i = 0; i < this.vertices.length; ++i) {
  70791. this.vertices[i].triangleCount = 0;
  70792. this.vertices[i].triangleStart = 0;
  70793. }
  70794. var t;
  70795. var j;
  70796. var v;
  70797. for (i = 0; i < this.triangles.length; ++i) {
  70798. t = this.triangles[i];
  70799. for (j = 0; j < 3; ++j) {
  70800. v = t.vertices[j];
  70801. v.triangleCount++;
  70802. }
  70803. }
  70804. var tStart = 0;
  70805. for (i = 0; i < this.vertices.length; ++i) {
  70806. this.vertices[i].triangleStart = tStart;
  70807. tStart += this.vertices[i].triangleCount;
  70808. this.vertices[i].triangleCount = 0;
  70809. }
  70810. var newReferences = new Array(this.triangles.length * 3);
  70811. for (i = 0; i < this.triangles.length; ++i) {
  70812. t = this.triangles[i];
  70813. for (j = 0; j < 3; ++j) {
  70814. v = t.vertices[j];
  70815. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  70816. v.triangleCount++;
  70817. }
  70818. }
  70819. this.references = newReferences;
  70820. if (identifyBorders) {
  70821. this.identifyBorder();
  70822. }
  70823. };
  70824. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  70825. var x = point.x;
  70826. var y = point.y;
  70827. var z = point.z;
  70828. 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
  70829. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  70830. };
  70831. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  70832. var q = vertex1.q.add(vertex2.q);
  70833. var border = vertex1.isBorder && vertex2.isBorder;
  70834. var error = 0;
  70835. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  70836. if (qDet !== 0 && !border) {
  70837. if (!pointResult) {
  70838. pointResult = BABYLON.Vector3.Zero();
  70839. }
  70840. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  70841. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  70842. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  70843. error = this.vertexError(q, pointResult);
  70844. }
  70845. else {
  70846. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  70847. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  70848. var error1 = this.vertexError(q, vertex1.position);
  70849. var error2 = this.vertexError(q, vertex2.position);
  70850. var error3 = this.vertexError(q, p3);
  70851. error = Math.min(error1, error2, error3);
  70852. if (error === error1) {
  70853. if (pointResult) {
  70854. pointResult.copyFrom(vertex1.position);
  70855. }
  70856. }
  70857. else if (error === error2) {
  70858. if (pointResult) {
  70859. pointResult.copyFrom(vertex2.position);
  70860. }
  70861. }
  70862. else {
  70863. if (pointResult) {
  70864. pointResult.copyFrom(p3);
  70865. }
  70866. }
  70867. }
  70868. return error;
  70869. };
  70870. return QuadraticErrorSimplification;
  70871. }());
  70872. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  70873. })(BABYLON || (BABYLON = {}));
  70874. //# sourceMappingURL=babylon.meshSimplification.js.map
  70875. var BABYLON;
  70876. (function (BABYLON) {
  70877. var Internals;
  70878. (function (Internals) {
  70879. var MeshLODLevel = /** @class */ (function () {
  70880. function MeshLODLevel(distance, mesh) {
  70881. this.distance = distance;
  70882. this.mesh = mesh;
  70883. }
  70884. return MeshLODLevel;
  70885. }());
  70886. Internals.MeshLODLevel = MeshLODLevel;
  70887. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  70888. })(BABYLON || (BABYLON = {}));
  70889. //# sourceMappingURL=babylon.meshLODLevel.js.map
  70890. var BABYLON;
  70891. (function (BABYLON) {
  70892. // Standard optimizations
  70893. var SceneOptimization = /** @class */ (function () {
  70894. function SceneOptimization(priority) {
  70895. if (priority === void 0) { priority = 0; }
  70896. this.priority = priority;
  70897. this.apply = function (scene) {
  70898. return true; // Return true if everything that can be done was applied
  70899. };
  70900. }
  70901. return SceneOptimization;
  70902. }());
  70903. BABYLON.SceneOptimization = SceneOptimization;
  70904. var TextureOptimization = /** @class */ (function (_super) {
  70905. __extends(TextureOptimization, _super);
  70906. function TextureOptimization(priority, maximumSize) {
  70907. if (priority === void 0) { priority = 0; }
  70908. if (maximumSize === void 0) { maximumSize = 1024; }
  70909. var _this = _super.call(this, priority) || this;
  70910. _this.priority = priority;
  70911. _this.maximumSize = maximumSize;
  70912. _this.apply = function (scene) {
  70913. var allDone = true;
  70914. for (var index = 0; index < scene.textures.length; index++) {
  70915. var texture = scene.textures[index];
  70916. if (!texture.canRescale || texture.getContext) {
  70917. continue;
  70918. }
  70919. var currentSize = texture.getSize();
  70920. var maxDimension = Math.max(currentSize.width, currentSize.height);
  70921. if (maxDimension > _this.maximumSize) {
  70922. texture.scale(0.5);
  70923. allDone = false;
  70924. }
  70925. }
  70926. return allDone;
  70927. };
  70928. return _this;
  70929. }
  70930. return TextureOptimization;
  70931. }(SceneOptimization));
  70932. BABYLON.TextureOptimization = TextureOptimization;
  70933. var HardwareScalingOptimization = /** @class */ (function (_super) {
  70934. __extends(HardwareScalingOptimization, _super);
  70935. function HardwareScalingOptimization(priority, maximumScale) {
  70936. if (priority === void 0) { priority = 0; }
  70937. if (maximumScale === void 0) { maximumScale = 2; }
  70938. var _this = _super.call(this, priority) || this;
  70939. _this.priority = priority;
  70940. _this.maximumScale = maximumScale;
  70941. _this._currentScale = 1;
  70942. _this.apply = function (scene) {
  70943. _this._currentScale++;
  70944. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  70945. return _this._currentScale >= _this.maximumScale;
  70946. };
  70947. return _this;
  70948. }
  70949. return HardwareScalingOptimization;
  70950. }(SceneOptimization));
  70951. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  70952. var ShadowsOptimization = /** @class */ (function (_super) {
  70953. __extends(ShadowsOptimization, _super);
  70954. function ShadowsOptimization() {
  70955. var _this = _super !== null && _super.apply(this, arguments) || this;
  70956. _this.apply = function (scene) {
  70957. scene.shadowsEnabled = false;
  70958. return true;
  70959. };
  70960. return _this;
  70961. }
  70962. return ShadowsOptimization;
  70963. }(SceneOptimization));
  70964. BABYLON.ShadowsOptimization = ShadowsOptimization;
  70965. var PostProcessesOptimization = /** @class */ (function (_super) {
  70966. __extends(PostProcessesOptimization, _super);
  70967. function PostProcessesOptimization() {
  70968. var _this = _super !== null && _super.apply(this, arguments) || this;
  70969. _this.apply = function (scene) {
  70970. scene.postProcessesEnabled = false;
  70971. return true;
  70972. };
  70973. return _this;
  70974. }
  70975. return PostProcessesOptimization;
  70976. }(SceneOptimization));
  70977. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  70978. var LensFlaresOptimization = /** @class */ (function (_super) {
  70979. __extends(LensFlaresOptimization, _super);
  70980. function LensFlaresOptimization() {
  70981. var _this = _super !== null && _super.apply(this, arguments) || this;
  70982. _this.apply = function (scene) {
  70983. scene.lensFlaresEnabled = false;
  70984. return true;
  70985. };
  70986. return _this;
  70987. }
  70988. return LensFlaresOptimization;
  70989. }(SceneOptimization));
  70990. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  70991. var ParticlesOptimization = /** @class */ (function (_super) {
  70992. __extends(ParticlesOptimization, _super);
  70993. function ParticlesOptimization() {
  70994. var _this = _super !== null && _super.apply(this, arguments) || this;
  70995. _this.apply = function (scene) {
  70996. scene.particlesEnabled = false;
  70997. return true;
  70998. };
  70999. return _this;
  71000. }
  71001. return ParticlesOptimization;
  71002. }(SceneOptimization));
  71003. BABYLON.ParticlesOptimization = ParticlesOptimization;
  71004. var RenderTargetsOptimization = /** @class */ (function (_super) {
  71005. __extends(RenderTargetsOptimization, _super);
  71006. function RenderTargetsOptimization() {
  71007. var _this = _super !== null && _super.apply(this, arguments) || this;
  71008. _this.apply = function (scene) {
  71009. scene.renderTargetsEnabled = false;
  71010. return true;
  71011. };
  71012. return _this;
  71013. }
  71014. return RenderTargetsOptimization;
  71015. }(SceneOptimization));
  71016. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  71017. var MergeMeshesOptimization = /** @class */ (function (_super) {
  71018. __extends(MergeMeshesOptimization, _super);
  71019. function MergeMeshesOptimization() {
  71020. var _this = _super !== null && _super.apply(this, arguments) || this;
  71021. _this._canBeMerged = function (abstractMesh) {
  71022. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  71023. return false;
  71024. }
  71025. var mesh = abstractMesh;
  71026. if (!mesh.isVisible || !mesh.isEnabled()) {
  71027. return false;
  71028. }
  71029. if (mesh.instances.length > 0) {
  71030. return false;
  71031. }
  71032. if (mesh.skeleton || mesh.hasLODLevels) {
  71033. return false;
  71034. }
  71035. if (mesh.parent) {
  71036. return false;
  71037. }
  71038. return true;
  71039. };
  71040. _this.apply = function (scene, updateSelectionTree) {
  71041. var globalPool = scene.meshes.slice(0);
  71042. var globalLength = globalPool.length;
  71043. for (var index = 0; index < globalLength; index++) {
  71044. var currentPool = new Array();
  71045. var current = globalPool[index];
  71046. // Checks
  71047. if (!_this._canBeMerged(current)) {
  71048. continue;
  71049. }
  71050. currentPool.push(current);
  71051. // Find compatible meshes
  71052. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  71053. var otherMesh = globalPool[subIndex];
  71054. if (!_this._canBeMerged(otherMesh)) {
  71055. continue;
  71056. }
  71057. if (otherMesh.material !== current.material) {
  71058. continue;
  71059. }
  71060. if (otherMesh.checkCollisions !== current.checkCollisions) {
  71061. continue;
  71062. }
  71063. currentPool.push(otherMesh);
  71064. globalLength--;
  71065. globalPool.splice(subIndex, 1);
  71066. subIndex--;
  71067. }
  71068. if (currentPool.length < 2) {
  71069. continue;
  71070. }
  71071. // Merge meshes
  71072. BABYLON.Mesh.MergeMeshes(currentPool);
  71073. }
  71074. if (updateSelectionTree != undefined) {
  71075. if (updateSelectionTree) {
  71076. scene.createOrUpdateSelectionOctree();
  71077. }
  71078. }
  71079. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  71080. scene.createOrUpdateSelectionOctree();
  71081. }
  71082. return true;
  71083. };
  71084. return _this;
  71085. }
  71086. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  71087. get: function () {
  71088. return MergeMeshesOptimization._UpdateSelectionTree;
  71089. },
  71090. set: function (value) {
  71091. MergeMeshesOptimization._UpdateSelectionTree = value;
  71092. },
  71093. enumerable: true,
  71094. configurable: true
  71095. });
  71096. MergeMeshesOptimization._UpdateSelectionTree = false;
  71097. return MergeMeshesOptimization;
  71098. }(SceneOptimization));
  71099. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  71100. // Options
  71101. var SceneOptimizerOptions = /** @class */ (function () {
  71102. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  71103. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  71104. if (trackerDuration === void 0) { trackerDuration = 2000; }
  71105. this.targetFrameRate = targetFrameRate;
  71106. this.trackerDuration = trackerDuration;
  71107. this.optimizations = new Array();
  71108. }
  71109. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  71110. var result = new SceneOptimizerOptions(targetFrameRate);
  71111. var priority = 0;
  71112. result.optimizations.push(new MergeMeshesOptimization(priority));
  71113. result.optimizations.push(new ShadowsOptimization(priority));
  71114. result.optimizations.push(new LensFlaresOptimization(priority));
  71115. // Next priority
  71116. priority++;
  71117. result.optimizations.push(new PostProcessesOptimization(priority));
  71118. result.optimizations.push(new ParticlesOptimization(priority));
  71119. // Next priority
  71120. priority++;
  71121. result.optimizations.push(new TextureOptimization(priority, 1024));
  71122. return result;
  71123. };
  71124. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  71125. var result = new SceneOptimizerOptions(targetFrameRate);
  71126. var priority = 0;
  71127. result.optimizations.push(new MergeMeshesOptimization(priority));
  71128. result.optimizations.push(new ShadowsOptimization(priority));
  71129. result.optimizations.push(new LensFlaresOptimization(priority));
  71130. // Next priority
  71131. priority++;
  71132. result.optimizations.push(new PostProcessesOptimization(priority));
  71133. result.optimizations.push(new ParticlesOptimization(priority));
  71134. // Next priority
  71135. priority++;
  71136. result.optimizations.push(new TextureOptimization(priority, 512));
  71137. // Next priority
  71138. priority++;
  71139. result.optimizations.push(new RenderTargetsOptimization(priority));
  71140. // Next priority
  71141. priority++;
  71142. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  71143. return result;
  71144. };
  71145. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  71146. var result = new SceneOptimizerOptions(targetFrameRate);
  71147. var priority = 0;
  71148. result.optimizations.push(new MergeMeshesOptimization(priority));
  71149. result.optimizations.push(new ShadowsOptimization(priority));
  71150. result.optimizations.push(new LensFlaresOptimization(priority));
  71151. // Next priority
  71152. priority++;
  71153. result.optimizations.push(new PostProcessesOptimization(priority));
  71154. result.optimizations.push(new ParticlesOptimization(priority));
  71155. // Next priority
  71156. priority++;
  71157. result.optimizations.push(new TextureOptimization(priority, 256));
  71158. // Next priority
  71159. priority++;
  71160. result.optimizations.push(new RenderTargetsOptimization(priority));
  71161. // Next priority
  71162. priority++;
  71163. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  71164. return result;
  71165. };
  71166. return SceneOptimizerOptions;
  71167. }());
  71168. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  71169. // Scene optimizer tool
  71170. var SceneOptimizer = /** @class */ (function () {
  71171. function SceneOptimizer() {
  71172. }
  71173. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  71174. // TODO: add an epsilon
  71175. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  71176. if (onSuccess) {
  71177. onSuccess();
  71178. }
  71179. return;
  71180. }
  71181. // Apply current level of optimizations
  71182. var allDone = true;
  71183. var noOptimizationApplied = true;
  71184. for (var index = 0; index < options.optimizations.length; index++) {
  71185. var optimization = options.optimizations[index];
  71186. if (optimization.priority === currentPriorityLevel) {
  71187. noOptimizationApplied = false;
  71188. allDone = allDone && optimization.apply(scene);
  71189. }
  71190. }
  71191. // If no optimization was applied, this is a failure :(
  71192. if (noOptimizationApplied) {
  71193. if (onFailure) {
  71194. onFailure();
  71195. }
  71196. return;
  71197. }
  71198. // If all optimizations were done, move to next level
  71199. if (allDone) {
  71200. currentPriorityLevel++;
  71201. }
  71202. // Let's the system running for a specific amount of time before checking FPS
  71203. scene.executeWhenReady(function () {
  71204. setTimeout(function () {
  71205. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  71206. }, options.trackerDuration);
  71207. });
  71208. };
  71209. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  71210. if (!options) {
  71211. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  71212. }
  71213. // Let's the system running for a specific amount of time before checking FPS
  71214. scene.executeWhenReady(function () {
  71215. setTimeout(function () {
  71216. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  71217. }, options.trackerDuration);
  71218. });
  71219. };
  71220. return SceneOptimizer;
  71221. }());
  71222. BABYLON.SceneOptimizer = SceneOptimizer;
  71223. })(BABYLON || (BABYLON = {}));
  71224. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  71225. var BABYLON;
  71226. (function (BABYLON) {
  71227. var OutlineRenderer = /** @class */ (function () {
  71228. function OutlineRenderer(scene) {
  71229. this.zOffset = 1;
  71230. this._scene = scene;
  71231. }
  71232. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  71233. var _this = this;
  71234. if (useOverlay === void 0) { useOverlay = false; }
  71235. var scene = this._scene;
  71236. var engine = this._scene.getEngine();
  71237. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71238. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  71239. return;
  71240. }
  71241. var mesh = subMesh.getRenderingMesh();
  71242. var material = subMesh.getMaterial();
  71243. if (!material || !scene.activeCamera) {
  71244. return;
  71245. }
  71246. engine.enableEffect(this._effect);
  71247. // Logarithmic depth
  71248. if (material.useLogarithmicDepth) {
  71249. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  71250. }
  71251. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  71252. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  71253. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71254. // Bones
  71255. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71256. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71257. }
  71258. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71259. // Alpha test
  71260. if (material && material.needAlphaTesting()) {
  71261. var alphaTexture = material.getAlphaTestTexture();
  71262. if (alphaTexture) {
  71263. this._effect.setTexture("diffuseSampler", alphaTexture);
  71264. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71265. }
  71266. }
  71267. engine.setZOffset(-this.zOffset);
  71268. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  71269. engine.setZOffset(0);
  71270. };
  71271. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  71272. var defines = [];
  71273. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71274. var mesh = subMesh.getMesh();
  71275. var material = subMesh.getMaterial();
  71276. if (material) {
  71277. // Alpha test
  71278. if (material.needAlphaTesting()) {
  71279. defines.push("#define ALPHATEST");
  71280. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71281. attribs.push(BABYLON.VertexBuffer.UVKind);
  71282. defines.push("#define UV1");
  71283. }
  71284. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71285. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71286. defines.push("#define UV2");
  71287. }
  71288. }
  71289. //Logarithmic depth
  71290. if (material.useLogarithmicDepth) {
  71291. defines.push("#define LOGARITHMICDEPTH");
  71292. }
  71293. }
  71294. // Bones
  71295. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71296. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71297. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71298. if (mesh.numBoneInfluencers > 4) {
  71299. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71300. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71301. }
  71302. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71303. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71304. }
  71305. else {
  71306. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71307. }
  71308. // Instances
  71309. if (useInstances) {
  71310. defines.push("#define INSTANCES");
  71311. attribs.push("world0");
  71312. attribs.push("world1");
  71313. attribs.push("world2");
  71314. attribs.push("world3");
  71315. }
  71316. // Get correct effect
  71317. var join = defines.join("\n");
  71318. if (this._cachedDefines !== join) {
  71319. this._cachedDefines = join;
  71320. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  71321. }
  71322. return this._effect.isReady();
  71323. };
  71324. return OutlineRenderer;
  71325. }());
  71326. BABYLON.OutlineRenderer = OutlineRenderer;
  71327. })(BABYLON || (BABYLON = {}));
  71328. //# sourceMappingURL=babylon.outlineRenderer.js.map
  71329. var BABYLON;
  71330. (function (BABYLON) {
  71331. var FaceAdjacencies = /** @class */ (function () {
  71332. function FaceAdjacencies() {
  71333. this.edges = new Array();
  71334. this.edgesConnectedCount = 0;
  71335. }
  71336. return FaceAdjacencies;
  71337. }());
  71338. var EdgesRenderer = /** @class */ (function () {
  71339. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  71340. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  71341. if (epsilon === void 0) { epsilon = 0.95; }
  71342. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  71343. this.edgesWidthScalerForOrthographic = 1000.0;
  71344. this.edgesWidthScalerForPerspective = 50.0;
  71345. this._linesPositions = new Array();
  71346. this._linesNormals = new Array();
  71347. this._linesIndices = new Array();
  71348. this._buffers = {};
  71349. this._checkVerticesInsteadOfIndices = false;
  71350. this._source = source;
  71351. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  71352. this._epsilon = epsilon;
  71353. this._prepareRessources();
  71354. this._generateEdgesLines();
  71355. }
  71356. EdgesRenderer.prototype._prepareRessources = function () {
  71357. if (this._lineShader) {
  71358. return;
  71359. }
  71360. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  71361. attributes: ["position", "normal"],
  71362. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  71363. });
  71364. this._lineShader.disableDepthWrite = true;
  71365. this._lineShader.backFaceCulling = false;
  71366. };
  71367. EdgesRenderer.prototype._rebuild = function () {
  71368. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71369. if (buffer) {
  71370. buffer._rebuild();
  71371. }
  71372. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71373. if (buffer) {
  71374. buffer._rebuild();
  71375. }
  71376. var scene = this._source.getScene();
  71377. var engine = scene.getEngine();
  71378. this._ib = engine.createIndexBuffer(this._linesIndices);
  71379. };
  71380. EdgesRenderer.prototype.dispose = function () {
  71381. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71382. if (buffer) {
  71383. buffer.dispose();
  71384. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  71385. }
  71386. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71387. if (buffer) {
  71388. buffer.dispose();
  71389. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  71390. }
  71391. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  71392. this._lineShader.dispose();
  71393. };
  71394. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  71395. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  71396. return 0;
  71397. }
  71398. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  71399. return 1;
  71400. }
  71401. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  71402. return 2;
  71403. }
  71404. return -1;
  71405. };
  71406. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  71407. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  71408. return 0;
  71409. }
  71410. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  71411. return 1;
  71412. }
  71413. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  71414. return 2;
  71415. }
  71416. return -1;
  71417. };
  71418. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  71419. var needToCreateLine;
  71420. if (edge === undefined) {
  71421. needToCreateLine = true;
  71422. }
  71423. else {
  71424. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  71425. needToCreateLine = dotProduct < this._epsilon;
  71426. }
  71427. if (needToCreateLine) {
  71428. var offset = this._linesPositions.length / 3;
  71429. var normal = p0.subtract(p1);
  71430. normal.normalize();
  71431. // Positions
  71432. this._linesPositions.push(p0.x);
  71433. this._linesPositions.push(p0.y);
  71434. this._linesPositions.push(p0.z);
  71435. this._linesPositions.push(p0.x);
  71436. this._linesPositions.push(p0.y);
  71437. this._linesPositions.push(p0.z);
  71438. this._linesPositions.push(p1.x);
  71439. this._linesPositions.push(p1.y);
  71440. this._linesPositions.push(p1.z);
  71441. this._linesPositions.push(p1.x);
  71442. this._linesPositions.push(p1.y);
  71443. this._linesPositions.push(p1.z);
  71444. // Normals
  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(p1.x);
  71450. this._linesNormals.push(p1.y);
  71451. this._linesNormals.push(p1.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. this._linesNormals.push(p0.x);
  71458. this._linesNormals.push(p0.y);
  71459. this._linesNormals.push(p0.z);
  71460. this._linesNormals.push(1);
  71461. // Indices
  71462. this._linesIndices.push(offset);
  71463. this._linesIndices.push(offset + 1);
  71464. this._linesIndices.push(offset + 2);
  71465. this._linesIndices.push(offset);
  71466. this._linesIndices.push(offset + 2);
  71467. this._linesIndices.push(offset + 3);
  71468. }
  71469. };
  71470. EdgesRenderer.prototype._generateEdgesLines = function () {
  71471. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71472. var indices = this._source.getIndices();
  71473. if (!indices || !positions) {
  71474. return;
  71475. }
  71476. // First let's find adjacencies
  71477. var adjacencies = new Array();
  71478. var faceNormals = new Array();
  71479. var index;
  71480. var faceAdjacencies;
  71481. // Prepare faces
  71482. for (index = 0; index < indices.length; index += 3) {
  71483. faceAdjacencies = new FaceAdjacencies();
  71484. var p0Index = indices[index];
  71485. var p1Index = indices[index + 1];
  71486. var p2Index = indices[index + 2];
  71487. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  71488. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  71489. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  71490. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  71491. faceNormal.normalize();
  71492. faceNormals.push(faceNormal);
  71493. adjacencies.push(faceAdjacencies);
  71494. }
  71495. // Scan
  71496. for (index = 0; index < adjacencies.length; index++) {
  71497. faceAdjacencies = adjacencies[index];
  71498. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  71499. var otherFaceAdjacencies = adjacencies[otherIndex];
  71500. if (faceAdjacencies.edgesConnectedCount === 3) {
  71501. break;
  71502. }
  71503. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  71504. continue;
  71505. }
  71506. var otherP0 = indices[otherIndex * 3];
  71507. var otherP1 = indices[otherIndex * 3 + 1];
  71508. var otherP2 = indices[otherIndex * 3 + 2];
  71509. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  71510. var otherEdgeIndex = 0;
  71511. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  71512. continue;
  71513. }
  71514. switch (edgeIndex) {
  71515. case 0:
  71516. if (this._checkVerticesInsteadOfIndices) {
  71517. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71518. }
  71519. else {
  71520. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  71521. }
  71522. break;
  71523. case 1:
  71524. if (this._checkVerticesInsteadOfIndices) {
  71525. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71526. }
  71527. else {
  71528. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  71529. }
  71530. break;
  71531. case 2:
  71532. if (this._checkVerticesInsteadOfIndices) {
  71533. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71534. }
  71535. else {
  71536. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  71537. }
  71538. break;
  71539. }
  71540. if (otherEdgeIndex === -1) {
  71541. continue;
  71542. }
  71543. faceAdjacencies.edges[edgeIndex] = otherIndex;
  71544. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  71545. faceAdjacencies.edgesConnectedCount++;
  71546. otherFaceAdjacencies.edgesConnectedCount++;
  71547. if (faceAdjacencies.edgesConnectedCount === 3) {
  71548. break;
  71549. }
  71550. }
  71551. }
  71552. }
  71553. // Create lines
  71554. for (index = 0; index < adjacencies.length; index++) {
  71555. // 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
  71556. var current = adjacencies[index];
  71557. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  71558. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  71559. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  71560. }
  71561. // Merge into a single mesh
  71562. var engine = this._source.getScene().getEngine();
  71563. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  71564. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  71565. this._ib = engine.createIndexBuffer(this._linesIndices);
  71566. this._indicesCount = this._linesIndices.length;
  71567. };
  71568. EdgesRenderer.prototype.render = function () {
  71569. var scene = this._source.getScene();
  71570. if (!this._lineShader.isReady() || !scene.activeCamera) {
  71571. return;
  71572. }
  71573. var engine = scene.getEngine();
  71574. this._lineShader._preBind();
  71575. // VBOs
  71576. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  71577. scene.resetCachedMaterial();
  71578. this._lineShader.setColor4("color", this._source.edgesColor);
  71579. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  71580. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  71581. }
  71582. else {
  71583. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  71584. }
  71585. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  71586. this._lineShader.bind(this._source.getWorldMatrix());
  71587. // Draw order
  71588. engine.draw(true, 0, this._indicesCount);
  71589. this._lineShader.unbind();
  71590. engine.setDepthWrite(true);
  71591. };
  71592. return EdgesRenderer;
  71593. }());
  71594. BABYLON.EdgesRenderer = EdgesRenderer;
  71595. })(BABYLON || (BABYLON = {}));
  71596. //# sourceMappingURL=babylon.edgesRenderer.js.map
  71597. var BABYLON;
  71598. (function (BABYLON) {
  71599. /**
  71600. * Special Glow Blur post process only blurring the alpha channel
  71601. * It enforces keeping the most luminous color in the color channel.
  71602. */
  71603. var GlowBlurPostProcess = /** @class */ (function (_super) {
  71604. __extends(GlowBlurPostProcess, _super);
  71605. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  71606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71607. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  71608. _this.direction = direction;
  71609. _this.kernel = kernel;
  71610. _this.onApplyObservable.add(function (effect) {
  71611. effect.setFloat2("screenSize", _this.width, _this.height);
  71612. effect.setVector2("direction", _this.direction);
  71613. effect.setFloat("blurWidth", _this.kernel);
  71614. });
  71615. return _this;
  71616. }
  71617. return GlowBlurPostProcess;
  71618. }(BABYLON.PostProcess));
  71619. /**
  71620. * The highlight layer Helps adding a glow effect around a mesh.
  71621. *
  71622. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  71623. * glowy meshes to your scene.
  71624. *
  71625. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  71626. */
  71627. var HighlightLayer = /** @class */ (function () {
  71628. /**
  71629. * Instantiates a new highlight Layer and references it to the scene..
  71630. * @param name The name of the layer
  71631. * @param scene The scene to use the layer in
  71632. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  71633. */
  71634. function HighlightLayer(name, scene, options) {
  71635. this.name = name;
  71636. this._vertexBuffers = {};
  71637. this._mainTextureDesiredSize = { width: 0, height: 0 };
  71638. this._meshes = {};
  71639. this._maxSize = 0;
  71640. this._shouldRender = false;
  71641. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  71642. this._excludedMeshes = {};
  71643. /**
  71644. * Specifies whether or not the inner glow is ACTIVE in the layer.
  71645. */
  71646. this.innerGlow = true;
  71647. /**
  71648. * Specifies whether or not the outer glow is ACTIVE in the layer.
  71649. */
  71650. this.outerGlow = true;
  71651. /**
  71652. * Specifies wether the highlight layer is enabled or not.
  71653. */
  71654. this.isEnabled = true;
  71655. /**
  71656. * An event triggered when the highlight layer has been disposed.
  71657. * @type {BABYLON.Observable}
  71658. */
  71659. this.onDisposeObservable = new BABYLON.Observable();
  71660. /**
  71661. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  71662. * @type {BABYLON.Observable}
  71663. */
  71664. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  71665. /**
  71666. * An event triggered when the highlight layer is being blurred.
  71667. * @type {BABYLON.Observable}
  71668. */
  71669. this.onBeforeBlurObservable = new BABYLON.Observable();
  71670. /**
  71671. * An event triggered when the highlight layer has been blurred.
  71672. * @type {BABYLON.Observable}
  71673. */
  71674. this.onAfterBlurObservable = new BABYLON.Observable();
  71675. /**
  71676. * An event triggered when the glowing blurred texture is being merged in the scene.
  71677. * @type {BABYLON.Observable}
  71678. */
  71679. this.onBeforeComposeObservable = new BABYLON.Observable();
  71680. /**
  71681. * An event triggered when the glowing blurred texture has been merged in the scene.
  71682. * @type {BABYLON.Observable}
  71683. */
  71684. this.onAfterComposeObservable = new BABYLON.Observable();
  71685. /**
  71686. * An event triggered when the highlight layer changes its size.
  71687. * @type {BABYLON.Observable}
  71688. */
  71689. this.onSizeChangedObservable = new BABYLON.Observable();
  71690. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71691. var engine = scene.getEngine();
  71692. this._engine = engine;
  71693. this._maxSize = this._engine.getCaps().maxTextureSize;
  71694. this._scene.highlightLayers.push(this);
  71695. // Warn on stencil.
  71696. if (!this._engine.isStencilEnable) {
  71697. 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 }");
  71698. }
  71699. // Adapt options
  71700. this._options = options || {
  71701. mainTextureRatio: 0.5,
  71702. blurTextureSizeRatio: 0.5,
  71703. blurHorizontalSize: 1.0,
  71704. blurVerticalSize: 1.0,
  71705. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  71706. camera: null
  71707. };
  71708. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  71709. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  71710. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  71711. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  71712. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  71713. // VBO
  71714. var vertices = [];
  71715. vertices.push(1, 1);
  71716. vertices.push(-1, 1);
  71717. vertices.push(-1, -1);
  71718. vertices.push(1, -1);
  71719. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71720. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71721. this._createIndexBuffer();
  71722. // Effect
  71723. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  71724. // Render target
  71725. this.setMainTextureSize();
  71726. // Create Textures and post processes
  71727. this.createTextureAndPostProcesses();
  71728. }
  71729. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  71730. /**
  71731. * Gets the horizontal size of the blur.
  71732. */
  71733. get: function () {
  71734. return this._horizontalBlurPostprocess.kernel;
  71735. },
  71736. /**
  71737. * Specifies the horizontal size of the blur.
  71738. */
  71739. set: function (value) {
  71740. this._horizontalBlurPostprocess.kernel = value;
  71741. },
  71742. enumerable: true,
  71743. configurable: true
  71744. });
  71745. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  71746. /**
  71747. * Gets the vertical size of the blur.
  71748. */
  71749. get: function () {
  71750. return this._verticalBlurPostprocess.kernel;
  71751. },
  71752. /**
  71753. * Specifies the vertical size of the blur.
  71754. */
  71755. set: function (value) {
  71756. this._verticalBlurPostprocess.kernel = value;
  71757. },
  71758. enumerable: true,
  71759. configurable: true
  71760. });
  71761. Object.defineProperty(HighlightLayer.prototype, "camera", {
  71762. /**
  71763. * Gets the camera attached to the layer.
  71764. */
  71765. get: function () {
  71766. return this._options.camera;
  71767. },
  71768. enumerable: true,
  71769. configurable: true
  71770. });
  71771. HighlightLayer.prototype._createIndexBuffer = function () {
  71772. var engine = this._scene.getEngine();
  71773. // Indices
  71774. var indices = [];
  71775. indices.push(0);
  71776. indices.push(1);
  71777. indices.push(2);
  71778. indices.push(0);
  71779. indices.push(2);
  71780. indices.push(3);
  71781. this._indexBuffer = engine.createIndexBuffer(indices);
  71782. };
  71783. HighlightLayer.prototype._rebuild = function () {
  71784. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71785. if (vb) {
  71786. vb._rebuild();
  71787. }
  71788. this._createIndexBuffer();
  71789. };
  71790. /**
  71791. * Creates the render target textures and post processes used in the highlight layer.
  71792. */
  71793. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  71794. var _this = this;
  71795. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  71796. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  71797. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  71798. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  71799. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  71800. width: this._mainTextureDesiredSize.width,
  71801. height: this._mainTextureDesiredSize.height
  71802. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71803. this._mainTexture.activeCamera = this._options.camera;
  71804. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71805. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71806. this._mainTexture.anisotropicFilteringLevel = 1;
  71807. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71808. this._mainTexture.renderParticles = false;
  71809. this._mainTexture.renderList = null;
  71810. this._mainTexture.ignoreCameraViewport = true;
  71811. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  71812. width: blurTextureWidth,
  71813. height: blurTextureHeight
  71814. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71815. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71816. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71817. this._blurTexture.anisotropicFilteringLevel = 16;
  71818. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71819. this._blurTexture.renderParticles = false;
  71820. this._blurTexture.ignoreCameraViewport = true;
  71821. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71822. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  71823. effect.setTexture("textureSampler", _this._mainTexture);
  71824. });
  71825. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  71826. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71827. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  71828. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71829. });
  71830. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71831. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  71832. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71833. });
  71834. }
  71835. else {
  71836. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71837. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  71838. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71839. });
  71840. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71841. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  71842. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71843. });
  71844. }
  71845. this._mainTexture.onAfterUnbindObservable.add(function () {
  71846. _this.onBeforeBlurObservable.notifyObservers(_this);
  71847. var internalTexture = _this._blurTexture.getInternalTexture();
  71848. if (internalTexture) {
  71849. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  71850. }
  71851. _this.onAfterBlurObservable.notifyObservers(_this);
  71852. });
  71853. // Custom render function
  71854. var renderSubMesh = function (subMesh) {
  71855. if (!_this._meshes) {
  71856. return;
  71857. }
  71858. var material = subMesh.getMaterial();
  71859. var mesh = subMesh.getRenderingMesh();
  71860. var scene = _this._scene;
  71861. var engine = scene.getEngine();
  71862. if (!material) {
  71863. return;
  71864. }
  71865. // Culling
  71866. engine.setState(material.backFaceCulling);
  71867. // Managing instances
  71868. var batch = mesh._getInstancesRenderList(subMesh._id);
  71869. if (batch.mustReturn) {
  71870. return;
  71871. }
  71872. // Excluded Mesh
  71873. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  71874. return;
  71875. }
  71876. ;
  71877. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71878. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  71879. var emissiveTexture = null;
  71880. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  71881. emissiveTexture = material.emissiveTexture;
  71882. }
  71883. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  71884. engine.enableEffect(_this._glowMapGenerationEffect);
  71885. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  71886. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  71887. if (highlightLayerMesh) {
  71888. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  71889. }
  71890. else {
  71891. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  71892. }
  71893. // Alpha test
  71894. if (material && material.needAlphaTesting()) {
  71895. var alphaTexture = material.getAlphaTestTexture();
  71896. if (alphaTexture) {
  71897. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  71898. var textureMatrix = alphaTexture.getTextureMatrix();
  71899. if (textureMatrix) {
  71900. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  71901. }
  71902. }
  71903. }
  71904. // Glow emissive only
  71905. if (emissiveTexture) {
  71906. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  71907. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  71908. }
  71909. // Bones
  71910. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71911. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71912. }
  71913. // Draw
  71914. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  71915. }
  71916. else {
  71917. // Need to reset refresh rate of the shadowMap
  71918. _this._mainTexture.resetRefreshCounter();
  71919. }
  71920. };
  71921. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71922. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  71923. var index;
  71924. var engine = _this._scene.getEngine();
  71925. if (depthOnlySubMeshes.length) {
  71926. engine.setColorWrite(false);
  71927. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71928. renderSubMesh(depthOnlySubMeshes.data[index]);
  71929. }
  71930. engine.setColorWrite(true);
  71931. }
  71932. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71933. renderSubMesh(opaqueSubMeshes.data[index]);
  71934. }
  71935. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71936. renderSubMesh(alphaTestSubMeshes.data[index]);
  71937. }
  71938. for (index = 0; index < transparentSubMeshes.length; index++) {
  71939. renderSubMesh(transparentSubMeshes.data[index]);
  71940. }
  71941. };
  71942. this._mainTexture.onClearObservable.add(function (engine) {
  71943. engine.clear(HighlightLayer.neutralColor, true, true, true);
  71944. });
  71945. };
  71946. /**
  71947. * Checks for the readiness of the element composing the layer.
  71948. * @param subMesh the mesh to check for
  71949. * @param useInstances specify wether or not to use instances to render the mesh
  71950. * @param emissiveTexture the associated emissive texture used to generate the glow
  71951. * @return true if ready otherwise, false
  71952. */
  71953. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  71954. var material = subMesh.getMaterial();
  71955. if (!material) {
  71956. return false;
  71957. }
  71958. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  71959. return false;
  71960. }
  71961. var defines = [];
  71962. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71963. var mesh = subMesh.getMesh();
  71964. var uv1 = false;
  71965. var uv2 = false;
  71966. // Alpha test
  71967. if (material && material.needAlphaTesting()) {
  71968. var alphaTexture = material.getAlphaTestTexture();
  71969. if (alphaTexture) {
  71970. defines.push("#define ALPHATEST");
  71971. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  71972. alphaTexture.coordinatesIndex === 1) {
  71973. defines.push("#define DIFFUSEUV2");
  71974. uv2 = true;
  71975. }
  71976. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71977. defines.push("#define DIFFUSEUV1");
  71978. uv1 = true;
  71979. }
  71980. }
  71981. }
  71982. // Emissive
  71983. if (emissiveTexture) {
  71984. defines.push("#define EMISSIVE");
  71985. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  71986. emissiveTexture.coordinatesIndex === 1) {
  71987. defines.push("#define EMISSIVEUV2");
  71988. uv2 = true;
  71989. }
  71990. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71991. defines.push("#define EMISSIVEUV1");
  71992. uv1 = true;
  71993. }
  71994. }
  71995. if (uv1) {
  71996. attribs.push(BABYLON.VertexBuffer.UVKind);
  71997. defines.push("#define UV1");
  71998. }
  71999. if (uv2) {
  72000. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72001. defines.push("#define UV2");
  72002. }
  72003. // Bones
  72004. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72005. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72006. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72007. if (mesh.numBoneInfluencers > 4) {
  72008. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72009. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72010. }
  72011. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72012. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72013. }
  72014. else {
  72015. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72016. }
  72017. // Instances
  72018. if (useInstances) {
  72019. defines.push("#define INSTANCES");
  72020. attribs.push("world0");
  72021. attribs.push("world1");
  72022. attribs.push("world2");
  72023. attribs.push("world3");
  72024. }
  72025. // Get correct effect
  72026. var join = defines.join("\n");
  72027. if (this._cachedDefines !== join) {
  72028. this._cachedDefines = join;
  72029. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  72030. }
  72031. return this._glowMapGenerationEffect.isReady();
  72032. };
  72033. /**
  72034. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  72035. */
  72036. HighlightLayer.prototype.render = function () {
  72037. var currentEffect = this._glowMapMergeEffect;
  72038. // Check
  72039. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  72040. return;
  72041. var engine = this._scene.getEngine();
  72042. this.onBeforeComposeObservable.notifyObservers(this);
  72043. // Render
  72044. engine.enableEffect(currentEffect);
  72045. engine.setState(false);
  72046. // Cache
  72047. var previousStencilBuffer = engine.getStencilBuffer();
  72048. var previousStencilFunction = engine.getStencilFunction();
  72049. var previousStencilMask = engine.getStencilMask();
  72050. var previousStencilOperationPass = engine.getStencilOperationPass();
  72051. var previousStencilOperationFail = engine.getStencilOperationFail();
  72052. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  72053. var previousAlphaMode = engine.getAlphaMode();
  72054. // Texture
  72055. currentEffect.setTexture("textureSampler", this._blurTexture);
  72056. // VBOs
  72057. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72058. // Stencil operations
  72059. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  72060. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  72061. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  72062. // Draw order
  72063. engine.setAlphaMode(this._options.alphaBlendingMode);
  72064. engine.setStencilMask(0x00);
  72065. engine.setStencilBuffer(true);
  72066. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  72067. if (this.outerGlow) {
  72068. currentEffect.setFloat("offset", 0);
  72069. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  72070. engine.draw(true, 0, 6);
  72071. }
  72072. if (this.innerGlow) {
  72073. currentEffect.setFloat("offset", 1);
  72074. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  72075. engine.draw(true, 0, 6);
  72076. }
  72077. // Restore Cache
  72078. engine.setStencilFunction(previousStencilFunction);
  72079. engine.setStencilMask(previousStencilMask);
  72080. engine.setAlphaMode(previousAlphaMode);
  72081. engine.setStencilBuffer(previousStencilBuffer);
  72082. engine.setStencilOperationPass(previousStencilOperationPass);
  72083. engine.setStencilOperationFail(previousStencilOperationFail);
  72084. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  72085. engine._stencilState.reset();
  72086. this.onAfterComposeObservable.notifyObservers(this);
  72087. // Handle size changes.
  72088. var size = this._mainTexture.getSize();
  72089. this.setMainTextureSize();
  72090. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  72091. // Recreate RTT and post processes on size change.
  72092. this.onSizeChangedObservable.notifyObservers(this);
  72093. this.disposeTextureAndPostProcesses();
  72094. this.createTextureAndPostProcesses();
  72095. }
  72096. };
  72097. /**
  72098. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  72099. * @param mesh The mesh to exclude from the highlight layer
  72100. */
  72101. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  72102. if (!this._excludedMeshes) {
  72103. return;
  72104. }
  72105. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72106. if (!meshExcluded) {
  72107. this._excludedMeshes[mesh.uniqueId] = {
  72108. mesh: mesh,
  72109. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  72110. mesh.getEngine().setStencilBuffer(false);
  72111. }),
  72112. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  72113. mesh.getEngine().setStencilBuffer(true);
  72114. }),
  72115. };
  72116. }
  72117. };
  72118. /**
  72119. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  72120. * @param mesh The mesh to highlight
  72121. */
  72122. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  72123. if (!this._excludedMeshes) {
  72124. return;
  72125. }
  72126. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72127. if (meshExcluded) {
  72128. if (meshExcluded.beforeRender) {
  72129. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  72130. }
  72131. if (meshExcluded.afterRender) {
  72132. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  72133. }
  72134. }
  72135. this._excludedMeshes[mesh.uniqueId] = null;
  72136. };
  72137. /**
  72138. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  72139. * @param mesh The mesh to highlight
  72140. * @param color The color of the highlight
  72141. * @param glowEmissiveOnly Extract the glow from the emissive texture
  72142. */
  72143. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  72144. var _this = this;
  72145. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  72146. if (!this._meshes) {
  72147. return;
  72148. }
  72149. var meshHighlight = this._meshes[mesh.uniqueId];
  72150. if (meshHighlight) {
  72151. meshHighlight.color = color;
  72152. }
  72153. else {
  72154. this._meshes[mesh.uniqueId] = {
  72155. mesh: mesh,
  72156. color: color,
  72157. // Lambda required for capture due to Observable this context
  72158. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  72159. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72160. _this.defaultStencilReference(mesh);
  72161. }
  72162. else {
  72163. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  72164. }
  72165. }),
  72166. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  72167. glowEmissiveOnly: glowEmissiveOnly
  72168. };
  72169. }
  72170. this._shouldRender = true;
  72171. };
  72172. /**
  72173. * Remove a mesh from the highlight layer in order to make it stop glowing.
  72174. * @param mesh The mesh to highlight
  72175. */
  72176. HighlightLayer.prototype.removeMesh = function (mesh) {
  72177. if (!this._meshes) {
  72178. return;
  72179. }
  72180. var meshHighlight = this._meshes[mesh.uniqueId];
  72181. if (meshHighlight) {
  72182. if (meshHighlight.observerHighlight) {
  72183. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72184. }
  72185. if (meshHighlight.observerDefault) {
  72186. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72187. }
  72188. }
  72189. this._meshes[mesh.uniqueId] = null;
  72190. this._shouldRender = false;
  72191. for (var meshHighlightToCheck in this._meshes) {
  72192. if (meshHighlightToCheck) {
  72193. this._shouldRender = true;
  72194. break;
  72195. }
  72196. }
  72197. };
  72198. /**
  72199. * Returns true if the layer contains information to display, otherwise false.
  72200. */
  72201. HighlightLayer.prototype.shouldRender = function () {
  72202. return this.isEnabled && this._shouldRender;
  72203. };
  72204. /**
  72205. * Sets the main texture desired size which is the closest power of two
  72206. * of the engine canvas size.
  72207. */
  72208. HighlightLayer.prototype.setMainTextureSize = function () {
  72209. if (this._options.mainTextureFixedSize) {
  72210. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  72211. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  72212. }
  72213. else {
  72214. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  72215. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  72216. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  72217. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  72218. }
  72219. };
  72220. /**
  72221. * Force the stencil to the normal expected value for none glowing parts
  72222. */
  72223. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  72224. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  72225. };
  72226. /**
  72227. * Dispose only the render target textures and post process.
  72228. */
  72229. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  72230. this._blurTexture.dispose();
  72231. this._mainTexture.dispose();
  72232. this._downSamplePostprocess.dispose();
  72233. this._horizontalBlurPostprocess.dispose();
  72234. this._verticalBlurPostprocess.dispose();
  72235. };
  72236. /**
  72237. * Dispose the highlight layer and free resources.
  72238. */
  72239. HighlightLayer.prototype.dispose = function () {
  72240. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72241. if (vertexBuffer) {
  72242. vertexBuffer.dispose();
  72243. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72244. }
  72245. if (this._indexBuffer) {
  72246. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72247. this._indexBuffer = null;
  72248. }
  72249. // Clean textures and post processes
  72250. this.disposeTextureAndPostProcesses();
  72251. if (this._meshes) {
  72252. // Clean mesh references
  72253. for (var id in this._meshes) {
  72254. var meshHighlight = this._meshes[id];
  72255. if (meshHighlight && meshHighlight.mesh) {
  72256. if (meshHighlight.observerHighlight) {
  72257. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72258. }
  72259. if (meshHighlight.observerDefault) {
  72260. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72261. }
  72262. }
  72263. }
  72264. this._meshes = null;
  72265. }
  72266. if (this._excludedMeshes) {
  72267. for (var id in this._excludedMeshes) {
  72268. var meshHighlight = this._excludedMeshes[id];
  72269. if (meshHighlight) {
  72270. if (meshHighlight.beforeRender) {
  72271. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  72272. }
  72273. if (meshHighlight.afterRender) {
  72274. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  72275. }
  72276. }
  72277. }
  72278. this._excludedMeshes = null;
  72279. }
  72280. // Remove from scene
  72281. var index = this._scene.highlightLayers.indexOf(this, 0);
  72282. if (index > -1) {
  72283. this._scene.highlightLayers.splice(index, 1);
  72284. }
  72285. // Callback
  72286. this.onDisposeObservable.notifyObservers(this);
  72287. this.onDisposeObservable.clear();
  72288. this.onBeforeRenderMainTextureObservable.clear();
  72289. this.onBeforeBlurObservable.clear();
  72290. this.onBeforeComposeObservable.clear();
  72291. this.onAfterComposeObservable.clear();
  72292. this.onSizeChangedObservable.clear();
  72293. };
  72294. /**
  72295. * The neutral color used during the preparation of the glow effect.
  72296. * This is black by default as the blend operation is a blend operation.
  72297. */
  72298. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  72299. /**
  72300. * Stencil value used for glowing meshes.
  72301. */
  72302. HighlightLayer.glowingMeshStencilReference = 0x02;
  72303. /**
  72304. * Stencil value used for the other meshes in the scene.
  72305. */
  72306. HighlightLayer.normalMeshStencilReference = 0x01;
  72307. return HighlightLayer;
  72308. }());
  72309. BABYLON.HighlightLayer = HighlightLayer;
  72310. })(BABYLON || (BABYLON = {}));
  72311. //# sourceMappingURL=babylon.highlightlayer.js.map
  72312. var BABYLON;
  72313. (function (BABYLON) {
  72314. var AssetTaskState;
  72315. (function (AssetTaskState) {
  72316. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  72317. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  72318. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  72319. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  72320. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  72321. var AbstractAssetTask = /** @class */ (function () {
  72322. function AbstractAssetTask(name) {
  72323. this.name = name;
  72324. this.isCompleted = false;
  72325. this.taskState = AssetTaskState.INIT;
  72326. }
  72327. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72328. var _this = this;
  72329. this.taskState = AssetTaskState.RUNNING;
  72330. this.runTask(scene, function () {
  72331. _this.onDoneCallback(onSuccess, onError);
  72332. }, function (msg, exception) {
  72333. _this.onErrorCallback(onError, msg, exception);
  72334. });
  72335. };
  72336. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72337. throw new Error("runTask is not implemented");
  72338. };
  72339. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  72340. this.taskState = AssetTaskState.ERROR;
  72341. this.errorObject = {
  72342. message: message,
  72343. exception: exception
  72344. };
  72345. if (this.onError) {
  72346. this.onError(this, message, exception);
  72347. }
  72348. onError();
  72349. };
  72350. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  72351. try {
  72352. this.taskState = AssetTaskState.DONE;
  72353. this.isCompleted = true;
  72354. if (this.onSuccess) {
  72355. this.onSuccess(this);
  72356. }
  72357. onSuccess();
  72358. }
  72359. catch (e) {
  72360. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  72361. }
  72362. };
  72363. return AbstractAssetTask;
  72364. }());
  72365. BABYLON.AbstractAssetTask = AbstractAssetTask;
  72366. var AssetsProgressEvent = /** @class */ (function () {
  72367. function AssetsProgressEvent(remainingCount, totalCount, task) {
  72368. this.remainingCount = remainingCount;
  72369. this.totalCount = totalCount;
  72370. this.task = task;
  72371. }
  72372. return AssetsProgressEvent;
  72373. }());
  72374. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  72375. var MeshAssetTask = /** @class */ (function (_super) {
  72376. __extends(MeshAssetTask, _super);
  72377. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  72378. var _this = _super.call(this, name) || this;
  72379. _this.name = name;
  72380. _this.meshesNames = meshesNames;
  72381. _this.rootUrl = rootUrl;
  72382. _this.sceneFilename = sceneFilename;
  72383. return _this;
  72384. }
  72385. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72386. var _this = this;
  72387. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  72388. _this.loadedMeshes = meshes;
  72389. _this.loadedParticleSystems = particleSystems;
  72390. _this.loadedSkeletons = skeletons;
  72391. onSuccess();
  72392. }, null, function (scene, message, exception) {
  72393. onError(message, exception);
  72394. });
  72395. };
  72396. return MeshAssetTask;
  72397. }(AbstractAssetTask));
  72398. BABYLON.MeshAssetTask = MeshAssetTask;
  72399. var TextFileAssetTask = /** @class */ (function (_super) {
  72400. __extends(TextFileAssetTask, _super);
  72401. function TextFileAssetTask(name, url) {
  72402. var _this = _super.call(this, name) || this;
  72403. _this.name = name;
  72404. _this.url = url;
  72405. return _this;
  72406. }
  72407. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72408. var _this = this;
  72409. BABYLON.Tools.LoadFile(this.url, function (data) {
  72410. _this.text = data;
  72411. onSuccess();
  72412. }, undefined, scene.database, false, function (request, exception) {
  72413. if (request) {
  72414. onError(request.status + " " + request.statusText, exception);
  72415. }
  72416. });
  72417. };
  72418. return TextFileAssetTask;
  72419. }(AbstractAssetTask));
  72420. BABYLON.TextFileAssetTask = TextFileAssetTask;
  72421. var BinaryFileAssetTask = /** @class */ (function (_super) {
  72422. __extends(BinaryFileAssetTask, _super);
  72423. function BinaryFileAssetTask(name, url) {
  72424. var _this = _super.call(this, name) || this;
  72425. _this.name = name;
  72426. _this.url = url;
  72427. return _this;
  72428. }
  72429. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72430. var _this = this;
  72431. BABYLON.Tools.LoadFile(this.url, function (data) {
  72432. _this.data = data;
  72433. onSuccess();
  72434. }, undefined, scene.database, true, function (request, exception) {
  72435. if (request) {
  72436. onError(request.status + " " + request.statusText, exception);
  72437. }
  72438. });
  72439. };
  72440. return BinaryFileAssetTask;
  72441. }(AbstractAssetTask));
  72442. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  72443. var ImageAssetTask = /** @class */ (function (_super) {
  72444. __extends(ImageAssetTask, _super);
  72445. function ImageAssetTask(name, url) {
  72446. var _this = _super.call(this, name) || this;
  72447. _this.name = name;
  72448. _this.url = url;
  72449. return _this;
  72450. }
  72451. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72452. var _this = this;
  72453. var img = new Image();
  72454. BABYLON.Tools.SetCorsBehavior(this.url, img);
  72455. img.onload = function () {
  72456. _this.image = img;
  72457. onSuccess();
  72458. };
  72459. img.onerror = function (err) {
  72460. onError("Error loading image", err);
  72461. };
  72462. img.src = this.url;
  72463. };
  72464. return ImageAssetTask;
  72465. }(AbstractAssetTask));
  72466. BABYLON.ImageAssetTask = ImageAssetTask;
  72467. var TextureAssetTask = /** @class */ (function (_super) {
  72468. __extends(TextureAssetTask, _super);
  72469. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  72470. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72471. var _this = _super.call(this, name) || this;
  72472. _this.name = name;
  72473. _this.url = url;
  72474. _this.noMipmap = noMipmap;
  72475. _this.invertY = invertY;
  72476. _this.samplingMode = samplingMode;
  72477. return _this;
  72478. }
  72479. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72480. var onload = function () {
  72481. onSuccess();
  72482. };
  72483. var onerror = function (msg, exception) {
  72484. onError(msg, exception);
  72485. };
  72486. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  72487. };
  72488. return TextureAssetTask;
  72489. }(AbstractAssetTask));
  72490. BABYLON.TextureAssetTask = TextureAssetTask;
  72491. var CubeTextureAssetTask = /** @class */ (function (_super) {
  72492. __extends(CubeTextureAssetTask, _super);
  72493. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  72494. var _this = _super.call(this, name) || this;
  72495. _this.name = name;
  72496. _this.url = url;
  72497. _this.extensions = extensions;
  72498. _this.noMipmap = noMipmap;
  72499. _this.files = files;
  72500. return _this;
  72501. }
  72502. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72503. var onload = function () {
  72504. onSuccess();
  72505. };
  72506. var onerror = function (msg, exception) {
  72507. onError(msg, exception);
  72508. };
  72509. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  72510. };
  72511. return CubeTextureAssetTask;
  72512. }(AbstractAssetTask));
  72513. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  72514. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  72515. __extends(HDRCubeTextureAssetTask, _super);
  72516. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72517. if (noMipmap === void 0) { noMipmap = false; }
  72518. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72519. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72520. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72521. var _this = _super.call(this, name) || this;
  72522. _this.name = name;
  72523. _this.url = url;
  72524. _this.size = size;
  72525. _this.noMipmap = noMipmap;
  72526. _this.generateHarmonics = generateHarmonics;
  72527. _this.useInGammaSpace = useInGammaSpace;
  72528. _this.usePMREMGenerator = usePMREMGenerator;
  72529. return _this;
  72530. }
  72531. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72532. var onload = function () {
  72533. onSuccess();
  72534. };
  72535. var onerror = function (message, exception) {
  72536. onError(message, exception);
  72537. };
  72538. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  72539. };
  72540. return HDRCubeTextureAssetTask;
  72541. }(AbstractAssetTask));
  72542. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  72543. var AssetsManager = /** @class */ (function () {
  72544. function AssetsManager(scene) {
  72545. this.tasks = new Array();
  72546. this.waitingTasksCount = 0;
  72547. //Observables
  72548. this.onTaskSuccessObservable = new BABYLON.Observable();
  72549. this.onTaskErrorObservable = new BABYLON.Observable();
  72550. this.onTasksDoneObservable = new BABYLON.Observable();
  72551. this.onProgressObservable = new BABYLON.Observable();
  72552. this.useDefaultLoadingScreen = true;
  72553. this._scene = scene;
  72554. }
  72555. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  72556. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  72557. this.tasks.push(task);
  72558. return task;
  72559. };
  72560. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  72561. var task = new TextFileAssetTask(taskName, url);
  72562. this.tasks.push(task);
  72563. return task;
  72564. };
  72565. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  72566. var task = new BinaryFileAssetTask(taskName, url);
  72567. this.tasks.push(task);
  72568. return task;
  72569. };
  72570. AssetsManager.prototype.addImageTask = function (taskName, url) {
  72571. var task = new ImageAssetTask(taskName, url);
  72572. this.tasks.push(task);
  72573. return task;
  72574. };
  72575. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  72576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72577. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  72578. this.tasks.push(task);
  72579. return task;
  72580. };
  72581. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  72582. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  72583. this.tasks.push(task);
  72584. return task;
  72585. };
  72586. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72587. if (noMipmap === void 0) { noMipmap = false; }
  72588. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72589. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72590. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72591. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  72592. this.tasks.push(task);
  72593. return task;
  72594. };
  72595. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  72596. this.waitingTasksCount--;
  72597. try {
  72598. if (this.onProgress) {
  72599. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  72600. }
  72601. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  72602. }
  72603. catch (e) {
  72604. BABYLON.Tools.Error("Error running progress callbacks.");
  72605. console.log(e);
  72606. }
  72607. if (this.waitingTasksCount === 0) {
  72608. try {
  72609. if (this.onFinish) {
  72610. this.onFinish(this.tasks);
  72611. }
  72612. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72613. }
  72614. catch (e) {
  72615. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  72616. console.log(e);
  72617. }
  72618. this._scene.getEngine().hideLoadingUI();
  72619. }
  72620. };
  72621. AssetsManager.prototype._runTask = function (task) {
  72622. var _this = this;
  72623. var done = function () {
  72624. try {
  72625. if (_this.onTaskSuccess) {
  72626. _this.onTaskSuccess(task);
  72627. }
  72628. _this.onTaskSuccessObservable.notifyObservers(task);
  72629. _this._decreaseWaitingTasksCount(task);
  72630. }
  72631. catch (e) {
  72632. error("Error executing task success callbacks", e);
  72633. }
  72634. };
  72635. var error = function (message, exception) {
  72636. task.errorObject = task.errorObject || {
  72637. message: message,
  72638. exception: exception
  72639. };
  72640. if (_this.onTaskError) {
  72641. _this.onTaskError(task);
  72642. }
  72643. _this.onTaskErrorObservable.notifyObservers(task);
  72644. _this._decreaseWaitingTasksCount(task);
  72645. };
  72646. task.run(this._scene, done, error);
  72647. };
  72648. AssetsManager.prototype.reset = function () {
  72649. this.tasks = new Array();
  72650. return this;
  72651. };
  72652. AssetsManager.prototype.load = function () {
  72653. this.waitingTasksCount = this.tasks.length;
  72654. if (this.waitingTasksCount === 0) {
  72655. if (this.onFinish) {
  72656. this.onFinish(this.tasks);
  72657. }
  72658. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72659. return this;
  72660. }
  72661. if (this.useDefaultLoadingScreen) {
  72662. this._scene.getEngine().displayLoadingUI();
  72663. }
  72664. for (var index = 0; index < this.tasks.length; index++) {
  72665. var task = this.tasks[index];
  72666. this._runTask(task);
  72667. }
  72668. return this;
  72669. };
  72670. return AssetsManager;
  72671. }());
  72672. BABYLON.AssetsManager = AssetsManager;
  72673. })(BABYLON || (BABYLON = {}));
  72674. //# sourceMappingURL=babylon.assetsManager.js.map
  72675. var BABYLON;
  72676. (function (BABYLON) {
  72677. var serializedGeometries = [];
  72678. var serializeGeometry = function (geometry, serializationGeometries) {
  72679. if (serializedGeometries[geometry.id]) {
  72680. return;
  72681. }
  72682. if (geometry.doNotSerialize) {
  72683. return;
  72684. }
  72685. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  72686. serializationGeometries.boxes.push(geometry.serialize());
  72687. }
  72688. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  72689. serializationGeometries.spheres.push(geometry.serialize());
  72690. }
  72691. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  72692. serializationGeometries.cylinders.push(geometry.serialize());
  72693. }
  72694. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  72695. serializationGeometries.toruses.push(geometry.serialize());
  72696. }
  72697. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  72698. serializationGeometries.grounds.push(geometry.serialize());
  72699. }
  72700. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  72701. serializationGeometries.planes.push(geometry.serialize());
  72702. }
  72703. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  72704. serializationGeometries.torusKnots.push(geometry.serialize());
  72705. }
  72706. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  72707. throw new Error("Unknown primitive type");
  72708. }
  72709. else {
  72710. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  72711. }
  72712. serializedGeometries[geometry.id] = true;
  72713. };
  72714. var serializeMesh = function (mesh, serializationScene) {
  72715. var serializationObject = {};
  72716. // Geometry
  72717. var geometry = mesh._geometry;
  72718. if (geometry) {
  72719. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  72720. // 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
  72721. serializeGeometry(geometry, serializationScene.geometries);
  72722. }
  72723. }
  72724. // Custom
  72725. if (mesh.serialize) {
  72726. mesh.serialize(serializationObject);
  72727. }
  72728. return serializationObject;
  72729. };
  72730. var finalizeSingleMesh = function (mesh, serializationObject) {
  72731. //only works if the mesh is already loaded
  72732. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72733. //serialize material
  72734. if (mesh.material) {
  72735. if (mesh.material instanceof BABYLON.StandardMaterial) {
  72736. serializationObject.materials = serializationObject.materials || [];
  72737. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72738. serializationObject.materials.push(mesh.material.serialize());
  72739. }
  72740. }
  72741. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  72742. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  72743. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72744. serializationObject.multiMaterials.push(mesh.material.serialize());
  72745. }
  72746. }
  72747. }
  72748. //serialize geometry
  72749. var geometry = mesh._geometry;
  72750. if (geometry) {
  72751. if (!serializationObject.geometries) {
  72752. serializationObject.geometries = {};
  72753. serializationObject.geometries.boxes = [];
  72754. serializationObject.geometries.spheres = [];
  72755. serializationObject.geometries.cylinders = [];
  72756. serializationObject.geometries.toruses = [];
  72757. serializationObject.geometries.grounds = [];
  72758. serializationObject.geometries.planes = [];
  72759. serializationObject.geometries.torusKnots = [];
  72760. serializationObject.geometries.vertexData = [];
  72761. }
  72762. serializeGeometry(geometry, serializationObject.geometries);
  72763. }
  72764. // Skeletons
  72765. if (mesh.skeleton) {
  72766. serializationObject.skeletons = serializationObject.skeletons || [];
  72767. serializationObject.skeletons.push(mesh.skeleton.serialize());
  72768. }
  72769. //serialize the actual mesh
  72770. serializationObject.meshes = serializationObject.meshes || [];
  72771. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  72772. }
  72773. };
  72774. var SceneSerializer = /** @class */ (function () {
  72775. function SceneSerializer() {
  72776. }
  72777. SceneSerializer.ClearCache = function () {
  72778. serializedGeometries = [];
  72779. };
  72780. SceneSerializer.Serialize = function (scene) {
  72781. var serializationObject = {};
  72782. SceneSerializer.ClearCache();
  72783. // Scene
  72784. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  72785. serializationObject.autoClear = scene.autoClear;
  72786. serializationObject.clearColor = scene.clearColor.asArray();
  72787. serializationObject.ambientColor = scene.ambientColor.asArray();
  72788. serializationObject.gravity = scene.gravity.asArray();
  72789. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  72790. serializationObject.workerCollisions = scene.workerCollisions;
  72791. // Fog
  72792. if (scene.fogMode && scene.fogMode !== 0) {
  72793. serializationObject.fogMode = scene.fogMode;
  72794. serializationObject.fogColor = scene.fogColor.asArray();
  72795. serializationObject.fogStart = scene.fogStart;
  72796. serializationObject.fogEnd = scene.fogEnd;
  72797. serializationObject.fogDensity = scene.fogDensity;
  72798. }
  72799. //Physics
  72800. if (scene.isPhysicsEnabled()) {
  72801. var physicEngine = scene.getPhysicsEngine();
  72802. if (physicEngine) {
  72803. serializationObject.physicsEnabled = true;
  72804. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  72805. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  72806. }
  72807. }
  72808. // Metadata
  72809. if (scene.metadata) {
  72810. serializationObject.metadata = scene.metadata;
  72811. }
  72812. // Morph targets
  72813. serializationObject.morphTargetManagers = [];
  72814. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  72815. var abstractMesh = _a[_i];
  72816. var manager = abstractMesh.morphTargetManager;
  72817. if (manager) {
  72818. serializationObject.morphTargetManagers.push(manager.serialize());
  72819. }
  72820. }
  72821. // Lights
  72822. serializationObject.lights = [];
  72823. var index;
  72824. var light;
  72825. for (index = 0; index < scene.lights.length; index++) {
  72826. light = scene.lights[index];
  72827. if (!light.doNotSerialize) {
  72828. serializationObject.lights.push(light.serialize());
  72829. }
  72830. }
  72831. // Cameras
  72832. serializationObject.cameras = [];
  72833. for (index = 0; index < scene.cameras.length; index++) {
  72834. var camera = scene.cameras[index];
  72835. if (!camera.doNotSerialize) {
  72836. serializationObject.cameras.push(camera.serialize());
  72837. }
  72838. }
  72839. if (scene.activeCamera) {
  72840. serializationObject.activeCameraID = scene.activeCamera.id;
  72841. }
  72842. // Animations
  72843. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  72844. // Materials
  72845. serializationObject.materials = [];
  72846. serializationObject.multiMaterials = [];
  72847. var material;
  72848. for (index = 0; index < scene.materials.length; index++) {
  72849. material = scene.materials[index];
  72850. if (!material.doNotSerialize) {
  72851. serializationObject.materials.push(material.serialize());
  72852. }
  72853. }
  72854. // MultiMaterials
  72855. serializationObject.multiMaterials = [];
  72856. for (index = 0; index < scene.multiMaterials.length; index++) {
  72857. var multiMaterial = scene.multiMaterials[index];
  72858. serializationObject.multiMaterials.push(multiMaterial.serialize());
  72859. }
  72860. // Skeletons
  72861. serializationObject.skeletons = [];
  72862. for (index = 0; index < scene.skeletons.length; index++) {
  72863. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  72864. }
  72865. // Geometries
  72866. serializationObject.geometries = {};
  72867. serializationObject.geometries.boxes = [];
  72868. serializationObject.geometries.spheres = [];
  72869. serializationObject.geometries.cylinders = [];
  72870. serializationObject.geometries.toruses = [];
  72871. serializationObject.geometries.grounds = [];
  72872. serializationObject.geometries.planes = [];
  72873. serializationObject.geometries.torusKnots = [];
  72874. serializationObject.geometries.vertexData = [];
  72875. serializedGeometries = [];
  72876. var geometries = scene.getGeometries();
  72877. for (index = 0; index < geometries.length; index++) {
  72878. var geometry = geometries[index];
  72879. if (geometry.isReady()) {
  72880. serializeGeometry(geometry, serializationObject.geometries);
  72881. }
  72882. }
  72883. // Meshes
  72884. serializationObject.meshes = [];
  72885. for (index = 0; index < scene.meshes.length; index++) {
  72886. var abstractMesh = scene.meshes[index];
  72887. if (abstractMesh instanceof BABYLON.Mesh) {
  72888. var mesh = abstractMesh;
  72889. if (!mesh.doNotSerialize) {
  72890. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72891. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  72892. }
  72893. }
  72894. }
  72895. }
  72896. // Particles Systems
  72897. serializationObject.particleSystems = [];
  72898. for (index = 0; index < scene.particleSystems.length; index++) {
  72899. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  72900. }
  72901. // Lens flares
  72902. serializationObject.lensFlareSystems = [];
  72903. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  72904. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  72905. }
  72906. // Shadows
  72907. serializationObject.shadowGenerators = [];
  72908. for (index = 0; index < scene.lights.length; index++) {
  72909. light = scene.lights[index];
  72910. var shadowGenerator = light.getShadowGenerator();
  72911. if (shadowGenerator) {
  72912. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  72913. }
  72914. }
  72915. // Action Manager
  72916. if (scene.actionManager) {
  72917. serializationObject.actions = scene.actionManager.serialize("scene");
  72918. }
  72919. // Audio
  72920. serializationObject.sounds = [];
  72921. for (index = 0; index < scene.soundTracks.length; index++) {
  72922. var soundtrack = scene.soundTracks[index];
  72923. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  72924. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  72925. }
  72926. }
  72927. return serializationObject;
  72928. };
  72929. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  72930. if (withParents === void 0) { withParents = false; }
  72931. if (withChildren === void 0) { withChildren = false; }
  72932. var serializationObject = {};
  72933. SceneSerializer.ClearCache();
  72934. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  72935. if (withParents || withChildren) {
  72936. //deliberate for loop! not for each, appended should be processed as well.
  72937. for (var i = 0; i < toSerialize.length; ++i) {
  72938. if (withChildren) {
  72939. toSerialize[i].getDescendants().forEach(function (node) {
  72940. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  72941. toSerialize.push(node);
  72942. }
  72943. });
  72944. }
  72945. //make sure the array doesn't contain the object already
  72946. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  72947. toSerialize.push(toSerialize[i].parent);
  72948. }
  72949. }
  72950. }
  72951. toSerialize.forEach(function (mesh) {
  72952. finalizeSingleMesh(mesh, serializationObject);
  72953. });
  72954. return serializationObject;
  72955. };
  72956. return SceneSerializer;
  72957. }());
  72958. BABYLON.SceneSerializer = SceneSerializer;
  72959. })(BABYLON || (BABYLON = {}));
  72960. //# sourceMappingURL=babylon.sceneSerializer.js.map
  72961. var BABYLON;
  72962. (function (BABYLON) {
  72963. var ReflectionProbe = /** @class */ (function () {
  72964. function ReflectionProbe(name, size, scene, generateMipMaps) {
  72965. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72966. var _this = this;
  72967. this.name = name;
  72968. this._viewMatrix = BABYLON.Matrix.Identity();
  72969. this._target = BABYLON.Vector3.Zero();
  72970. this._add = BABYLON.Vector3.Zero();
  72971. this.invertYAxis = false;
  72972. this.position = BABYLON.Vector3.Zero();
  72973. this._scene = scene;
  72974. this._scene.reflectionProbes.push(this);
  72975. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  72976. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  72977. switch (faceIndex) {
  72978. case 0:
  72979. _this._add.copyFromFloats(1, 0, 0);
  72980. break;
  72981. case 1:
  72982. _this._add.copyFromFloats(-1, 0, 0);
  72983. break;
  72984. case 2:
  72985. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  72986. break;
  72987. case 3:
  72988. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  72989. break;
  72990. case 4:
  72991. _this._add.copyFromFloats(0, 0, 1);
  72992. break;
  72993. case 5:
  72994. _this._add.copyFromFloats(0, 0, -1);
  72995. break;
  72996. }
  72997. if (_this._attachedMesh) {
  72998. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  72999. }
  73000. _this.position.addToRef(_this._add, _this._target);
  73001. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  73002. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  73003. scene._forcedViewPosition = _this.position;
  73004. });
  73005. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  73006. scene._forcedViewPosition = null;
  73007. scene.updateTransformMatrix(true);
  73008. });
  73009. if (scene.activeCamera) {
  73010. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73011. }
  73012. }
  73013. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  73014. get: function () {
  73015. return this._renderTargetTexture.samples;
  73016. },
  73017. set: function (value) {
  73018. this._renderTargetTexture.samples = value;
  73019. },
  73020. enumerable: true,
  73021. configurable: true
  73022. });
  73023. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  73024. get: function () {
  73025. return this._renderTargetTexture.refreshRate;
  73026. },
  73027. set: function (value) {
  73028. this._renderTargetTexture.refreshRate = value;
  73029. },
  73030. enumerable: true,
  73031. configurable: true
  73032. });
  73033. ReflectionProbe.prototype.getScene = function () {
  73034. return this._scene;
  73035. };
  73036. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  73037. get: function () {
  73038. return this._renderTargetTexture;
  73039. },
  73040. enumerable: true,
  73041. configurable: true
  73042. });
  73043. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  73044. get: function () {
  73045. return this._renderTargetTexture.renderList;
  73046. },
  73047. enumerable: true,
  73048. configurable: true
  73049. });
  73050. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  73051. this._attachedMesh = mesh;
  73052. };
  73053. /**
  73054. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73055. *
  73056. * @param renderingGroupId The rendering group id corresponding to its index
  73057. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73058. */
  73059. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73060. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73061. };
  73062. ReflectionProbe.prototype.dispose = function () {
  73063. var index = this._scene.reflectionProbes.indexOf(this);
  73064. if (index !== -1) {
  73065. // Remove from the scene if found
  73066. this._scene.reflectionProbes.splice(index, 1);
  73067. }
  73068. if (this._renderTargetTexture) {
  73069. this._renderTargetTexture.dispose();
  73070. this._renderTargetTexture = null;
  73071. }
  73072. };
  73073. return ReflectionProbe;
  73074. }());
  73075. BABYLON.ReflectionProbe = ReflectionProbe;
  73076. })(BABYLON || (BABYLON = {}));
  73077. //# sourceMappingURL=babylon.reflectionProbe.js.map
  73078. var BABYLON;
  73079. (function (BABYLON) {
  73080. var Layer = /** @class */ (function () {
  73081. function Layer(name, imgUrl, scene, isBackground, color) {
  73082. this.name = name;
  73083. this.scale = new BABYLON.Vector2(1, 1);
  73084. this.offset = new BABYLON.Vector2(0, 0);
  73085. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  73086. this.layerMask = 0x0FFFFFFF;
  73087. this._vertexBuffers = {};
  73088. // Events
  73089. /**
  73090. * An event triggered when the layer is disposed.
  73091. * @type {BABYLON.Observable}
  73092. */
  73093. this.onDisposeObservable = new BABYLON.Observable();
  73094. /**
  73095. * An event triggered before rendering the scene
  73096. * @type {BABYLON.Observable}
  73097. */
  73098. this.onBeforeRenderObservable = new BABYLON.Observable();
  73099. /**
  73100. * An event triggered after rendering the scene
  73101. * @type {BABYLON.Observable}
  73102. */
  73103. this.onAfterRenderObservable = new BABYLON.Observable();
  73104. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  73105. this.isBackground = isBackground === undefined ? true : isBackground;
  73106. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  73107. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  73108. this._scene.layers.push(this);
  73109. var engine = this._scene.getEngine();
  73110. // VBO
  73111. var vertices = [];
  73112. vertices.push(1, 1);
  73113. vertices.push(-1, 1);
  73114. vertices.push(-1, -1);
  73115. vertices.push(1, -1);
  73116. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73117. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73118. this._createIndexBuffer();
  73119. // Effects
  73120. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  73121. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  73122. }
  73123. Object.defineProperty(Layer.prototype, "onDispose", {
  73124. set: function (callback) {
  73125. if (this._onDisposeObserver) {
  73126. this.onDisposeObservable.remove(this._onDisposeObserver);
  73127. }
  73128. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  73129. },
  73130. enumerable: true,
  73131. configurable: true
  73132. });
  73133. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  73134. set: function (callback) {
  73135. if (this._onBeforeRenderObserver) {
  73136. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73137. }
  73138. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73139. },
  73140. enumerable: true,
  73141. configurable: true
  73142. });
  73143. Object.defineProperty(Layer.prototype, "onAfterRender", {
  73144. set: function (callback) {
  73145. if (this._onAfterRenderObserver) {
  73146. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73147. }
  73148. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73149. },
  73150. enumerable: true,
  73151. configurable: true
  73152. });
  73153. Layer.prototype._createIndexBuffer = function () {
  73154. var engine = this._scene.getEngine();
  73155. // Indices
  73156. var indices = [];
  73157. indices.push(0);
  73158. indices.push(1);
  73159. indices.push(2);
  73160. indices.push(0);
  73161. indices.push(2);
  73162. indices.push(3);
  73163. this._indexBuffer = engine.createIndexBuffer(indices);
  73164. };
  73165. Layer.prototype._rebuild = function () {
  73166. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73167. if (vb) {
  73168. vb._rebuild();
  73169. }
  73170. this._createIndexBuffer();
  73171. };
  73172. Layer.prototype.render = function () {
  73173. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  73174. // Check
  73175. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  73176. return;
  73177. var engine = this._scene.getEngine();
  73178. this.onBeforeRenderObservable.notifyObservers(this);
  73179. // Render
  73180. engine.enableEffect(currentEffect);
  73181. engine.setState(false);
  73182. // Texture
  73183. currentEffect.setTexture("textureSampler", this.texture);
  73184. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  73185. // Color
  73186. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  73187. // Scale / offset
  73188. currentEffect.setVector2("offset", this.offset);
  73189. currentEffect.setVector2("scale", this.scale);
  73190. // VBOs
  73191. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73192. // Draw order
  73193. if (!this.alphaTest) {
  73194. engine.setAlphaMode(this.alphaBlendingMode);
  73195. engine.draw(true, 0, 6);
  73196. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73197. }
  73198. else {
  73199. engine.draw(true, 0, 6);
  73200. }
  73201. this.onAfterRenderObservable.notifyObservers(this);
  73202. };
  73203. Layer.prototype.dispose = function () {
  73204. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73205. if (vertexBuffer) {
  73206. vertexBuffer.dispose();
  73207. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73208. }
  73209. if (this._indexBuffer) {
  73210. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73211. this._indexBuffer = null;
  73212. }
  73213. if (this.texture) {
  73214. this.texture.dispose();
  73215. this.texture = null;
  73216. }
  73217. // Remove from scene
  73218. var index = this._scene.layers.indexOf(this);
  73219. this._scene.layers.splice(index, 1);
  73220. // Callback
  73221. this.onDisposeObservable.notifyObservers(this);
  73222. this.onDisposeObservable.clear();
  73223. this.onAfterRenderObservable.clear();
  73224. this.onBeforeRenderObservable.clear();
  73225. };
  73226. return Layer;
  73227. }());
  73228. BABYLON.Layer = Layer;
  73229. })(BABYLON || (BABYLON = {}));
  73230. //# sourceMappingURL=babylon.layer.js.map
  73231. var BABYLON;
  73232. (function (BABYLON) {
  73233. var TextureTools = /** @class */ (function () {
  73234. function TextureTools() {
  73235. }
  73236. /**
  73237. * Uses the GPU to create a copy texture rescaled at a given size
  73238. * @param texture Texture to copy from
  73239. * @param width Desired width
  73240. * @param height Desired height
  73241. * @return Generated texture
  73242. */
  73243. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  73244. if (useBilinearMode === void 0) { useBilinearMode = true; }
  73245. var scene = texture.getScene();
  73246. var engine = scene.getEngine();
  73247. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  73248. rtt.wrapU = texture.wrapU;
  73249. rtt.wrapV = texture.wrapV;
  73250. rtt.uOffset = texture.uOffset;
  73251. rtt.vOffset = texture.vOffset;
  73252. rtt.uScale = texture.uScale;
  73253. rtt.vScale = texture.vScale;
  73254. rtt.uAng = texture.uAng;
  73255. rtt.vAng = texture.vAng;
  73256. rtt.wAng = texture.wAng;
  73257. rtt.coordinatesIndex = texture.coordinatesIndex;
  73258. rtt.level = texture.level;
  73259. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  73260. rtt._texture.isReady = false;
  73261. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73262. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73263. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73264. passPostProcess.getEffect().executeWhenCompiled(function () {
  73265. passPostProcess.onApply = function (effect) {
  73266. effect.setTexture("textureSampler", texture);
  73267. };
  73268. var internalTexture = rtt.getInternalTexture();
  73269. if (internalTexture) {
  73270. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  73271. engine.unBindFramebuffer(internalTexture);
  73272. rtt.disposeFramebufferObjects();
  73273. passPostProcess.dispose();
  73274. internalTexture.isReady = true;
  73275. }
  73276. });
  73277. return rtt;
  73278. };
  73279. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  73280. if (!scene._environmentBRDFTexture) {
  73281. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73282. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73283. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73284. scene._environmentBRDFTexture = texture;
  73285. }
  73286. return scene._environmentBRDFTexture;
  73287. };
  73288. 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=";
  73289. return TextureTools;
  73290. }());
  73291. BABYLON.TextureTools = TextureTools;
  73292. })(BABYLON || (BABYLON = {}));
  73293. //# sourceMappingURL=babylon.textureTools.js.map
  73294. var BABYLON;
  73295. (function (BABYLON) {
  73296. var FramingBehavior = /** @class */ (function () {
  73297. function FramingBehavior() {
  73298. this._mode = FramingBehavior.FitFrustumSidesMode;
  73299. this._radiusScale = 1.0;
  73300. this._positionScale = 0.5;
  73301. this._defaultElevation = 0.3;
  73302. this._elevationReturnTime = 1500;
  73303. this._elevationReturnWaitTime = 1000;
  73304. this._zoomStopsAnimation = false;
  73305. this._framingTime = 1500;
  73306. this._isPointerDown = false;
  73307. this._lastInteractionTime = -Infinity;
  73308. // Framing control
  73309. this._animatables = new Array();
  73310. this._betaIsAnimating = false;
  73311. }
  73312. Object.defineProperty(FramingBehavior.prototype, "name", {
  73313. get: function () {
  73314. return "Framing";
  73315. },
  73316. enumerable: true,
  73317. configurable: true
  73318. });
  73319. Object.defineProperty(FramingBehavior.prototype, "mode", {
  73320. /**
  73321. * Gets current mode used by the behavior.
  73322. */
  73323. get: function () {
  73324. return this._mode;
  73325. },
  73326. /**
  73327. * Sets the current mode used by the behavior
  73328. */
  73329. set: function (mode) {
  73330. this._mode = mode;
  73331. },
  73332. enumerable: true,
  73333. configurable: true
  73334. });
  73335. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  73336. /**
  73337. * Gets the scale applied to the radius
  73338. */
  73339. get: function () {
  73340. return this._radiusScale;
  73341. },
  73342. /**
  73343. * Sets the scale applied to the radius (1 by default)
  73344. */
  73345. set: function (radius) {
  73346. this._radiusScale = radius;
  73347. },
  73348. enumerable: true,
  73349. configurable: true
  73350. });
  73351. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  73352. /**
  73353. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73354. */
  73355. get: function () {
  73356. return this._positionScale;
  73357. },
  73358. /**
  73359. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73360. */
  73361. set: function (scale) {
  73362. this._positionScale = scale;
  73363. },
  73364. enumerable: true,
  73365. configurable: true
  73366. });
  73367. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  73368. /**
  73369. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73370. * behaviour is triggered, in radians.
  73371. */
  73372. get: function () {
  73373. return this._defaultElevation;
  73374. },
  73375. /**
  73376. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73377. * behaviour is triggered, in radians.
  73378. */
  73379. set: function (elevation) {
  73380. this._defaultElevation = elevation;
  73381. },
  73382. enumerable: true,
  73383. configurable: true
  73384. });
  73385. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  73386. /**
  73387. * Gets the time (in milliseconds) taken to return to the default beta position.
  73388. * Negative value indicates camera should not return to default.
  73389. */
  73390. get: function () {
  73391. return this._elevationReturnTime;
  73392. },
  73393. /**
  73394. * Sets the time (in milliseconds) taken to return to the default beta position.
  73395. * Negative value indicates camera should not return to default.
  73396. */
  73397. set: function (speed) {
  73398. this._elevationReturnTime = speed;
  73399. },
  73400. enumerable: true,
  73401. configurable: true
  73402. });
  73403. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  73404. /**
  73405. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73406. */
  73407. get: function () {
  73408. return this._elevationReturnWaitTime;
  73409. },
  73410. /**
  73411. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73412. */
  73413. set: function (time) {
  73414. this._elevationReturnWaitTime = time;
  73415. },
  73416. enumerable: true,
  73417. configurable: true
  73418. });
  73419. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  73420. /**
  73421. * Gets the flag that indicates if user zooming should stop animation.
  73422. */
  73423. get: function () {
  73424. return this._zoomStopsAnimation;
  73425. },
  73426. /**
  73427. * Sets the flag that indicates if user zooming should stop animation.
  73428. */
  73429. set: function (flag) {
  73430. this._zoomStopsAnimation = flag;
  73431. },
  73432. enumerable: true,
  73433. configurable: true
  73434. });
  73435. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  73436. /**
  73437. * Gets the transition time when framing the mesh, in milliseconds
  73438. */
  73439. get: function () {
  73440. return this._framingTime;
  73441. },
  73442. /**
  73443. * Sets the transition time when framing the mesh, in milliseconds
  73444. */
  73445. set: function (time) {
  73446. this._framingTime = time;
  73447. },
  73448. enumerable: true,
  73449. configurable: true
  73450. });
  73451. FramingBehavior.prototype.attach = function (camera) {
  73452. var _this = this;
  73453. this._attachedCamera = camera;
  73454. var scene = this._attachedCamera.getScene();
  73455. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  73456. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73457. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73458. _this._isPointerDown = true;
  73459. return;
  73460. }
  73461. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73462. _this._isPointerDown = false;
  73463. }
  73464. });
  73465. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73466. if (mesh) {
  73467. _this.zoomOnMesh(mesh);
  73468. }
  73469. });
  73470. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73471. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73472. _this._applyUserInteraction();
  73473. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  73474. // back to the default position after a given timeout
  73475. _this._maintainCameraAboveGround();
  73476. });
  73477. };
  73478. FramingBehavior.prototype.detach = function () {
  73479. if (!this._attachedCamera) {
  73480. return;
  73481. }
  73482. var scene = this._attachedCamera.getScene();
  73483. if (this._onPrePointerObservableObserver) {
  73484. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73485. }
  73486. if (this._onAfterCheckInputsObserver) {
  73487. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73488. }
  73489. if (this._onMeshTargetChangedObserver) {
  73490. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73491. }
  73492. this._attachedCamera = null;
  73493. };
  73494. /**
  73495. * Targets the given mesh and updates zoom level accordingly.
  73496. * @param mesh The mesh to target.
  73497. * @param radius Optional. If a cached radius position already exists, overrides default.
  73498. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73499. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73500. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73501. */
  73502. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  73503. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73504. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73505. mesh.computeWorldMatrix(true);
  73506. var boundingBox = mesh.getBoundingInfo().boundingBox;
  73507. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  73508. };
  73509. /**
  73510. * Targets the given mesh and updates zoom level accordingly.
  73511. * @param mesh The mesh to target.
  73512. * @param radius Optional. If a cached radius position already exists, overrides default.
  73513. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73514. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73515. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73516. */
  73517. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  73518. var _this = this;
  73519. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73520. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73521. var zoomTarget;
  73522. if (!this._attachedCamera) {
  73523. return;
  73524. }
  73525. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  73526. var bottom = minimumWorld.y;
  73527. var top = maximumWorld.y;
  73528. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  73529. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  73530. if (focusOnOriginXZ) {
  73531. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  73532. }
  73533. else {
  73534. var centerWorld = minimumWorld.add(radiusWorld);
  73535. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  73536. }
  73537. if (!this._vectorTransition) {
  73538. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  73539. }
  73540. this._betaIsAnimating = true;
  73541. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  73542. if (animatable) {
  73543. this._animatables.push(animatable);
  73544. }
  73545. // sets the radius and lower radius bounds
  73546. // Small delta ensures camera is not always at lower zoom limit.
  73547. var radius = 0;
  73548. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  73549. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73550. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  73551. radius = position;
  73552. }
  73553. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73554. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73555. if (this._attachedCamera.lowerRadiusLimit === null) {
  73556. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  73557. }
  73558. }
  73559. // Set sensibilities
  73560. var extend = maximumWorld.subtract(minimumWorld).length();
  73561. this._attachedCamera.panningSensibility = 5000 / extend;
  73562. this._attachedCamera.wheelPrecision = 100 / radius;
  73563. // transition to new radius
  73564. if (!this._radiusTransition) {
  73565. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73566. }
  73567. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  73568. if (onAnimationEnd) {
  73569. onAnimationEnd();
  73570. }
  73571. if (_this._attachedCamera) {
  73572. _this._attachedCamera.storeState();
  73573. }
  73574. });
  73575. if (animatable) {
  73576. this._animatables.push(animatable);
  73577. }
  73578. };
  73579. /**
  73580. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  73581. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  73582. * frustum width.
  73583. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  73584. * to fully enclose the mesh in the viewing frustum.
  73585. */
  73586. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  73587. var size = maximumWorld.subtract(minimumWorld);
  73588. var boxVectorGlobalDiagonal = size.length();
  73589. var frustumSlope = this._getFrustumSlope();
  73590. // Formula for setting distance
  73591. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  73592. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  73593. // Horizon distance
  73594. var radius = radiusWithoutFraming * this._radiusScale;
  73595. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  73596. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  73597. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  73598. var camera = this._attachedCamera;
  73599. if (!camera) {
  73600. return 0;
  73601. }
  73602. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73603. // Don't exceed the requested limit
  73604. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  73605. }
  73606. // Don't exceed the upper radius limit
  73607. if (camera.upperRadiusLimit) {
  73608. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  73609. }
  73610. return distance;
  73611. };
  73612. /**
  73613. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  73614. * is automatically returned to its default position (expected to be above ground plane).
  73615. */
  73616. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  73617. var _this = this;
  73618. if (this._elevationReturnTime < 0) {
  73619. return;
  73620. }
  73621. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  73622. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  73623. var limitBeta = Math.PI * 0.5;
  73624. // Bring the camera back up if below the ground plane
  73625. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  73626. this._betaIsAnimating = true;
  73627. //Transition to new position
  73628. this.stopAllAnimations();
  73629. if (!this._betaTransition) {
  73630. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73631. }
  73632. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  73633. _this._clearAnimationLocks();
  73634. _this.stopAllAnimations();
  73635. });
  73636. if (animatabe) {
  73637. this._animatables.push(animatabe);
  73638. }
  73639. }
  73640. };
  73641. /**
  73642. * Returns the frustum slope based on the canvas ratio and camera FOV
  73643. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  73644. */
  73645. FramingBehavior.prototype._getFrustumSlope = function () {
  73646. // Calculate the viewport ratio
  73647. // Aspect Ratio is Height/Width.
  73648. var camera = this._attachedCamera;
  73649. if (!camera) {
  73650. return BABYLON.Vector2.Zero();
  73651. }
  73652. var engine = camera.getScene().getEngine();
  73653. var aspectRatio = engine.getAspectRatio(camera);
  73654. // Camera FOV is the vertical field of view (top-bottom) in radians.
  73655. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  73656. var frustumSlopeY = Math.tan(camera.fov / 2);
  73657. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  73658. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  73659. // along the forward vector.
  73660. var frustumSlopeX = frustumSlopeY * aspectRatio;
  73661. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  73662. };
  73663. /**
  73664. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  73665. */
  73666. FramingBehavior.prototype._clearAnimationLocks = function () {
  73667. this._betaIsAnimating = false;
  73668. };
  73669. /**
  73670. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  73671. */
  73672. FramingBehavior.prototype._applyUserInteraction = function () {
  73673. if (this.isUserIsMoving) {
  73674. this._lastInteractionTime = BABYLON.Tools.Now;
  73675. this.stopAllAnimations();
  73676. this._clearAnimationLocks();
  73677. }
  73678. };
  73679. /**
  73680. * Stops and removes all animations that have been applied to the camera
  73681. */
  73682. FramingBehavior.prototype.stopAllAnimations = function () {
  73683. if (this._attachedCamera) {
  73684. this._attachedCamera.animations = [];
  73685. }
  73686. while (this._animatables.length) {
  73687. if (this._animatables[0]) {
  73688. this._animatables[0].onAnimationEnd = null;
  73689. this._animatables[0].stop();
  73690. }
  73691. this._animatables.shift();
  73692. }
  73693. };
  73694. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  73695. /**
  73696. * Gets a value indicating if the user is moving the camera
  73697. */
  73698. get: function () {
  73699. if (!this._attachedCamera) {
  73700. return false;
  73701. }
  73702. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  73703. this._attachedCamera.inertialBetaOffset !== 0 ||
  73704. this._attachedCamera.inertialRadiusOffset !== 0 ||
  73705. this._attachedCamera.inertialPanningX !== 0 ||
  73706. this._attachedCamera.inertialPanningY !== 0 ||
  73707. this._isPointerDown;
  73708. },
  73709. enumerable: true,
  73710. configurable: true
  73711. });
  73712. /**
  73713. * The easing function used by animations
  73714. */
  73715. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  73716. /**
  73717. * The easing mode used by animations
  73718. */
  73719. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  73720. // Statics
  73721. /**
  73722. * The camera can move all the way towards the mesh.
  73723. */
  73724. FramingBehavior.IgnoreBoundsSizeMode = 0;
  73725. /**
  73726. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  73727. */
  73728. FramingBehavior.FitFrustumSidesMode = 1;
  73729. return FramingBehavior;
  73730. }());
  73731. BABYLON.FramingBehavior = FramingBehavior;
  73732. })(BABYLON || (BABYLON = {}));
  73733. //# sourceMappingURL=babylon.framingBehavior.js.map
  73734. var BABYLON;
  73735. (function (BABYLON) {
  73736. /**
  73737. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  73738. */
  73739. var BouncingBehavior = /** @class */ (function () {
  73740. function BouncingBehavior() {
  73741. /**
  73742. * The duration of the animation, in milliseconds
  73743. */
  73744. this.transitionDuration = 450;
  73745. /**
  73746. * Length of the distance animated by the transition when lower radius is reached
  73747. */
  73748. this.lowerRadiusTransitionRange = 2;
  73749. /**
  73750. * Length of the distance animated by the transition when upper radius is reached
  73751. */
  73752. this.upperRadiusTransitionRange = -2;
  73753. this._autoTransitionRange = false;
  73754. // Animations
  73755. this._radiusIsAnimating = false;
  73756. this._radiusBounceTransition = null;
  73757. this._animatables = new Array();
  73758. }
  73759. Object.defineProperty(BouncingBehavior.prototype, "name", {
  73760. get: function () {
  73761. return "Bouncing";
  73762. },
  73763. enumerable: true,
  73764. configurable: true
  73765. });
  73766. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  73767. /**
  73768. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73769. */
  73770. get: function () {
  73771. return this._autoTransitionRange;
  73772. },
  73773. /**
  73774. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73775. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  73776. */
  73777. set: function (value) {
  73778. var _this = this;
  73779. if (this._autoTransitionRange === value) {
  73780. return;
  73781. }
  73782. this._autoTransitionRange = value;
  73783. var camera = this._attachedCamera;
  73784. if (!camera) {
  73785. return;
  73786. }
  73787. if (value) {
  73788. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73789. if (!mesh) {
  73790. return;
  73791. }
  73792. mesh.computeWorldMatrix(true);
  73793. var diagonal = mesh.getBoundingInfo().diagonalLength;
  73794. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  73795. _this.upperRadiusTransitionRange = diagonal * 0.05;
  73796. });
  73797. }
  73798. else if (this._onMeshTargetChangedObserver) {
  73799. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73800. }
  73801. },
  73802. enumerable: true,
  73803. configurable: true
  73804. });
  73805. BouncingBehavior.prototype.attach = function (camera) {
  73806. var _this = this;
  73807. this._attachedCamera = camera;
  73808. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73809. if (!_this._attachedCamera) {
  73810. return;
  73811. }
  73812. // Add the bounce animation to the lower radius limit
  73813. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  73814. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  73815. }
  73816. // Add the bounce animation to the upper radius limit
  73817. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  73818. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  73819. }
  73820. });
  73821. };
  73822. BouncingBehavior.prototype.detach = function () {
  73823. if (!this._attachedCamera) {
  73824. return;
  73825. }
  73826. if (this._onAfterCheckInputsObserver) {
  73827. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73828. }
  73829. if (this._onMeshTargetChangedObserver) {
  73830. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73831. }
  73832. this._attachedCamera = null;
  73833. };
  73834. /**
  73835. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  73836. * @param radiusLimit The limit to check against.
  73837. * @return Bool to indicate if at limit.
  73838. */
  73839. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  73840. if (!this._attachedCamera) {
  73841. return false;
  73842. }
  73843. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  73844. return true;
  73845. }
  73846. return false;
  73847. };
  73848. /**
  73849. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  73850. * @param radiusDelta The delta by which to animate to. Can be negative.
  73851. */
  73852. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  73853. var _this = this;
  73854. if (!this._attachedCamera) {
  73855. return;
  73856. }
  73857. if (!this._radiusBounceTransition) {
  73858. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  73859. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  73860. }
  73861. // Prevent zoom until bounce has completed
  73862. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  73863. this._attachedCamera.wheelPrecision = Infinity;
  73864. this._attachedCamera.inertialRadiusOffset = 0;
  73865. // Animate to the radius limit
  73866. this.stopAllAnimations();
  73867. this._radiusIsAnimating = true;
  73868. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  73869. if (animatable) {
  73870. this._animatables.push(animatable);
  73871. }
  73872. };
  73873. /**
  73874. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  73875. */
  73876. BouncingBehavior.prototype._clearAnimationLocks = function () {
  73877. this._radiusIsAnimating = false;
  73878. if (this._attachedCamera) {
  73879. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  73880. }
  73881. };
  73882. /**
  73883. * Stops and removes all animations that have been applied to the camera
  73884. */
  73885. BouncingBehavior.prototype.stopAllAnimations = function () {
  73886. if (this._attachedCamera) {
  73887. this._attachedCamera.animations = [];
  73888. }
  73889. while (this._animatables.length) {
  73890. this._animatables[0].onAnimationEnd = null;
  73891. this._animatables[0].stop();
  73892. this._animatables.shift();
  73893. }
  73894. };
  73895. /**
  73896. * The easing function used by animations
  73897. */
  73898. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  73899. /**
  73900. * The easing mode used by animations
  73901. */
  73902. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  73903. return BouncingBehavior;
  73904. }());
  73905. BABYLON.BouncingBehavior = BouncingBehavior;
  73906. })(BABYLON || (BABYLON = {}));
  73907. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  73908. var BABYLON;
  73909. (function (BABYLON) {
  73910. var AutoRotationBehavior = /** @class */ (function () {
  73911. function AutoRotationBehavior() {
  73912. this._zoomStopsAnimation = false;
  73913. this._idleRotationSpeed = 0.05;
  73914. this._idleRotationWaitTime = 2000;
  73915. this._idleRotationSpinupTime = 2000;
  73916. this._isPointerDown = false;
  73917. this._lastFrameTime = null;
  73918. this._lastInteractionTime = -Infinity;
  73919. this._cameraRotationSpeed = 0;
  73920. this._lastFrameRadius = 0;
  73921. }
  73922. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  73923. get: function () {
  73924. return "AutoRotation";
  73925. },
  73926. enumerable: true,
  73927. configurable: true
  73928. });
  73929. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  73930. /**
  73931. * Gets the flag that indicates if user zooming should stop animation.
  73932. */
  73933. get: function () {
  73934. return this._zoomStopsAnimation;
  73935. },
  73936. /**
  73937. * Sets the flag that indicates if user zooming should stop animation.
  73938. */
  73939. set: function (flag) {
  73940. this._zoomStopsAnimation = flag;
  73941. },
  73942. enumerable: true,
  73943. configurable: true
  73944. });
  73945. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  73946. /**
  73947. * Gets the default speed at which the camera rotates around the model.
  73948. */
  73949. get: function () {
  73950. return this._idleRotationSpeed;
  73951. },
  73952. /**
  73953. * Sets the default speed at which the camera rotates around the model.
  73954. */
  73955. set: function (speed) {
  73956. this._idleRotationSpeed = speed;
  73957. },
  73958. enumerable: true,
  73959. configurable: true
  73960. });
  73961. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  73962. /**
  73963. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  73964. */
  73965. get: function () {
  73966. return this._idleRotationWaitTime;
  73967. },
  73968. /**
  73969. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  73970. */
  73971. set: function (time) {
  73972. this._idleRotationWaitTime = time;
  73973. },
  73974. enumerable: true,
  73975. configurable: true
  73976. });
  73977. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  73978. /**
  73979. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  73980. */
  73981. get: function () {
  73982. return this._idleRotationSpinupTime;
  73983. },
  73984. /**
  73985. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  73986. */
  73987. set: function (time) {
  73988. this._idleRotationSpinupTime = time;
  73989. },
  73990. enumerable: true,
  73991. configurable: true
  73992. });
  73993. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  73994. /**
  73995. * Gets a value indicating if the camera is currently rotating because of this behavior
  73996. */
  73997. get: function () {
  73998. return Math.abs(this._cameraRotationSpeed) > 0;
  73999. },
  74000. enumerable: true,
  74001. configurable: true
  74002. });
  74003. AutoRotationBehavior.prototype.attach = function (camera) {
  74004. var _this = this;
  74005. this._attachedCamera = camera;
  74006. var scene = this._attachedCamera.getScene();
  74007. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74008. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74009. _this._isPointerDown = true;
  74010. return;
  74011. }
  74012. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74013. _this._isPointerDown = false;
  74014. }
  74015. });
  74016. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74017. var now = BABYLON.Tools.Now;
  74018. var dt = 0;
  74019. if (_this._lastFrameTime != null) {
  74020. dt = now - _this._lastFrameTime;
  74021. }
  74022. _this._lastFrameTime = now;
  74023. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74024. _this._applyUserInteraction();
  74025. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  74026. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  74027. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  74028. // Step camera rotation by rotation speed
  74029. if (_this._attachedCamera) {
  74030. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  74031. }
  74032. });
  74033. };
  74034. AutoRotationBehavior.prototype.detach = function () {
  74035. if (!this._attachedCamera) {
  74036. return;
  74037. }
  74038. var scene = this._attachedCamera.getScene();
  74039. if (this._onPrePointerObservableObserver) {
  74040. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74041. }
  74042. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74043. this._attachedCamera = null;
  74044. };
  74045. /**
  74046. * Returns true if user is scrolling.
  74047. * @return true if user is scrolling.
  74048. */
  74049. AutoRotationBehavior.prototype._userIsZooming = function () {
  74050. if (!this._attachedCamera) {
  74051. return false;
  74052. }
  74053. return this._attachedCamera.inertialRadiusOffset !== 0;
  74054. };
  74055. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  74056. if (!this._attachedCamera) {
  74057. return false;
  74058. }
  74059. var zoomHasHitLimit = false;
  74060. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  74061. zoomHasHitLimit = true;
  74062. }
  74063. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  74064. this._lastFrameRadius = this._attachedCamera.radius;
  74065. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  74066. };
  74067. /**
  74068. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74069. */
  74070. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  74071. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  74072. this._lastInteractionTime = BABYLON.Tools.Now;
  74073. }
  74074. };
  74075. // Tools
  74076. AutoRotationBehavior.prototype._userIsMoving = function () {
  74077. if (!this._attachedCamera) {
  74078. return false;
  74079. }
  74080. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74081. this._attachedCamera.inertialBetaOffset !== 0 ||
  74082. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74083. this._attachedCamera.inertialPanningX !== 0 ||
  74084. this._attachedCamera.inertialPanningY !== 0 ||
  74085. this._isPointerDown;
  74086. };
  74087. return AutoRotationBehavior;
  74088. }());
  74089. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  74090. })(BABYLON || (BABYLON = {}));
  74091. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  74092. var BABYLON;
  74093. (function (BABYLON) {
  74094. /**
  74095. * This class can be used to get instrumentation data from a Babylon engine
  74096. */
  74097. var EngineInstrumentation = /** @class */ (function () {
  74098. function EngineInstrumentation(engine) {
  74099. this.engine = engine;
  74100. this._captureGPUFrameTime = false;
  74101. this._gpuFrameTime = new BABYLON.PerfCounter();
  74102. this._captureShaderCompilationTime = false;
  74103. this._shaderCompilationTime = new BABYLON.PerfCounter();
  74104. // Observers
  74105. this._onBeginFrameObserver = null;
  74106. this._onEndFrameObserver = null;
  74107. this._onBeforeShaderCompilationObserver = null;
  74108. this._onAfterShaderCompilationObserver = null;
  74109. }
  74110. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  74111. // Properties
  74112. /**
  74113. * Gets the perf counter used for GPU frame time
  74114. */
  74115. get: function () {
  74116. return this._gpuFrameTime;
  74117. },
  74118. enumerable: true,
  74119. configurable: true
  74120. });
  74121. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  74122. /**
  74123. * Gets the GPU frame time capture status
  74124. */
  74125. get: function () {
  74126. return this._captureGPUFrameTime;
  74127. },
  74128. /**
  74129. * Enable or disable the GPU frame time capture
  74130. */
  74131. set: function (value) {
  74132. var _this = this;
  74133. if (value === this._captureGPUFrameTime) {
  74134. return;
  74135. }
  74136. if (value) {
  74137. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  74138. if (!_this._gpuFrameTimeToken) {
  74139. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  74140. }
  74141. });
  74142. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  74143. if (!_this._gpuFrameTimeToken) {
  74144. return;
  74145. }
  74146. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  74147. if (time > -1) {
  74148. _this._gpuFrameTimeToken = null;
  74149. _this._gpuFrameTime.fetchNewFrame();
  74150. _this._gpuFrameTime.addCount(time, true);
  74151. }
  74152. });
  74153. }
  74154. else {
  74155. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74156. this._onBeginFrameObserver = null;
  74157. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74158. this._onEndFrameObserver = null;
  74159. }
  74160. },
  74161. enumerable: true,
  74162. configurable: true
  74163. });
  74164. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  74165. /**
  74166. * Gets the perf counter used for shader compilation time
  74167. */
  74168. get: function () {
  74169. return this._shaderCompilationTime;
  74170. },
  74171. enumerable: true,
  74172. configurable: true
  74173. });
  74174. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  74175. /**
  74176. * Gets the shader compilation time capture status
  74177. */
  74178. get: function () {
  74179. return this._captureShaderCompilationTime;
  74180. },
  74181. /**
  74182. * Enable or disable the shader compilation time capture
  74183. */
  74184. set: function (value) {
  74185. var _this = this;
  74186. if (value === this._captureShaderCompilationTime) {
  74187. return;
  74188. }
  74189. if (value) {
  74190. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  74191. _this._shaderCompilationTime.fetchNewFrame();
  74192. _this._shaderCompilationTime.beginMonitoring();
  74193. });
  74194. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  74195. _this._shaderCompilationTime.endMonitoring();
  74196. });
  74197. }
  74198. else {
  74199. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74200. this._onBeforeShaderCompilationObserver = null;
  74201. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74202. this._onAfterShaderCompilationObserver = null;
  74203. }
  74204. },
  74205. enumerable: true,
  74206. configurable: true
  74207. });
  74208. EngineInstrumentation.prototype.dispose = function () {
  74209. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74210. this._onBeginFrameObserver = null;
  74211. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74212. this._onEndFrameObserver = null;
  74213. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74214. this._onBeforeShaderCompilationObserver = null;
  74215. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74216. this._onAfterShaderCompilationObserver = null;
  74217. this.engine = null;
  74218. };
  74219. return EngineInstrumentation;
  74220. }());
  74221. BABYLON.EngineInstrumentation = EngineInstrumentation;
  74222. })(BABYLON || (BABYLON = {}));
  74223. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  74224. var BABYLON;
  74225. (function (BABYLON) {
  74226. /**
  74227. * This class can be used to get instrumentation data from a Babylon engine
  74228. */
  74229. var SceneInstrumentation = /** @class */ (function () {
  74230. function SceneInstrumentation(scene) {
  74231. var _this = this;
  74232. this.scene = scene;
  74233. this._captureActiveMeshesEvaluationTime = false;
  74234. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  74235. this._captureRenderTargetsRenderTime = false;
  74236. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  74237. this._captureFrameTime = false;
  74238. this._frameTime = new BABYLON.PerfCounter();
  74239. // Observers
  74240. this._onBeforeActiveMeshesEvaluationObserver = null;
  74241. this._onAfterActiveMeshesEvaluationObserver = null;
  74242. this._onBeforeRenderTargetsRenderObserver = null;
  74243. this._onAfterRenderTargetsRenderObserver = null;
  74244. this._onBeforeRenderObserver = null;
  74245. this._onAfterRenderObserver = null;
  74246. this._onBeforeRenderObserver = scene.onBeforeRenderObservable.add(function () {
  74247. if (_this._captureActiveMeshesEvaluationTime) {
  74248. _this._activeMeshesEvaluationTime.fetchNewFrame();
  74249. }
  74250. if (_this._captureRenderTargetsRenderTime) {
  74251. _this._renderTargetsRenderTime.fetchNewFrame();
  74252. }
  74253. if (_this._captureFrameTime) {
  74254. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  74255. _this._frameTime.beginMonitoring();
  74256. }
  74257. });
  74258. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  74259. if (_this._captureFrameTime) {
  74260. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  74261. _this._frameTime.endMonitoring();
  74262. }
  74263. });
  74264. }
  74265. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTime", {
  74266. // Properties
  74267. /**
  74268. * Gets the perf counter used for active meshes evaluation time
  74269. */
  74270. get: function () {
  74271. return this._activeMeshesEvaluationTime;
  74272. },
  74273. enumerable: true,
  74274. configurable: true
  74275. });
  74276. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  74277. /**
  74278. * Gets the active meshes evaluation time capture status
  74279. */
  74280. get: function () {
  74281. return this._captureActiveMeshesEvaluationTime;
  74282. },
  74283. /**
  74284. * Enable or disable the active meshes evaluation time capture
  74285. */
  74286. set: function (value) {
  74287. var _this = this;
  74288. if (value === this._captureActiveMeshesEvaluationTime) {
  74289. return;
  74290. }
  74291. if (value) {
  74292. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  74293. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  74294. _this._activeMeshesEvaluationTime.beginMonitoring();
  74295. });
  74296. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  74297. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  74298. _this._activeMeshesEvaluationTime.endMonitoring();
  74299. });
  74300. }
  74301. else {
  74302. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74303. this._onBeforeActiveMeshesEvaluationObserver = null;
  74304. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74305. this._onAfterActiveMeshesEvaluationObserver = null;
  74306. }
  74307. },
  74308. enumerable: true,
  74309. configurable: true
  74310. });
  74311. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  74312. /**
  74313. * Gets the perf counter used for render targets render time
  74314. */
  74315. get: function () {
  74316. return this._renderTargetsRenderTime;
  74317. },
  74318. enumerable: true,
  74319. configurable: true
  74320. });
  74321. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  74322. /**
  74323. * Gets the render targets render time capture status
  74324. */
  74325. get: function () {
  74326. return this._captureRenderTargetsRenderTime;
  74327. },
  74328. /**
  74329. * Enable or disable the render targets render time capture
  74330. */
  74331. set: function (value) {
  74332. var _this = this;
  74333. if (value === this._captureRenderTargetsRenderTime) {
  74334. return;
  74335. }
  74336. if (value) {
  74337. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  74338. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  74339. _this._renderTargetsRenderTime.beginMonitoring();
  74340. });
  74341. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  74342. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  74343. _this._renderTargetsRenderTime.endMonitoring(false);
  74344. });
  74345. }
  74346. else {
  74347. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74348. this._onBeforeRenderTargetsRenderObserver = null;
  74349. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74350. this._onAfterRenderTargetsRenderObserver = null;
  74351. }
  74352. },
  74353. enumerable: true,
  74354. configurable: true
  74355. });
  74356. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  74357. /**
  74358. * Gets the perf counter used for frame time capture
  74359. */
  74360. get: function () {
  74361. return this._frameTime;
  74362. },
  74363. enumerable: true,
  74364. configurable: true
  74365. });
  74366. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  74367. /**
  74368. * Gets the frame time capture status
  74369. */
  74370. get: function () {
  74371. return this._captureFrameTime;
  74372. },
  74373. /**
  74374. * Enable or disable the frame time capture
  74375. */
  74376. set: function (value) {
  74377. this._captureFrameTime = value;
  74378. },
  74379. enumerable: true,
  74380. configurable: true
  74381. });
  74382. SceneInstrumentation.prototype.dispose = function () {
  74383. this.scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74384. this._onBeforeRenderObserver = null;
  74385. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74386. this._onAfterRenderObserver = null;
  74387. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74388. this._onBeforeActiveMeshesEvaluationObserver = null;
  74389. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74390. this._onAfterActiveMeshesEvaluationObserver = null;
  74391. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74392. this._onBeforeRenderTargetsRenderObserver = null;
  74393. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74394. this._onAfterRenderTargetsRenderObserver = null;
  74395. this.scene = null;
  74396. };
  74397. return SceneInstrumentation;
  74398. }());
  74399. BABYLON.SceneInstrumentation = SceneInstrumentation;
  74400. })(BABYLON || (BABYLON = {}));
  74401. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  74402. var BABYLON;
  74403. (function (BABYLON) {
  74404. var _TimeToken = /** @class */ (function () {
  74405. function _TimeToken() {
  74406. this._timeElapsedQueryEnded = false;
  74407. }
  74408. return _TimeToken;
  74409. }());
  74410. BABYLON._TimeToken = _TimeToken;
  74411. })(BABYLON || (BABYLON = {}));
  74412. //# sourceMappingURL=babylon.timeToken.js.map
  74413. 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}"};
  74414. 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};"};
  74415. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74416. var BABYLON;
  74417. (function (BABYLON) {
  74418. var GridMaterialDefines = /** @class */ (function (_super) {
  74419. __extends(GridMaterialDefines, _super);
  74420. function GridMaterialDefines() {
  74421. var _this = _super.call(this) || this;
  74422. _this.TRANSPARENT = false;
  74423. _this.FOG = false;
  74424. _this.PREMULTIPLYALPHA = false;
  74425. _this.rebuild();
  74426. return _this;
  74427. }
  74428. return GridMaterialDefines;
  74429. }(BABYLON.MaterialDefines));
  74430. /**
  74431. * The grid materials allows you to wrap any shape with a grid.
  74432. * Colors are customizable.
  74433. */
  74434. var GridMaterial = /** @class */ (function (_super) {
  74435. __extends(GridMaterial, _super);
  74436. /**
  74437. * constructor
  74438. * @param name The name given to the material in order to identify it afterwards.
  74439. * @param scene The scene the material is used in.
  74440. */
  74441. function GridMaterial(name, scene) {
  74442. var _this = _super.call(this, name, scene) || this;
  74443. /**
  74444. * Main color of the grid (e.g. between lines)
  74445. */
  74446. _this.mainColor = BABYLON.Color3.Black();
  74447. /**
  74448. * Color of the grid lines.
  74449. */
  74450. _this.lineColor = BABYLON.Color3.Teal();
  74451. /**
  74452. * The scale of the grid compared to unit.
  74453. */
  74454. _this.gridRatio = 1.0;
  74455. /**
  74456. * Allows setting an offset for the grid lines.
  74457. */
  74458. _this.gridOffset = BABYLON.Vector3.Zero();
  74459. /**
  74460. * The frequency of thicker lines.
  74461. */
  74462. _this.majorUnitFrequency = 10;
  74463. /**
  74464. * The visibility of minor units in the grid.
  74465. */
  74466. _this.minorUnitVisibility = 0.33;
  74467. /**
  74468. * The grid opacity outside of the lines.
  74469. */
  74470. _this.opacity = 1.0;
  74471. /**
  74472. * Determine RBG output is premultiplied by alpha value.
  74473. */
  74474. _this.preMultiplyAlpha = false;
  74475. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  74476. return _this;
  74477. }
  74478. /**
  74479. * Returns wehter or not the grid requires alpha blending.
  74480. */
  74481. GridMaterial.prototype.needAlphaBlending = function () {
  74482. return this.opacity < 1.0;
  74483. };
  74484. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74485. if (this.isFrozen) {
  74486. if (this._wasPreviouslyReady && subMesh.effect) {
  74487. return true;
  74488. }
  74489. }
  74490. if (!subMesh._materialDefines) {
  74491. subMesh._materialDefines = new GridMaterialDefines();
  74492. }
  74493. var defines = subMesh._materialDefines;
  74494. var scene = this.getScene();
  74495. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  74496. if (this._renderId === scene.getRenderId()) {
  74497. return true;
  74498. }
  74499. }
  74500. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  74501. defines.TRANSPARENT = !defines.TRANSPARENT;
  74502. defines.markAsUnprocessed();
  74503. }
  74504. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  74505. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  74506. defines.markAsUnprocessed();
  74507. }
  74508. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  74509. // Get correct effect
  74510. if (defines.isDirty) {
  74511. defines.markAsProcessed();
  74512. scene.resetCachedMaterial();
  74513. // Attributes
  74514. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74515. // Defines
  74516. var join = defines.toString();
  74517. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  74518. }
  74519. if (!subMesh.effect || !subMesh.effect.isReady()) {
  74520. return false;
  74521. }
  74522. this._renderId = scene.getRenderId();
  74523. this._wasPreviouslyReady = true;
  74524. return true;
  74525. };
  74526. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  74527. var scene = this.getScene();
  74528. var defines = subMesh._materialDefines;
  74529. if (!defines) {
  74530. return;
  74531. }
  74532. var effect = subMesh.effect;
  74533. if (!effect) {
  74534. return;
  74535. }
  74536. this._activeEffect = effect;
  74537. // Matrices
  74538. this.bindOnlyWorldMatrix(world);
  74539. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  74540. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  74541. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  74542. // Uniforms
  74543. if (this._mustRebind(scene, effect)) {
  74544. this._activeEffect.setColor3("mainColor", this.mainColor);
  74545. this._activeEffect.setColor3("lineColor", this.lineColor);
  74546. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  74547. this._gridControl.x = this.gridRatio;
  74548. this._gridControl.y = Math.round(this.majorUnitFrequency);
  74549. this._gridControl.z = this.minorUnitVisibility;
  74550. this._gridControl.w = this.opacity;
  74551. this._activeEffect.setVector4("gridControl", this._gridControl);
  74552. }
  74553. // Fog
  74554. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  74555. this._afterBind(mesh, this._activeEffect);
  74556. };
  74557. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  74558. _super.prototype.dispose.call(this, forceDisposeEffect);
  74559. };
  74560. GridMaterial.prototype.clone = function (name) {
  74561. var _this = this;
  74562. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  74563. };
  74564. GridMaterial.prototype.serialize = function () {
  74565. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74566. serializationObject.customType = "BABYLON.GridMaterial";
  74567. return serializationObject;
  74568. };
  74569. GridMaterial.prototype.getClassName = function () {
  74570. return "GridMaterial";
  74571. };
  74572. GridMaterial.Parse = function (source, scene, rootUrl) {
  74573. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  74574. };
  74575. __decorate([
  74576. BABYLON.serializeAsColor3()
  74577. ], GridMaterial.prototype, "mainColor", void 0);
  74578. __decorate([
  74579. BABYLON.serializeAsColor3()
  74580. ], GridMaterial.prototype, "lineColor", void 0);
  74581. __decorate([
  74582. BABYLON.serialize()
  74583. ], GridMaterial.prototype, "gridRatio", void 0);
  74584. __decorate([
  74585. BABYLON.serializeAsColor3()
  74586. ], GridMaterial.prototype, "gridOffset", void 0);
  74587. __decorate([
  74588. BABYLON.serialize()
  74589. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  74590. __decorate([
  74591. BABYLON.serialize()
  74592. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  74593. __decorate([
  74594. BABYLON.serialize()
  74595. ], GridMaterial.prototype, "opacity", void 0);
  74596. __decorate([
  74597. BABYLON.serialize()
  74598. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  74599. return GridMaterial;
  74600. }(BABYLON.PushMaterial));
  74601. BABYLON.GridMaterial = GridMaterial;
  74602. })(BABYLON || (BABYLON = {}));
  74603. //# sourceMappingURL=babylon.gridmaterial.js.map
  74604. 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}";
  74605. 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}";
  74606. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74607. var BABYLON;
  74608. (function (BABYLON) {
  74609. /**
  74610. * Background material defines definition.
  74611. */
  74612. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  74613. __extends(BackgroundMaterialDefines, _super);
  74614. /**
  74615. * Constructor of the defines.
  74616. */
  74617. function BackgroundMaterialDefines() {
  74618. var _this = _super.call(this) || this;
  74619. /**
  74620. * True if the diffuse texture is in use.
  74621. */
  74622. _this.DIFFUSE = false;
  74623. /**
  74624. * The direct UV channel to use.
  74625. */
  74626. _this.DIFFUSEDIRECTUV = 0;
  74627. /**
  74628. * True if the diffuse texture is in gamma space.
  74629. */
  74630. _this.GAMMADIFFUSE = false;
  74631. /**
  74632. * True if the diffuse texture has opacity in the alpha channel.
  74633. */
  74634. _this.DIFFUSEHASALPHA = false;
  74635. /**
  74636. * True if you want the material to fade to transparent at grazing angle.
  74637. */
  74638. _this.OPACITYFRESNEL = false;
  74639. /**
  74640. * True if an extra blur needs to be added in the reflection.
  74641. */
  74642. _this.REFLECTIONBLUR = false;
  74643. /**
  74644. * False if the current Webgl implementation does not support the texture lod extension.
  74645. */
  74646. _this.TEXTURELODSUPPORT = false;
  74647. /**
  74648. * True to ensure the data are premultiplied.
  74649. */
  74650. _this.PREMULTIPLYALPHA = false;
  74651. /**
  74652. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  74653. */
  74654. _this.USERGBCOLOR = false;
  74655. // Image Processing Configuration.
  74656. _this.IMAGEPROCESSING = false;
  74657. _this.VIGNETTE = false;
  74658. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  74659. _this.VIGNETTEBLENDMODEOPAQUE = false;
  74660. _this.TONEMAPPING = false;
  74661. _this.CONTRAST = false;
  74662. _this.COLORCURVES = false;
  74663. _this.COLORGRADING = false;
  74664. _this.COLORGRADING3D = false;
  74665. _this.SAMPLER3DGREENDEPTH = false;
  74666. _this.SAMPLER3DBGRMAP = false;
  74667. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  74668. _this.EXPOSURE = false;
  74669. // Reflection.
  74670. _this.REFLECTION = false;
  74671. _this.REFLECTIONMAP_3D = false;
  74672. _this.REFLECTIONMAP_SPHERICAL = false;
  74673. _this.REFLECTIONMAP_PLANAR = false;
  74674. _this.REFLECTIONMAP_CUBIC = false;
  74675. _this.REFLECTIONMAP_PROJECTION = false;
  74676. _this.REFLECTIONMAP_SKYBOX = false;
  74677. _this.REFLECTIONMAP_EXPLICIT = false;
  74678. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  74679. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  74680. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  74681. _this.INVERTCUBICMAP = false;
  74682. _this.REFLECTIONMAP_OPPOSITEZ = false;
  74683. _this.LODINREFLECTIONALPHA = false;
  74684. _this.GAMMAREFLECTION = false;
  74685. // Default BJS.
  74686. _this.MAINUV1 = false;
  74687. _this.MAINUV2 = false;
  74688. _this.UV1 = false;
  74689. _this.UV2 = false;
  74690. _this.CLIPPLANE = false;
  74691. _this.POINTSIZE = false;
  74692. _this.FOG = false;
  74693. _this.NORMAL = false;
  74694. _this.NUM_BONE_INFLUENCERS = 0;
  74695. _this.BonesPerMesh = 0;
  74696. _this.INSTANCES = false;
  74697. _this.SHADOWFLOAT = false;
  74698. _this.rebuild();
  74699. return _this;
  74700. }
  74701. return BackgroundMaterialDefines;
  74702. }(BABYLON.MaterialDefines));
  74703. /**
  74704. * Background material
  74705. */
  74706. var BackgroundMaterial = /** @class */ (function (_super) {
  74707. __extends(BackgroundMaterial, _super);
  74708. /**
  74709. * constructor
  74710. * @param name The name of the material
  74711. * @param scene The scene to add the material to
  74712. */
  74713. function BackgroundMaterial(name, scene) {
  74714. var _this = _super.call(this, name, scene) || this;
  74715. _this.primaryColor = BABYLON.Color3.White();
  74716. _this.primaryLevel = 1;
  74717. _this.secondaryColor = BABYLON.Color3.Gray();
  74718. _this.secondaryLevel = 1;
  74719. _this.tertiaryColor = BABYLON.Color3.Black();
  74720. _this.tertiaryLevel = 1;
  74721. _this.reflectionTexture = null;
  74722. _this.reflectionBlur = 0;
  74723. _this.diffuseTexture = null;
  74724. /**
  74725. * Specify the list of lights casting shadow on the material.
  74726. * All scene shadow lights will be included if null.
  74727. */
  74728. _this._shadowLights = null;
  74729. _this.shadowLights = null;
  74730. _this.shadowBlurScale = 1;
  74731. _this.shadowLevel = 0;
  74732. _this.opacityFresnel = true;
  74733. _this.useRGBColor = true;
  74734. /**
  74735. * Number of Simultaneous lights allowed on the material.
  74736. */
  74737. _this._maxSimultaneousLights = 4;
  74738. _this.maxSimultaneousLights = 4;
  74739. /**
  74740. * Keep track of the image processing observer to allow dispose and replace.
  74741. */
  74742. _this._imageProcessingObserver = null;
  74743. // Temp values kept as cache in the material.
  74744. _this._renderTargets = new BABYLON.SmartArray(16);
  74745. // Setup the default processing configuration to the scene.
  74746. _this._attachImageProcessingConfiguration(null);
  74747. _this.getRenderTargetTextures = function () {
  74748. _this._renderTargets.reset();
  74749. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  74750. _this._renderTargets.push(_this._diffuseTexture);
  74751. }
  74752. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  74753. _this._renderTargets.push(_this._reflectionTexture);
  74754. }
  74755. return _this._renderTargets;
  74756. };
  74757. return _this;
  74758. }
  74759. /**
  74760. * Attaches a new image processing configuration to the PBR Material.
  74761. * @param configuration (if null the scene configuration will be use)
  74762. */
  74763. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  74764. var _this = this;
  74765. if (configuration === this._imageProcessingConfiguration) {
  74766. return;
  74767. }
  74768. // Detaches observer.
  74769. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  74770. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  74771. }
  74772. // Pick the scene configuration if needed.
  74773. if (!configuration) {
  74774. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  74775. }
  74776. else {
  74777. this._imageProcessingConfiguration = configuration;
  74778. }
  74779. // Attaches observer.
  74780. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  74781. _this._markAllSubMeshesAsImageProcessingDirty();
  74782. });
  74783. };
  74784. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  74785. /**
  74786. * Gets the image processing configuration used either in this material.
  74787. */
  74788. get: function () {
  74789. return this._imageProcessingConfiguration;
  74790. },
  74791. /**
  74792. * Sets the Default image processing configuration used either in the this material.
  74793. *
  74794. * If sets to null, the scene one is in use.
  74795. */
  74796. set: function (value) {
  74797. this._attachImageProcessingConfiguration(value);
  74798. // Ensure the effect will be rebuilt.
  74799. this._markAllSubMeshesAsTexturesDirty();
  74800. },
  74801. enumerable: true,
  74802. configurable: true
  74803. });
  74804. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  74805. /**
  74806. * Gets wether the color curves effect is enabled.
  74807. */
  74808. get: function () {
  74809. return this.imageProcessingConfiguration.colorCurvesEnabled;
  74810. },
  74811. /**
  74812. * Sets wether the color curves effect is enabled.
  74813. */
  74814. set: function (value) {
  74815. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  74816. },
  74817. enumerable: true,
  74818. configurable: true
  74819. });
  74820. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  74821. /**
  74822. * Gets wether the color grading effect is enabled.
  74823. */
  74824. get: function () {
  74825. return this.imageProcessingConfiguration.colorGradingEnabled;
  74826. },
  74827. /**
  74828. * Gets wether the color grading effect is enabled.
  74829. */
  74830. set: function (value) {
  74831. this.imageProcessingConfiguration.colorGradingEnabled = value;
  74832. },
  74833. enumerable: true,
  74834. configurable: true
  74835. });
  74836. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  74837. /**
  74838. * Gets wether tonemapping is enabled or not.
  74839. */
  74840. get: function () {
  74841. return this._imageProcessingConfiguration.toneMappingEnabled;
  74842. },
  74843. /**
  74844. * Sets wether tonemapping is enabled or not
  74845. */
  74846. set: function (value) {
  74847. this._imageProcessingConfiguration.toneMappingEnabled = value;
  74848. },
  74849. enumerable: true,
  74850. configurable: true
  74851. });
  74852. ;
  74853. ;
  74854. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  74855. /**
  74856. * The camera exposure used on this material.
  74857. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  74858. * This corresponds to a photographic exposure.
  74859. */
  74860. get: function () {
  74861. return this._imageProcessingConfiguration.exposure;
  74862. },
  74863. /**
  74864. * The camera exposure used on this material.
  74865. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  74866. * This corresponds to a photographic exposure.
  74867. */
  74868. set: function (value) {
  74869. this._imageProcessingConfiguration.exposure = value;
  74870. },
  74871. enumerable: true,
  74872. configurable: true
  74873. });
  74874. ;
  74875. ;
  74876. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  74877. /**
  74878. * Gets The camera contrast used on this material.
  74879. */
  74880. get: function () {
  74881. return this._imageProcessingConfiguration.contrast;
  74882. },
  74883. /**
  74884. * Sets The camera contrast used on this material.
  74885. */
  74886. set: function (value) {
  74887. this._imageProcessingConfiguration.contrast = value;
  74888. },
  74889. enumerable: true,
  74890. configurable: true
  74891. });
  74892. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  74893. /**
  74894. * Gets the Color Grading 2D Lookup Texture.
  74895. */
  74896. get: function () {
  74897. return this._imageProcessingConfiguration.colorGradingTexture;
  74898. },
  74899. /**
  74900. * Sets the Color Grading 2D Lookup Texture.
  74901. */
  74902. set: function (value) {
  74903. this.imageProcessingConfiguration.colorGradingTexture = value;
  74904. },
  74905. enumerable: true,
  74906. configurable: true
  74907. });
  74908. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  74909. /**
  74910. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  74911. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  74912. * 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;
  74913. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  74914. */
  74915. get: function () {
  74916. return this.imageProcessingConfiguration.colorCurves;
  74917. },
  74918. /**
  74919. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  74920. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  74921. * 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;
  74922. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  74923. */
  74924. set: function (value) {
  74925. this.imageProcessingConfiguration.colorCurves = value;
  74926. },
  74927. enumerable: true,
  74928. configurable: true
  74929. });
  74930. /**
  74931. * The entire material has been created in order to prevent overdraw.
  74932. * @returns false
  74933. */
  74934. BackgroundMaterial.prototype.needAlphaTesting = function () {
  74935. return false;
  74936. };
  74937. /**
  74938. * The entire material has been created in order to prevent overdraw.
  74939. * @returns true if blending is enable
  74940. */
  74941. BackgroundMaterial.prototype.needAlphaBlending = function () {
  74942. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  74943. };
  74944. /**
  74945. * Checks wether the material is ready to be rendered for a given mesh.
  74946. * @param mesh The mesh to render
  74947. * @param subMesh The submesh to check against
  74948. * @param useInstances Specify wether or not the material is used with instances
  74949. */
  74950. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74951. var _this = this;
  74952. if (useInstances === void 0) { useInstances = false; }
  74953. if (subMesh.effect && this.isFrozen) {
  74954. if (this._wasPreviouslyReady) {
  74955. return true;
  74956. }
  74957. }
  74958. if (!subMesh._materialDefines) {
  74959. subMesh._materialDefines = new BackgroundMaterialDefines();
  74960. }
  74961. var scene = this.getScene();
  74962. var defines = subMesh._materialDefines;
  74963. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  74964. if (defines._renderId === scene.getRenderId()) {
  74965. return true;
  74966. }
  74967. }
  74968. var engine = scene.getEngine();
  74969. // Lights
  74970. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  74971. defines._needNormals = true;
  74972. // Textures
  74973. if (defines._areTexturesDirty) {
  74974. defines._needUVs = false;
  74975. if (scene.texturesEnabled) {
  74976. if (scene.getEngine().getCaps().textureLOD) {
  74977. defines.TEXTURELODSUPPORT = true;
  74978. }
  74979. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  74980. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  74981. return false;
  74982. }
  74983. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  74984. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  74985. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  74986. defines.OPACITYFRESNEL = this._opacityFresnel;
  74987. }
  74988. else {
  74989. defines.DIFFUSE = false;
  74990. defines.DIFFUSEHASALPHA = false;
  74991. defines.GAMMADIFFUSE = false;
  74992. defines.OPACITYFRESNEL = false;
  74993. }
  74994. var reflectionTexture = this._reflectionTexture;
  74995. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  74996. if (!reflectionTexture.isReadyOrNotBlocking()) {
  74997. return false;
  74998. }
  74999. defines.REFLECTION = true;
  75000. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  75001. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  75002. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  75003. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  75004. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  75005. defines.INVERTCUBICMAP = true;
  75006. }
  75007. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  75008. switch (reflectionTexture.coordinatesMode) {
  75009. case BABYLON.Texture.CUBIC_MODE:
  75010. case BABYLON.Texture.INVCUBIC_MODE:
  75011. defines.REFLECTIONMAP_CUBIC = true;
  75012. break;
  75013. case BABYLON.Texture.EXPLICIT_MODE:
  75014. defines.REFLECTIONMAP_EXPLICIT = true;
  75015. break;
  75016. case BABYLON.Texture.PLANAR_MODE:
  75017. defines.REFLECTIONMAP_PLANAR = true;
  75018. break;
  75019. case BABYLON.Texture.PROJECTION_MODE:
  75020. defines.REFLECTIONMAP_PROJECTION = true;
  75021. break;
  75022. case BABYLON.Texture.SKYBOX_MODE:
  75023. defines.REFLECTIONMAP_SKYBOX = true;
  75024. break;
  75025. case BABYLON.Texture.SPHERICAL_MODE:
  75026. defines.REFLECTIONMAP_SPHERICAL = true;
  75027. break;
  75028. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  75029. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  75030. break;
  75031. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  75032. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  75033. break;
  75034. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  75035. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  75036. break;
  75037. }
  75038. }
  75039. else {
  75040. defines.REFLECTION = false;
  75041. defines.REFLECTIONBLUR = false;
  75042. defines.REFLECTIONMAP_3D = false;
  75043. defines.REFLECTIONMAP_SPHERICAL = false;
  75044. defines.REFLECTIONMAP_PLANAR = false;
  75045. defines.REFLECTIONMAP_CUBIC = false;
  75046. defines.REFLECTIONMAP_PROJECTION = false;
  75047. defines.REFLECTIONMAP_SKYBOX = false;
  75048. defines.REFLECTIONMAP_EXPLICIT = false;
  75049. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75050. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75051. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75052. defines.INVERTCUBICMAP = false;
  75053. defines.REFLECTIONMAP_OPPOSITEZ = false;
  75054. defines.LODINREFLECTIONALPHA = false;
  75055. defines.GAMMAREFLECTION = false;
  75056. }
  75057. }
  75058. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  75059. defines.USERGBCOLOR = this._useRGBColor;
  75060. }
  75061. if (defines._areImageProcessingDirty) {
  75062. if (!this._imageProcessingConfiguration.isReady()) {
  75063. return false;
  75064. }
  75065. this._imageProcessingConfiguration.prepareDefines(defines);
  75066. }
  75067. // Misc.
  75068. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  75069. // Values that need to be evaluated on every frame
  75070. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  75071. // Attribs
  75072. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  75073. if (mesh) {
  75074. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75075. mesh.createNormals(true);
  75076. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  75077. }
  75078. }
  75079. }
  75080. // Get correct effect
  75081. if (defines.isDirty) {
  75082. defines.markAsProcessed();
  75083. scene.resetCachedMaterial();
  75084. // Fallbacks
  75085. var fallbacks = new BABYLON.EffectFallbacks();
  75086. if (defines.FOG) {
  75087. fallbacks.addFallback(0, "FOG");
  75088. }
  75089. if (defines.POINTSIZE) {
  75090. fallbacks.addFallback(1, "POINTSIZE");
  75091. }
  75092. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  75093. if (defines.NUM_BONE_INFLUENCERS > 0) {
  75094. fallbacks.addCPUSkinningFallback(0, mesh);
  75095. }
  75096. //Attributes
  75097. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75098. if (defines.NORMAL) {
  75099. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75100. }
  75101. if (defines.UV1) {
  75102. attribs.push(BABYLON.VertexBuffer.UVKind);
  75103. }
  75104. if (defines.UV2) {
  75105. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75106. }
  75107. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  75108. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  75109. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  75110. "vFogInfos", "vFogColor", "pointSize",
  75111. "vClipPlane", "mBones",
  75112. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  75113. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  75114. "shadowLevel", "alpha",
  75115. "vDiffuseInfos", "diffuseMatrix",
  75116. ];
  75117. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  75118. var uniformBuffers = ["Material", "Scene"];
  75119. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  75120. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  75121. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  75122. uniformsNames: uniforms,
  75123. uniformBuffersNames: uniformBuffers,
  75124. samplers: samplers,
  75125. defines: defines,
  75126. maxSimultaneousLights: this._maxSimultaneousLights
  75127. });
  75128. var onCompiled = function (effect) {
  75129. if (_this.onCompiled) {
  75130. _this.onCompiled(effect);
  75131. }
  75132. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  75133. };
  75134. var join = defines.toString();
  75135. subMesh.setEffect(scene.getEngine().createEffect("background", {
  75136. attributes: attribs,
  75137. uniformsNames: uniforms,
  75138. uniformBuffersNames: uniformBuffers,
  75139. samplers: samplers,
  75140. defines: join,
  75141. fallbacks: fallbacks,
  75142. onCompiled: onCompiled,
  75143. onError: this.onError,
  75144. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  75145. }, engine), defines);
  75146. this.buildUniformLayout();
  75147. }
  75148. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75149. return false;
  75150. }
  75151. defines._renderId = scene.getRenderId();
  75152. this._wasPreviouslyReady = true;
  75153. return true;
  75154. };
  75155. /**
  75156. * Build the uniform buffer used in the material.
  75157. */
  75158. BackgroundMaterial.prototype.buildUniformLayout = function () {
  75159. // Order is important !
  75160. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  75161. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  75162. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  75163. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  75164. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  75165. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  75166. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  75167. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  75168. this._uniformBuffer.addUniform("pointSize", 1);
  75169. this._uniformBuffer.addUniform("shadowLevel", 1);
  75170. this._uniformBuffer.addUniform("alpha", 1);
  75171. this._uniformBuffer.create();
  75172. };
  75173. /**
  75174. * Unbind the material.
  75175. */
  75176. BackgroundMaterial.prototype.unbind = function () {
  75177. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  75178. this._uniformBuffer.setTexture("diffuseSampler", null);
  75179. }
  75180. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  75181. this._uniformBuffer.setTexture("reflectionSampler", null);
  75182. }
  75183. _super.prototype.unbind.call(this);
  75184. };
  75185. /**
  75186. * Bind only the world matrix to the material.
  75187. * @param world The world matrix to bind.
  75188. */
  75189. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  75190. this._activeEffect.setMatrix("world", world);
  75191. };
  75192. /**
  75193. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  75194. * @param world The world matrix to bind.
  75195. * @param subMesh The submesh to bind for.
  75196. */
  75197. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75198. var scene = this.getScene();
  75199. var defines = subMesh._materialDefines;
  75200. if (!defines) {
  75201. return;
  75202. }
  75203. var effect = subMesh.effect;
  75204. if (!effect) {
  75205. return;
  75206. }
  75207. this._activeEffect = effect;
  75208. // Matrices
  75209. this.bindOnlyWorldMatrix(world);
  75210. // Bones
  75211. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  75212. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  75213. if (mustRebind) {
  75214. this._uniformBuffer.bindToEffect(effect, "Material");
  75215. this.bindViewProjection(effect);
  75216. var reflectionTexture = this._reflectionTexture;
  75217. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  75218. // Texture uniforms
  75219. if (scene.texturesEnabled) {
  75220. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75221. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  75222. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  75223. }
  75224. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75225. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  75226. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  75227. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  75228. }
  75229. }
  75230. if (this.shadowLevel > 0) {
  75231. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  75232. }
  75233. this._uniformBuffer.updateFloat("alpha", this.alpha);
  75234. // Point size
  75235. if (this.pointsCloud) {
  75236. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  75237. }
  75238. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  75239. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  75240. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  75241. }
  75242. // Textures
  75243. if (scene.texturesEnabled) {
  75244. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75245. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  75246. }
  75247. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75248. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  75249. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75250. }
  75251. else if (!defines.REFLECTIONBLUR) {
  75252. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75253. }
  75254. else {
  75255. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  75256. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  75257. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  75258. }
  75259. }
  75260. }
  75261. // Clip plane
  75262. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  75263. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  75264. }
  75265. if (mustRebind || !this.isFrozen) {
  75266. if (scene.lightsEnabled) {
  75267. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  75268. }
  75269. // View
  75270. this.bindView(effect);
  75271. // Fog
  75272. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75273. // image processing
  75274. this._imageProcessingConfiguration.bind(this._activeEffect);
  75275. }
  75276. this._uniformBuffer.update();
  75277. this._afterBind(mesh);
  75278. };
  75279. /**
  75280. * Dispose the material.
  75281. * @forceDisposeEffect Force disposal of the associated effect.
  75282. * @forceDisposeTextures Force disposal of the associated textures.
  75283. */
  75284. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75285. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  75286. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  75287. if (forceDisposeTextures) {
  75288. if (this.diffuseTexture) {
  75289. this.diffuseTexture.dispose();
  75290. }
  75291. if (this.reflectionTexture) {
  75292. this.reflectionTexture.dispose();
  75293. }
  75294. }
  75295. this._renderTargets.dispose();
  75296. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75297. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75298. }
  75299. _super.prototype.dispose.call(this, forceDisposeEffect);
  75300. };
  75301. /**
  75302. * Clones the material.
  75303. * @name The cloned name.
  75304. * @returns The cloned material.
  75305. */
  75306. BackgroundMaterial.prototype.clone = function (name) {
  75307. var _this = this;
  75308. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  75309. };
  75310. /**
  75311. * Serializes the current material to its JSON representation.
  75312. * @returns The JSON representation.
  75313. */
  75314. BackgroundMaterial.prototype.serialize = function () {
  75315. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75316. serializationObject.customType = "BABYLON.BackgroundMaterial";
  75317. return serializationObject;
  75318. };
  75319. /**
  75320. * Gets the class name of the material
  75321. * @returns "BackgroundMaterial"
  75322. */
  75323. BackgroundMaterial.prototype.getClassName = function () {
  75324. return "BackgroundMaterial";
  75325. };
  75326. /**
  75327. * Parse a JSON input to create back a background material.
  75328. * @param source
  75329. * @param scene
  75330. * @param rootUrl
  75331. * @returns the instantiated BackgroundMaterial.
  75332. */
  75333. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  75334. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  75335. };
  75336. __decorate([
  75337. BABYLON.serializeAsColor3()
  75338. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  75339. __decorate([
  75340. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75341. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  75342. __decorate([
  75343. BABYLON.serialize()
  75344. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  75345. __decorate([
  75346. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75347. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  75348. __decorate([
  75349. BABYLON.serializeAsColor3()
  75350. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  75351. __decorate([
  75352. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75353. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  75354. __decorate([
  75355. BABYLON.serialize()
  75356. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  75357. __decorate([
  75358. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75359. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  75360. __decorate([
  75361. BABYLON.serializeAsColor3()
  75362. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  75363. __decorate([
  75364. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75365. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  75366. __decorate([
  75367. BABYLON.serialize()
  75368. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  75369. __decorate([
  75370. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75371. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  75372. __decorate([
  75373. BABYLON.serializeAsTexture()
  75374. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  75375. __decorate([
  75376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75377. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  75378. __decorate([
  75379. BABYLON.serialize()
  75380. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  75381. __decorate([
  75382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75383. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  75384. __decorate([
  75385. BABYLON.serializeAsTexture()
  75386. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  75387. __decorate([
  75388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75389. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  75390. __decorate([
  75391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75392. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  75393. __decorate([
  75394. BABYLON.serialize()
  75395. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  75396. __decorate([
  75397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75398. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  75399. __decorate([
  75400. BABYLON.serialize()
  75401. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  75402. __decorate([
  75403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75404. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  75405. __decorate([
  75406. BABYLON.serialize()
  75407. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  75408. __decorate([
  75409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75410. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  75411. __decorate([
  75412. BABYLON.serialize()
  75413. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  75414. __decorate([
  75415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75416. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  75417. __decorate([
  75418. BABYLON.serialize()
  75419. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  75420. __decorate([
  75421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75422. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  75423. __decorate([
  75424. BABYLON.serializeAsImageProcessingConfiguration()
  75425. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  75426. return BackgroundMaterial;
  75427. }(BABYLON.PushMaterial));
  75428. BABYLON.BackgroundMaterial = BackgroundMaterial;
  75429. })(BABYLON || (BABYLON = {}));
  75430. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  75431. 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";
  75432. 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}";
  75433. 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";
  75434. 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};";
  75435. 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";
  75436. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  75437. var BABYLON;
  75438. (function (BABYLON) {
  75439. var GLTFLoaderCoordinateSystemMode;
  75440. (function (GLTFLoaderCoordinateSystemMode) {
  75441. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  75442. // 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.
  75443. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  75444. // The glTF right-handed data is not transformed in any form and is loaded directly.
  75445. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  75446. // Sets the useRightHandedSystem flag on the scene.
  75447. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  75448. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  75449. var GLTFFileLoader = /** @class */ (function () {
  75450. function GLTFFileLoader() {
  75451. // V2 options
  75452. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  75453. this.name = "gltf";
  75454. this.extensions = {
  75455. ".gltf": { isBinary: false },
  75456. ".glb": { isBinary: true }
  75457. };
  75458. }
  75459. GLTFFileLoader.prototype.dispose = function () {
  75460. if (this._loader) {
  75461. this._loader.dispose();
  75462. this._loader = null;
  75463. }
  75464. };
  75465. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75466. var loaderData = GLTFFileLoader._parse(data, onError);
  75467. if (!loaderData) {
  75468. return;
  75469. }
  75470. if (this.onParsed) {
  75471. this.onParsed(loaderData);
  75472. }
  75473. this._loader = this._getLoader(loaderData, onError);
  75474. if (!this._loader) {
  75475. return;
  75476. }
  75477. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  75478. };
  75479. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  75480. var loaderData = GLTFFileLoader._parse(data, onError);
  75481. if (!loaderData) {
  75482. return;
  75483. }
  75484. if (this.onParsed) {
  75485. this.onParsed(loaderData);
  75486. }
  75487. this._loader = this._getLoader(loaderData, onError);
  75488. if (!this._loader) {
  75489. return;
  75490. }
  75491. return this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  75492. };
  75493. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  75494. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  75495. };
  75496. GLTFFileLoader._parse = function (data, onError) {
  75497. try {
  75498. if (data instanceof ArrayBuffer) {
  75499. return GLTFFileLoader._parseBinary(data, onError);
  75500. }
  75501. return {
  75502. json: JSON.parse(data),
  75503. bin: null
  75504. };
  75505. }
  75506. catch (e) {
  75507. onError(e.message);
  75508. return null;
  75509. }
  75510. };
  75511. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  75512. var loaderVersion = { major: 2, minor: 0 };
  75513. var asset = loaderData.json.asset || {};
  75514. var version = GLTFFileLoader._parseVersion(asset.version);
  75515. if (!version) {
  75516. onError("Invalid version: " + asset.version);
  75517. return null;
  75518. }
  75519. if (asset.minVersion !== undefined) {
  75520. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  75521. if (!minVersion) {
  75522. onError("Invalid minimum version: " + asset.minVersion);
  75523. return null;
  75524. }
  75525. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  75526. onError("Incompatible minimum version: " + asset.minVersion);
  75527. return null;
  75528. }
  75529. }
  75530. var createLoaders = {
  75531. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  75532. 2: GLTFFileLoader.CreateGLTFLoaderV2
  75533. };
  75534. var createLoader = createLoaders[version.major];
  75535. if (!createLoader) {
  75536. onError("Unsupported version: " + asset.version);
  75537. return null;
  75538. }
  75539. return createLoader(this);
  75540. };
  75541. GLTFFileLoader._parseBinary = function (data, onError) {
  75542. var Binary = {
  75543. Magic: 0x46546C67
  75544. };
  75545. var binaryReader = new BinaryReader(data);
  75546. var magic = binaryReader.readUint32();
  75547. if (magic !== Binary.Magic) {
  75548. onError("Unexpected magic: " + magic);
  75549. return null;
  75550. }
  75551. var version = binaryReader.readUint32();
  75552. switch (version) {
  75553. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  75554. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  75555. }
  75556. onError("Unsupported version: " + version);
  75557. return null;
  75558. };
  75559. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  75560. var ContentFormat = {
  75561. JSON: 0
  75562. };
  75563. var length = binaryReader.readUint32();
  75564. if (length != binaryReader.getLength()) {
  75565. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  75566. return null;
  75567. }
  75568. var contentLength = binaryReader.readUint32();
  75569. var contentFormat = binaryReader.readUint32();
  75570. var content;
  75571. switch (contentFormat) {
  75572. case ContentFormat.JSON:
  75573. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  75574. break;
  75575. default:
  75576. onError("Unexpected content format: " + contentFormat);
  75577. return null;
  75578. }
  75579. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  75580. var body = binaryReader.readUint8Array(bytesRemaining);
  75581. return {
  75582. json: content,
  75583. bin: body
  75584. };
  75585. };
  75586. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  75587. var ChunkFormat = {
  75588. JSON: 0x4E4F534A,
  75589. BIN: 0x004E4942
  75590. };
  75591. var length = binaryReader.readUint32();
  75592. if (length !== binaryReader.getLength()) {
  75593. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  75594. return null;
  75595. }
  75596. // JSON chunk
  75597. var chunkLength = binaryReader.readUint32();
  75598. var chunkFormat = binaryReader.readUint32();
  75599. if (chunkFormat !== ChunkFormat.JSON) {
  75600. onError("First chunk format is not JSON");
  75601. return null;
  75602. }
  75603. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  75604. // Look for BIN chunk
  75605. var bin = null;
  75606. while (binaryReader.getPosition() < binaryReader.getLength()) {
  75607. var chunkLength_1 = binaryReader.readUint32();
  75608. var chunkFormat_1 = binaryReader.readUint32();
  75609. switch (chunkFormat_1) {
  75610. case ChunkFormat.JSON:
  75611. onError("Unexpected JSON chunk");
  75612. return null;
  75613. case ChunkFormat.BIN:
  75614. bin = binaryReader.readUint8Array(chunkLength_1);
  75615. break;
  75616. default:
  75617. // ignore unrecognized chunkFormat
  75618. binaryReader.skipBytes(chunkLength_1);
  75619. break;
  75620. }
  75621. }
  75622. return {
  75623. json: json,
  75624. bin: bin
  75625. };
  75626. };
  75627. GLTFFileLoader._parseVersion = function (version) {
  75628. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  75629. if (!match) {
  75630. return null;
  75631. }
  75632. return {
  75633. major: parseInt(match[1]),
  75634. minor: parseInt(match[2])
  75635. };
  75636. };
  75637. GLTFFileLoader._compareVersion = function (a, b) {
  75638. if (a.major > b.major)
  75639. return 1;
  75640. if (a.major < b.major)
  75641. return -1;
  75642. if (a.minor > b.minor)
  75643. return 1;
  75644. if (a.minor < b.minor)
  75645. return -1;
  75646. return 0;
  75647. };
  75648. GLTFFileLoader._decodeBufferToText = function (buffer) {
  75649. var result = "";
  75650. var length = buffer.byteLength;
  75651. for (var i = 0; i < length; i++) {
  75652. result += String.fromCharCode(buffer[i]);
  75653. }
  75654. return result;
  75655. };
  75656. // V1 options
  75657. GLTFFileLoader.HomogeneousCoordinates = false;
  75658. GLTFFileLoader.IncrementalLoading = true;
  75659. return GLTFFileLoader;
  75660. }());
  75661. BABYLON.GLTFFileLoader = GLTFFileLoader;
  75662. var BinaryReader = /** @class */ (function () {
  75663. function BinaryReader(arrayBuffer) {
  75664. this._arrayBuffer = arrayBuffer;
  75665. this._dataView = new DataView(arrayBuffer);
  75666. this._byteOffset = 0;
  75667. }
  75668. BinaryReader.prototype.getPosition = function () {
  75669. return this._byteOffset;
  75670. };
  75671. BinaryReader.prototype.getLength = function () {
  75672. return this._arrayBuffer.byteLength;
  75673. };
  75674. BinaryReader.prototype.readUint32 = function () {
  75675. var value = this._dataView.getUint32(this._byteOffset, true);
  75676. this._byteOffset += 4;
  75677. return value;
  75678. };
  75679. BinaryReader.prototype.readUint8Array = function (length) {
  75680. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  75681. this._byteOffset += length;
  75682. return value;
  75683. };
  75684. BinaryReader.prototype.skipBytes = function (length) {
  75685. this._byteOffset += length;
  75686. };
  75687. return BinaryReader;
  75688. }());
  75689. if (BABYLON.SceneLoader) {
  75690. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  75691. }
  75692. })(BABYLON || (BABYLON = {}));
  75693. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  75694. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75695. var BABYLON;
  75696. (function (BABYLON) {
  75697. var GLTF1;
  75698. (function (GLTF1) {
  75699. /**
  75700. * Enums
  75701. */
  75702. var EComponentType;
  75703. (function (EComponentType) {
  75704. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  75705. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  75706. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  75707. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  75708. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  75709. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  75710. var EShaderType;
  75711. (function (EShaderType) {
  75712. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  75713. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  75714. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  75715. var EParameterType;
  75716. (function (EParameterType) {
  75717. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  75718. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  75719. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  75720. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  75721. EParameterType[EParameterType["INT"] = 5124] = "INT";
  75722. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  75723. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  75724. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  75725. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  75726. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  75727. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  75728. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  75729. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  75730. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  75731. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  75732. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  75733. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  75734. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  75735. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  75736. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  75737. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  75738. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  75739. var ETextureWrapMode;
  75740. (function (ETextureWrapMode) {
  75741. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  75742. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  75743. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  75744. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  75745. var ETextureFilterType;
  75746. (function (ETextureFilterType) {
  75747. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  75748. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  75749. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  75750. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  75751. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  75752. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  75753. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  75754. var ETextureFormat;
  75755. (function (ETextureFormat) {
  75756. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  75757. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  75758. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  75759. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  75760. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  75761. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  75762. var ECullingType;
  75763. (function (ECullingType) {
  75764. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  75765. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  75766. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  75767. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  75768. var EBlendingFunction;
  75769. (function (EBlendingFunction) {
  75770. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  75771. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  75772. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  75773. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  75774. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  75775. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  75776. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  75777. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  75778. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  75779. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  75780. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  75781. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  75782. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  75783. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  75784. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  75785. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  75786. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  75787. })(BABYLON || (BABYLON = {}));
  75788. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  75789. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75790. var BABYLON;
  75791. (function (BABYLON) {
  75792. var GLTF1;
  75793. (function (GLTF1) {
  75794. /**
  75795. * Tokenizer. Used for shaders compatibility
  75796. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  75797. */
  75798. var ETokenType;
  75799. (function (ETokenType) {
  75800. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  75801. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  75802. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  75803. })(ETokenType || (ETokenType = {}));
  75804. var Tokenizer = /** @class */ (function () {
  75805. function Tokenizer(toParse) {
  75806. this._pos = 0;
  75807. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  75808. this._toParse = toParse;
  75809. this._maxPos = toParse.length;
  75810. }
  75811. Tokenizer.prototype.getNextToken = function () {
  75812. if (this.isEnd())
  75813. return ETokenType.END_OF_INPUT;
  75814. this.currentString = this.read();
  75815. this.currentToken = ETokenType.UNKNOWN;
  75816. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  75817. this.currentToken = ETokenType.IDENTIFIER;
  75818. this.currentIdentifier = this.currentString;
  75819. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  75820. this.currentIdentifier += this.currentString;
  75821. this.forward();
  75822. }
  75823. }
  75824. return this.currentToken;
  75825. };
  75826. Tokenizer.prototype.peek = function () {
  75827. return this._toParse[this._pos];
  75828. };
  75829. Tokenizer.prototype.read = function () {
  75830. return this._toParse[this._pos++];
  75831. };
  75832. Tokenizer.prototype.forward = function () {
  75833. this._pos++;
  75834. };
  75835. Tokenizer.prototype.isEnd = function () {
  75836. return this._pos >= this._maxPos;
  75837. };
  75838. return Tokenizer;
  75839. }());
  75840. /**
  75841. * Values
  75842. */
  75843. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  75844. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  75845. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  75846. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  75847. /**
  75848. * Parse
  75849. */
  75850. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  75851. for (var buf in parsedBuffers) {
  75852. var parsedBuffer = parsedBuffers[buf];
  75853. gltfRuntime.buffers[buf] = parsedBuffer;
  75854. gltfRuntime.buffersCount++;
  75855. }
  75856. };
  75857. var parseShaders = function (parsedShaders, gltfRuntime) {
  75858. for (var sha in parsedShaders) {
  75859. var parsedShader = parsedShaders[sha];
  75860. gltfRuntime.shaders[sha] = parsedShader;
  75861. gltfRuntime.shaderscount++;
  75862. }
  75863. };
  75864. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  75865. for (var object in parsedObjects) {
  75866. var parsedObject = parsedObjects[object];
  75867. gltfRuntime[runtimeProperty][object] = parsedObject;
  75868. }
  75869. };
  75870. /**
  75871. * Utils
  75872. */
  75873. var normalizeUVs = function (buffer) {
  75874. if (!buffer) {
  75875. return;
  75876. }
  75877. for (var i = 0; i < buffer.length / 2; i++) {
  75878. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  75879. }
  75880. };
  75881. var getAttribute = function (attributeParameter) {
  75882. if (attributeParameter.semantic === "NORMAL") {
  75883. return "normal";
  75884. }
  75885. else if (attributeParameter.semantic === "POSITION") {
  75886. return "position";
  75887. }
  75888. else if (attributeParameter.semantic === "JOINT") {
  75889. return "matricesIndices";
  75890. }
  75891. else if (attributeParameter.semantic === "WEIGHT") {
  75892. return "matricesWeights";
  75893. }
  75894. else if (attributeParameter.semantic === "COLOR") {
  75895. return "color";
  75896. }
  75897. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  75898. var channel = Number(attributeParameter.semantic.split("_")[1]);
  75899. return "uv" + (channel === 0 ? "" : channel + 1);
  75900. }
  75901. return null;
  75902. };
  75903. /**
  75904. * Loads and creates animations
  75905. */
  75906. var loadAnimations = function (gltfRuntime) {
  75907. for (var anim in gltfRuntime.animations) {
  75908. var animation = gltfRuntime.animations[anim];
  75909. if (!animation.channels || !animation.samplers) {
  75910. continue;
  75911. }
  75912. var lastAnimation = null;
  75913. for (var i = 0; i < animation.channels.length; i++) {
  75914. // Get parameters and load buffers
  75915. var channel = animation.channels[i];
  75916. var sampler = animation.samplers[channel.sampler];
  75917. if (!sampler) {
  75918. continue;
  75919. }
  75920. var inputData = null;
  75921. var outputData = null;
  75922. if (animation.parameters) {
  75923. inputData = animation.parameters[sampler.input];
  75924. outputData = animation.parameters[sampler.output];
  75925. }
  75926. else {
  75927. inputData = sampler.input;
  75928. outputData = sampler.output;
  75929. }
  75930. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  75931. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  75932. var targetID = channel.target.id;
  75933. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  75934. if (targetNode === null) {
  75935. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  75936. }
  75937. if (targetNode === null) {
  75938. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  75939. continue;
  75940. }
  75941. var isBone = targetNode instanceof BABYLON.Bone;
  75942. // Get target path (position, rotation or scaling)
  75943. var targetPath = channel.target.path;
  75944. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  75945. if (targetPathIndex !== -1) {
  75946. targetPath = babylonAnimationPaths[targetPathIndex];
  75947. }
  75948. // Determine animation type
  75949. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  75950. if (!isBone) {
  75951. if (targetPath === "rotationQuaternion") {
  75952. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  75953. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  75954. }
  75955. else {
  75956. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  75957. }
  75958. }
  75959. // Create animation and key frames
  75960. var babylonAnimation = null;
  75961. var keys = [];
  75962. var arrayOffset = 0;
  75963. var modifyKey = false;
  75964. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  75965. babylonAnimation = lastAnimation;
  75966. modifyKey = true;
  75967. }
  75968. if (!modifyKey) {
  75969. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  75970. }
  75971. // For each frame
  75972. for (var j = 0; j < bufferInput.length; j++) {
  75973. var value = null;
  75974. if (targetPath === "rotationQuaternion") {
  75975. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  75976. arrayOffset += 4;
  75977. }
  75978. else {
  75979. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  75980. arrayOffset += 3;
  75981. }
  75982. if (isBone) {
  75983. var bone = targetNode;
  75984. var translation = BABYLON.Vector3.Zero();
  75985. var rotationQuaternion = new BABYLON.Quaternion();
  75986. var scaling = BABYLON.Vector3.Zero();
  75987. // Warning on decompose
  75988. var mat = bone.getBaseMatrix();
  75989. if (modifyKey && lastAnimation) {
  75990. mat = lastAnimation.getKeys()[j].value;
  75991. }
  75992. mat.decompose(scaling, rotationQuaternion, translation);
  75993. if (targetPath === "position") {
  75994. translation = value;
  75995. }
  75996. else if (targetPath === "rotationQuaternion") {
  75997. rotationQuaternion = value;
  75998. }
  75999. else {
  76000. scaling = value;
  76001. }
  76002. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  76003. }
  76004. if (!modifyKey) {
  76005. keys.push({
  76006. frame: bufferInput[j],
  76007. value: value
  76008. });
  76009. }
  76010. else if (lastAnimation) {
  76011. lastAnimation.getKeys()[j].value = value;
  76012. }
  76013. }
  76014. // Finish
  76015. if (!modifyKey && babylonAnimation) {
  76016. babylonAnimation.setKeys(keys);
  76017. targetNode.animations.push(babylonAnimation);
  76018. }
  76019. lastAnimation = babylonAnimation;
  76020. gltfRuntime.scene.stopAnimation(targetNode);
  76021. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  76022. }
  76023. }
  76024. };
  76025. /**
  76026. * Returns the bones transformation matrix
  76027. */
  76028. var configureBoneTransformation = function (node) {
  76029. var mat = null;
  76030. if (node.translation || node.rotation || node.scale) {
  76031. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  76032. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  76033. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  76034. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  76035. }
  76036. else {
  76037. mat = BABYLON.Matrix.FromArray(node.matrix);
  76038. }
  76039. return mat;
  76040. };
  76041. /**
  76042. * Returns the parent bone
  76043. */
  76044. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  76045. // Try to find
  76046. for (var i = 0; i < newSkeleton.bones.length; i++) {
  76047. if (newSkeleton.bones[i].name === jointName) {
  76048. return newSkeleton.bones[i];
  76049. }
  76050. }
  76051. // Not found, search in gltf nodes
  76052. var nodes = gltfRuntime.nodes;
  76053. for (var nde in nodes) {
  76054. var node = nodes[nde];
  76055. if (!node.jointName) {
  76056. continue;
  76057. }
  76058. var children = node.children;
  76059. for (var i = 0; i < children.length; i++) {
  76060. var child = gltfRuntime.nodes[children[i]];
  76061. if (!child.jointName) {
  76062. continue;
  76063. }
  76064. if (child.jointName === jointName) {
  76065. var mat = configureBoneTransformation(node);
  76066. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  76067. bone.id = nde;
  76068. return bone;
  76069. }
  76070. }
  76071. }
  76072. return null;
  76073. };
  76074. /**
  76075. * Returns the appropriate root node
  76076. */
  76077. var getNodeToRoot = function (nodesToRoot, id) {
  76078. for (var i = 0; i < nodesToRoot.length; i++) {
  76079. var nodeToRoot = nodesToRoot[i];
  76080. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  76081. var child = nodeToRoot.node.children[j];
  76082. if (child === id) {
  76083. return nodeToRoot.bone;
  76084. }
  76085. }
  76086. }
  76087. return null;
  76088. };
  76089. /**
  76090. * Returns the node with the joint name
  76091. */
  76092. var getJointNode = function (gltfRuntime, jointName) {
  76093. var nodes = gltfRuntime.nodes;
  76094. var node = nodes[jointName];
  76095. if (node) {
  76096. return {
  76097. node: node,
  76098. id: jointName
  76099. };
  76100. }
  76101. for (var nde in nodes) {
  76102. node = nodes[nde];
  76103. if (node.jointName === jointName) {
  76104. return {
  76105. node: node,
  76106. id: nde
  76107. };
  76108. }
  76109. }
  76110. return null;
  76111. };
  76112. /**
  76113. * Checks if a nodes is in joints
  76114. */
  76115. var nodeIsInJoints = function (skins, id) {
  76116. for (var i = 0; i < skins.jointNames.length; i++) {
  76117. if (skins.jointNames[i] === id) {
  76118. return true;
  76119. }
  76120. }
  76121. return false;
  76122. };
  76123. /**
  76124. * Fills the nodes to root for bones and builds hierarchy
  76125. */
  76126. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  76127. // Creates nodes for root
  76128. for (var nde in gltfRuntime.nodes) {
  76129. var node = gltfRuntime.nodes[nde];
  76130. var id = nde;
  76131. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  76132. continue;
  76133. }
  76134. // Create node to root bone
  76135. var mat = configureBoneTransformation(node);
  76136. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  76137. bone.id = id;
  76138. nodesToRoot.push({ bone: bone, node: node, id: id });
  76139. }
  76140. // Parenting
  76141. for (var i = 0; i < nodesToRoot.length; i++) {
  76142. var nodeToRoot = nodesToRoot[i];
  76143. var children = nodeToRoot.node.children;
  76144. for (var j = 0; j < children.length; j++) {
  76145. var child = null;
  76146. for (var k = 0; k < nodesToRoot.length; k++) {
  76147. if (nodesToRoot[k].id === children[j]) {
  76148. child = nodesToRoot[k];
  76149. break;
  76150. }
  76151. }
  76152. if (child) {
  76153. child.bone._parent = nodeToRoot.bone;
  76154. nodeToRoot.bone.children.push(child.bone);
  76155. }
  76156. }
  76157. }
  76158. };
  76159. /**
  76160. * Imports a skeleton
  76161. */
  76162. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  76163. if (!newSkeleton) {
  76164. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  76165. }
  76166. if (!skins.babylonSkeleton) {
  76167. return newSkeleton;
  76168. }
  76169. // Find the root bones
  76170. var nodesToRoot = [];
  76171. var nodesToRootToAdd = [];
  76172. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  76173. newSkeleton.bones = [];
  76174. // Joints
  76175. for (var i = 0; i < skins.jointNames.length; i++) {
  76176. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76177. if (!jointNode) {
  76178. continue;
  76179. }
  76180. var node = jointNode.node;
  76181. if (!node) {
  76182. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  76183. continue;
  76184. }
  76185. var id = jointNode.id;
  76186. // Optimize, if the bone already exists...
  76187. var existingBone = gltfRuntime.scene.getBoneByID(id);
  76188. if (existingBone) {
  76189. newSkeleton.bones.push(existingBone);
  76190. continue;
  76191. }
  76192. // Search for parent bone
  76193. var foundBone = false;
  76194. var parentBone = null;
  76195. for (var j = 0; j < i; j++) {
  76196. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  76197. if (!jointNode_1) {
  76198. continue;
  76199. }
  76200. var joint = jointNode_1.node;
  76201. if (!joint) {
  76202. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  76203. continue;
  76204. }
  76205. var children = joint.children;
  76206. if (!children) {
  76207. continue;
  76208. }
  76209. foundBone = false;
  76210. for (var k = 0; k < children.length; k++) {
  76211. if (children[k] === id) {
  76212. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  76213. foundBone = true;
  76214. break;
  76215. }
  76216. }
  76217. if (foundBone) {
  76218. break;
  76219. }
  76220. }
  76221. // Create bone
  76222. var mat = configureBoneTransformation(node);
  76223. if (!parentBone && nodesToRoot.length > 0) {
  76224. parentBone = getNodeToRoot(nodesToRoot, id);
  76225. if (parentBone) {
  76226. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  76227. nodesToRootToAdd.push(parentBone);
  76228. }
  76229. }
  76230. }
  76231. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  76232. bone.id = id;
  76233. }
  76234. // Polish
  76235. var bones = newSkeleton.bones;
  76236. newSkeleton.bones = [];
  76237. for (var i = 0; i < skins.jointNames.length; i++) {
  76238. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76239. if (!jointNode) {
  76240. continue;
  76241. }
  76242. for (var j = 0; j < bones.length; j++) {
  76243. if (bones[j].id === jointNode.id) {
  76244. newSkeleton.bones.push(bones[j]);
  76245. break;
  76246. }
  76247. }
  76248. }
  76249. newSkeleton.prepare();
  76250. // Finish
  76251. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  76252. newSkeleton.bones.push(nodesToRootToAdd[i]);
  76253. }
  76254. return newSkeleton;
  76255. };
  76256. /**
  76257. * Imports a mesh and its geometries
  76258. */
  76259. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  76260. if (!newMesh) {
  76261. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  76262. newMesh.id = id;
  76263. }
  76264. if (!node.babylonNode) {
  76265. return newMesh;
  76266. }
  76267. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  76268. if (!newMesh.material) {
  76269. newMesh.material = multiMat;
  76270. }
  76271. var vertexData = new BABYLON.VertexData();
  76272. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  76273. var verticesStarts = new Array();
  76274. var verticesCounts = new Array();
  76275. var indexStarts = new Array();
  76276. var indexCounts = new Array();
  76277. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76278. var meshID = meshes[meshIndex];
  76279. var mesh = gltfRuntime.meshes[meshID];
  76280. if (!mesh) {
  76281. continue;
  76282. }
  76283. // Positions, normals and UVs
  76284. for (var i = 0; i < mesh.primitives.length; i++) {
  76285. // Temporary vertex data
  76286. var tempVertexData = new BABYLON.VertexData();
  76287. var primitive = mesh.primitives[i];
  76288. if (primitive.mode !== 4) {
  76289. // continue;
  76290. }
  76291. var attributes = primitive.attributes;
  76292. var accessor = null;
  76293. var buffer = null;
  76294. // Set positions, normal and uvs
  76295. for (var semantic in attributes) {
  76296. // Link accessor and buffer view
  76297. accessor = gltfRuntime.accessors[attributes[semantic]];
  76298. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76299. if (semantic === "NORMAL") {
  76300. tempVertexData.normals = new Float32Array(buffer.length);
  76301. tempVertexData.normals.set(buffer);
  76302. }
  76303. else if (semantic === "POSITION") {
  76304. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  76305. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  76306. for (var j = 0; j < buffer.length; j += 4) {
  76307. tempVertexData.positions[j] = buffer[j];
  76308. tempVertexData.positions[j + 1] = buffer[j + 1];
  76309. tempVertexData.positions[j + 2] = buffer[j + 2];
  76310. }
  76311. }
  76312. else {
  76313. tempVertexData.positions = new Float32Array(buffer.length);
  76314. tempVertexData.positions.set(buffer);
  76315. }
  76316. verticesCounts.push(tempVertexData.positions.length);
  76317. }
  76318. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  76319. var channel = Number(semantic.split("_")[1]);
  76320. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  76321. var uvs = new Float32Array(buffer.length);
  76322. uvs.set(buffer);
  76323. normalizeUVs(uvs);
  76324. tempVertexData.set(uvs, uvKind);
  76325. }
  76326. else if (semantic === "JOINT") {
  76327. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  76328. tempVertexData.matricesIndices.set(buffer);
  76329. }
  76330. else if (semantic === "WEIGHT") {
  76331. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  76332. tempVertexData.matricesWeights.set(buffer);
  76333. }
  76334. else if (semantic === "COLOR") {
  76335. tempVertexData.colors = new Float32Array(buffer.length);
  76336. tempVertexData.colors.set(buffer);
  76337. }
  76338. }
  76339. // Indices
  76340. accessor = gltfRuntime.accessors[primitive.indices];
  76341. if (accessor) {
  76342. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76343. tempVertexData.indices = new Int32Array(buffer.length);
  76344. tempVertexData.indices.set(buffer);
  76345. indexCounts.push(tempVertexData.indices.length);
  76346. }
  76347. else {
  76348. // Set indices on the fly
  76349. var indices = [];
  76350. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  76351. indices.push(j);
  76352. }
  76353. tempVertexData.indices = new Int32Array(indices);
  76354. indexCounts.push(tempVertexData.indices.length);
  76355. }
  76356. vertexData.merge(tempVertexData);
  76357. // Sub material
  76358. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  76359. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  76360. // Update vertices start and index start
  76361. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  76362. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  76363. }
  76364. }
  76365. // Apply geometry
  76366. geometry.setAllVerticesData(vertexData, false);
  76367. newMesh.computeWorldMatrix(true);
  76368. // Apply submeshes
  76369. newMesh.subMeshes = [];
  76370. var index = 0;
  76371. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76372. var meshID = meshes[meshIndex];
  76373. var mesh = gltfRuntime.meshes[meshID];
  76374. if (!mesh) {
  76375. continue;
  76376. }
  76377. for (var i = 0; i < mesh.primitives.length; i++) {
  76378. if (mesh.primitives[i].mode !== 4) {
  76379. //continue;
  76380. }
  76381. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  76382. index++;
  76383. }
  76384. }
  76385. // Finish
  76386. return newMesh;
  76387. };
  76388. /**
  76389. * Configure node transformation from position, rotation and scaling
  76390. */
  76391. var configureNode = function (newNode, position, rotation, scaling) {
  76392. if (newNode.position) {
  76393. newNode.position = position;
  76394. }
  76395. if (newNode.rotationQuaternion || newNode.rotation) {
  76396. newNode.rotationQuaternion = rotation;
  76397. }
  76398. if (newNode.scaling) {
  76399. newNode.scaling = scaling;
  76400. }
  76401. };
  76402. /**
  76403. * Configures node from transformation matrix
  76404. */
  76405. var configureNodeFromMatrix = function (newNode, node, parent) {
  76406. if (node.matrix) {
  76407. var position = new BABYLON.Vector3(0, 0, 0);
  76408. var rotation = new BABYLON.Quaternion();
  76409. var scaling = new BABYLON.Vector3(0, 0, 0);
  76410. var mat = BABYLON.Matrix.FromArray(node.matrix);
  76411. mat.decompose(scaling, rotation, position);
  76412. configureNode(newNode, position, rotation, scaling);
  76413. }
  76414. else if (node.translation && node.rotation && node.scale) {
  76415. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  76416. }
  76417. newNode.computeWorldMatrix(true);
  76418. };
  76419. /**
  76420. * Imports a node
  76421. */
  76422. var importNode = function (gltfRuntime, node, id, parent) {
  76423. var lastNode = null;
  76424. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  76425. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  76426. return null;
  76427. }
  76428. }
  76429. // Meshes
  76430. if (node.skin) {
  76431. if (node.meshes) {
  76432. var skin = gltfRuntime.skins[node.skin];
  76433. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  76434. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  76435. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  76436. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  76437. if (!skin.babylonSkeleton) {
  76438. skin.babylonSkeleton = newMesh.skeleton;
  76439. }
  76440. }
  76441. lastNode = newMesh;
  76442. }
  76443. }
  76444. else if (node.meshes) {
  76445. /**
  76446. * Improve meshes property
  76447. */
  76448. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  76449. lastNode = newMesh;
  76450. }
  76451. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  76452. var light = gltfRuntime.lights[node.light];
  76453. if (light) {
  76454. if (light.type === "ambient") {
  76455. var ambienLight = light[light.type];
  76456. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76457. hemiLight.name = node.name || "";
  76458. if (ambienLight.color) {
  76459. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  76460. }
  76461. lastNode = hemiLight;
  76462. }
  76463. else if (light.type === "directional") {
  76464. var directionalLight = light[light.type];
  76465. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76466. dirLight.name = node.name || "";
  76467. if (directionalLight.color) {
  76468. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  76469. }
  76470. lastNode = dirLight;
  76471. }
  76472. else if (light.type === "point") {
  76473. var pointLight = light[light.type];
  76474. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76475. ptLight.name = node.name || "";
  76476. if (pointLight.color) {
  76477. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  76478. }
  76479. lastNode = ptLight;
  76480. }
  76481. else if (light.type === "spot") {
  76482. var spotLight = light[light.type];
  76483. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  76484. spLight.name = node.name || "";
  76485. if (spotLight.color) {
  76486. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  76487. }
  76488. if (spotLight.fallOfAngle) {
  76489. spLight.angle = spotLight.fallOfAngle;
  76490. }
  76491. if (spotLight.fallOffExponent) {
  76492. spLight.exponent = spotLight.fallOffExponent;
  76493. }
  76494. lastNode = spLight;
  76495. }
  76496. }
  76497. }
  76498. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  76499. var camera = gltfRuntime.cameras[node.camera];
  76500. if (camera) {
  76501. if (camera.type === "orthographic") {
  76502. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76503. orthoCamera.name = node.name || "";
  76504. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  76505. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  76506. lastNode = orthoCamera;
  76507. }
  76508. else if (camera.type === "perspective") {
  76509. var perspectiveCamera = camera[camera.type];
  76510. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76511. persCamera.name = node.name || "";
  76512. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  76513. if (!perspectiveCamera.aspectRatio) {
  76514. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  76515. }
  76516. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  76517. persCamera.maxZ = perspectiveCamera.zfar;
  76518. persCamera.minZ = perspectiveCamera.znear;
  76519. }
  76520. lastNode = persCamera;
  76521. }
  76522. }
  76523. }
  76524. // Empty node
  76525. if (!node.jointName) {
  76526. if (node.babylonNode) {
  76527. return node.babylonNode;
  76528. }
  76529. else if (lastNode === null) {
  76530. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  76531. node.babylonNode = dummy;
  76532. lastNode = dummy;
  76533. }
  76534. }
  76535. if (lastNode !== null) {
  76536. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  76537. configureNodeFromMatrix(lastNode, node, parent);
  76538. }
  76539. else {
  76540. var translation = node.translation || [0, 0, 0];
  76541. var rotation = node.rotation || [0, 0, 0, 1];
  76542. var scale = node.scale || [1, 1, 1];
  76543. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  76544. }
  76545. lastNode.updateCache(true);
  76546. node.babylonNode = lastNode;
  76547. }
  76548. return lastNode;
  76549. };
  76550. /**
  76551. * Traverses nodes and creates them
  76552. */
  76553. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  76554. if (meshIncluded === void 0) { meshIncluded = false; }
  76555. var node = gltfRuntime.nodes[id];
  76556. var newNode = null;
  76557. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  76558. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  76559. meshIncluded = true;
  76560. }
  76561. else {
  76562. meshIncluded = false;
  76563. }
  76564. }
  76565. else {
  76566. meshIncluded = true;
  76567. }
  76568. if (!node.jointName && meshIncluded) {
  76569. newNode = importNode(gltfRuntime, node, id, parent);
  76570. if (newNode !== null) {
  76571. newNode.id = id;
  76572. newNode.parent = parent;
  76573. }
  76574. }
  76575. if (node.children) {
  76576. for (var i = 0; i < node.children.length; i++) {
  76577. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  76578. }
  76579. }
  76580. };
  76581. /**
  76582. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  76583. */
  76584. var postLoad = function (gltfRuntime) {
  76585. // Nodes
  76586. var currentScene = gltfRuntime.currentScene;
  76587. if (currentScene) {
  76588. for (var i = 0; i < currentScene.nodes.length; i++) {
  76589. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  76590. }
  76591. }
  76592. else {
  76593. for (var thing in gltfRuntime.scenes) {
  76594. currentScene = gltfRuntime.scenes[thing];
  76595. for (var i = 0; i < currentScene.nodes.length; i++) {
  76596. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  76597. }
  76598. }
  76599. }
  76600. // Set animations
  76601. loadAnimations(gltfRuntime);
  76602. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  76603. var skeleton = gltfRuntime.scene.skeletons[i];
  76604. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  76605. }
  76606. };
  76607. /**
  76608. * onBind shaderrs callback to set uniforms and matrices
  76609. */
  76610. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  76611. var materialValues = material.values || technique.parameters;
  76612. for (var unif in unTreatedUniforms) {
  76613. var uniform = unTreatedUniforms[unif];
  76614. var type = uniform.type;
  76615. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  76616. if (uniform.semantic && !uniform.source && !uniform.node) {
  76617. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  76618. }
  76619. else if (uniform.semantic && (uniform.source || uniform.node)) {
  76620. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  76621. if (source === null) {
  76622. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  76623. }
  76624. if (source === null) {
  76625. continue;
  76626. }
  76627. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  76628. }
  76629. }
  76630. else {
  76631. var value = materialValues[technique.uniforms[unif]];
  76632. if (!value) {
  76633. continue;
  76634. }
  76635. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  76636. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  76637. if (texture === null || texture === undefined) {
  76638. continue;
  76639. }
  76640. shaderMaterial.getEffect().setTexture(unif, texture);
  76641. }
  76642. else {
  76643. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  76644. }
  76645. }
  76646. }
  76647. onSuccess(shaderMaterial);
  76648. };
  76649. /**
  76650. * Prepare uniforms to send the only one time
  76651. * Loads the appropriate textures
  76652. */
  76653. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  76654. var materialValues = material.values || technique.parameters;
  76655. var techniqueUniforms = technique.uniforms;
  76656. /**
  76657. * Prepare values here (not matrices)
  76658. */
  76659. for (var unif in unTreatedUniforms) {
  76660. var uniform = unTreatedUniforms[unif];
  76661. var type = uniform.type;
  76662. var value = materialValues[techniqueUniforms[unif]];
  76663. if (value === undefined) {
  76664. // In case the value is the same for all materials
  76665. value = uniform.value;
  76666. }
  76667. if (!value) {
  76668. continue;
  76669. }
  76670. var onLoadTexture = function (uniformName) {
  76671. return function (texture) {
  76672. if (uniform.value && uniformName) {
  76673. // Static uniform
  76674. shaderMaterial.setTexture(uniformName, texture);
  76675. delete unTreatedUniforms[uniformName];
  76676. }
  76677. };
  76678. };
  76679. // Texture (sampler2D)
  76680. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  76681. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  76682. }
  76683. else {
  76684. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  76685. // Static uniform
  76686. delete unTreatedUniforms[unif];
  76687. }
  76688. }
  76689. }
  76690. };
  76691. /**
  76692. * Shader compilation failed
  76693. */
  76694. var onShaderCompileError = function (program, shaderMaterial, onError) {
  76695. return function (effect, error) {
  76696. shaderMaterial.dispose(true);
  76697. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  76698. };
  76699. };
  76700. /**
  76701. * Shader compilation success
  76702. */
  76703. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  76704. return function (_) {
  76705. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  76706. shaderMaterial.onBind = function (mesh) {
  76707. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  76708. };
  76709. };
  76710. };
  76711. /**
  76712. * Returns the appropriate uniform if already handled by babylon
  76713. */
  76714. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  76715. for (var unif in technique.uniforms) {
  76716. var uniform = technique.uniforms[unif];
  76717. var uniformParameter = technique.parameters[uniform];
  76718. if (tokenizer.currentIdentifier === unif) {
  76719. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  76720. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  76721. if (transformIndex !== -1) {
  76722. delete unTreatedUniforms[unif];
  76723. return babylonTransforms[transformIndex];
  76724. }
  76725. }
  76726. }
  76727. }
  76728. return tokenizer.currentIdentifier;
  76729. };
  76730. /**
  76731. * All shaders loaded. Create materials one by one
  76732. */
  76733. var importMaterials = function (gltfRuntime) {
  76734. // Create materials
  76735. for (var mat in gltfRuntime.materials) {
  76736. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  76737. }
  76738. };
  76739. /**
  76740. * Implementation of the base glTF spec
  76741. */
  76742. var GLTFLoaderBase = /** @class */ (function () {
  76743. function GLTFLoaderBase() {
  76744. }
  76745. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  76746. var gltfRuntime = {
  76747. extensions: {},
  76748. accessors: {},
  76749. buffers: {},
  76750. bufferViews: {},
  76751. meshes: {},
  76752. lights: {},
  76753. cameras: {},
  76754. nodes: {},
  76755. images: {},
  76756. textures: {},
  76757. shaders: {},
  76758. programs: {},
  76759. samplers: {},
  76760. techniques: {},
  76761. materials: {},
  76762. animations: {},
  76763. skins: {},
  76764. extensionsUsed: [],
  76765. scenes: {},
  76766. buffersCount: 0,
  76767. shaderscount: 0,
  76768. scene: scene,
  76769. rootUrl: rootUrl,
  76770. loadedBufferCount: 0,
  76771. loadedBufferViews: {},
  76772. loadedShaderCount: 0,
  76773. importOnlyMeshes: false,
  76774. dummyNodes: []
  76775. };
  76776. // Parse
  76777. if (parsedData.extensions) {
  76778. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  76779. }
  76780. if (parsedData.extensionsUsed) {
  76781. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  76782. }
  76783. if (parsedData.buffers) {
  76784. parseBuffers(parsedData.buffers, gltfRuntime);
  76785. }
  76786. if (parsedData.bufferViews) {
  76787. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  76788. }
  76789. if (parsedData.accessors) {
  76790. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  76791. }
  76792. if (parsedData.meshes) {
  76793. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  76794. }
  76795. if (parsedData.lights) {
  76796. parseObject(parsedData.lights, "lights", gltfRuntime);
  76797. }
  76798. if (parsedData.cameras) {
  76799. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  76800. }
  76801. if (parsedData.nodes) {
  76802. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  76803. }
  76804. if (parsedData.images) {
  76805. parseObject(parsedData.images, "images", gltfRuntime);
  76806. }
  76807. if (parsedData.textures) {
  76808. parseObject(parsedData.textures, "textures", gltfRuntime);
  76809. }
  76810. if (parsedData.shaders) {
  76811. parseShaders(parsedData.shaders, gltfRuntime);
  76812. }
  76813. if (parsedData.programs) {
  76814. parseObject(parsedData.programs, "programs", gltfRuntime);
  76815. }
  76816. if (parsedData.samplers) {
  76817. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  76818. }
  76819. if (parsedData.techniques) {
  76820. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  76821. }
  76822. if (parsedData.materials) {
  76823. parseObject(parsedData.materials, "materials", gltfRuntime);
  76824. }
  76825. if (parsedData.animations) {
  76826. parseObject(parsedData.animations, "animations", gltfRuntime);
  76827. }
  76828. if (parsedData.skins) {
  76829. parseObject(parsedData.skins, "skins", gltfRuntime);
  76830. }
  76831. if (parsedData.scenes) {
  76832. gltfRuntime.scenes = parsedData.scenes;
  76833. }
  76834. if (parsedData.scene && parsedData.scenes) {
  76835. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  76836. }
  76837. return gltfRuntime;
  76838. };
  76839. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  76840. var buffer = gltfRuntime.buffers[id];
  76841. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  76842. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  76843. }
  76844. else {
  76845. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  76846. if (request) {
  76847. onError(request.status + " " + request.statusText);
  76848. }
  76849. });
  76850. }
  76851. };
  76852. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  76853. var texture = gltfRuntime.textures[id];
  76854. if (!texture || !texture.source) {
  76855. onError("");
  76856. return;
  76857. }
  76858. if (texture.babylonTexture) {
  76859. onSuccess(null);
  76860. return;
  76861. }
  76862. var source = gltfRuntime.images[texture.source];
  76863. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  76864. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  76865. }
  76866. else {
  76867. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  76868. if (request) {
  76869. onError(request.status + " " + request.statusText);
  76870. }
  76871. });
  76872. }
  76873. };
  76874. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  76875. var texture = gltfRuntime.textures[id];
  76876. if (texture.babylonTexture) {
  76877. onSuccess(texture.babylonTexture);
  76878. return;
  76879. }
  76880. var sampler = gltfRuntime.samplers[texture.sampler];
  76881. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  76882. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  76883. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  76884. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  76885. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  76886. var blob = new Blob([buffer]);
  76887. var blobURL = URL.createObjectURL(blob);
  76888. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  76889. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  76890. if (sampler.wrapS !== undefined) {
  76891. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  76892. }
  76893. if (sampler.wrapT !== undefined) {
  76894. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  76895. }
  76896. newTexture.name = id;
  76897. texture.babylonTexture = newTexture;
  76898. onSuccess(newTexture);
  76899. };
  76900. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  76901. var shader = gltfRuntime.shaders[id];
  76902. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  76903. var shaderString = atob(shader.uri.split(",")[1]);
  76904. onSuccess(shaderString);
  76905. }
  76906. else {
  76907. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  76908. if (request) {
  76909. onError(request.status + " " + request.statusText);
  76910. }
  76911. });
  76912. }
  76913. };
  76914. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  76915. var material = gltfRuntime.materials[id];
  76916. if (!material.technique) {
  76917. if (onError) {
  76918. onError("No technique found.");
  76919. }
  76920. return;
  76921. }
  76922. var technique = gltfRuntime.techniques[material.technique];
  76923. if (!technique) {
  76924. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  76925. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  76926. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  76927. onSuccess(defaultMaterial);
  76928. return;
  76929. }
  76930. var program = gltfRuntime.programs[technique.program];
  76931. var states = technique.states;
  76932. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  76933. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  76934. var newVertexShader = "";
  76935. var newPixelShader = "";
  76936. var vertexTokenizer = new Tokenizer(vertexShader);
  76937. var pixelTokenizer = new Tokenizer(pixelShader);
  76938. var unTreatedUniforms = {};
  76939. var uniforms = [];
  76940. var attributes = [];
  76941. var samplers = [];
  76942. // Fill uniform, sampler2D and attributes
  76943. for (var unif in technique.uniforms) {
  76944. var uniform = technique.uniforms[unif];
  76945. var uniformParameter = technique.parameters[uniform];
  76946. unTreatedUniforms[unif] = uniformParameter;
  76947. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  76948. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  76949. if (transformIndex !== -1) {
  76950. uniforms.push(babylonTransforms[transformIndex]);
  76951. delete unTreatedUniforms[unif];
  76952. }
  76953. else {
  76954. uniforms.push(unif);
  76955. }
  76956. }
  76957. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  76958. samplers.push(unif);
  76959. }
  76960. else {
  76961. uniforms.push(unif);
  76962. }
  76963. }
  76964. for (var attr in technique.attributes) {
  76965. var attribute = technique.attributes[attr];
  76966. var attributeParameter = technique.parameters[attribute];
  76967. if (attributeParameter.semantic) {
  76968. attributes.push(getAttribute(attributeParameter));
  76969. }
  76970. }
  76971. // Configure vertex shader
  76972. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  76973. var tokenType = vertexTokenizer.currentToken;
  76974. if (tokenType !== ETokenType.IDENTIFIER) {
  76975. newVertexShader += vertexTokenizer.currentString;
  76976. continue;
  76977. }
  76978. var foundAttribute = false;
  76979. for (var attr in technique.attributes) {
  76980. var attribute = technique.attributes[attr];
  76981. var attributeParameter = technique.parameters[attribute];
  76982. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  76983. newVertexShader += getAttribute(attributeParameter);
  76984. foundAttribute = true;
  76985. break;
  76986. }
  76987. }
  76988. if (foundAttribute) {
  76989. continue;
  76990. }
  76991. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  76992. }
  76993. // Configure pixel shader
  76994. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  76995. var tokenType = pixelTokenizer.currentToken;
  76996. if (tokenType !== ETokenType.IDENTIFIER) {
  76997. newPixelShader += pixelTokenizer.currentString;
  76998. continue;
  76999. }
  77000. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  77001. }
  77002. // Create shader material
  77003. var shaderPath = {
  77004. vertex: program.vertexShader + id,
  77005. fragment: program.fragmentShader + id
  77006. };
  77007. var options = {
  77008. attributes: attributes,
  77009. uniforms: uniforms,
  77010. samplers: samplers,
  77011. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  77012. };
  77013. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  77014. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  77015. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  77016. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  77017. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  77018. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77019. if (states && states.functions) {
  77020. var functions = states.functions;
  77021. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  77022. shaderMaterial.backFaceCulling = false;
  77023. }
  77024. var blendFunc = functions.blendFuncSeparate;
  77025. if (blendFunc) {
  77026. 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) {
  77027. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  77028. }
  77029. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77030. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  77031. }
  77032. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77033. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  77034. }
  77035. 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) {
  77036. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  77037. }
  77038. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77039. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  77040. }
  77041. 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) {
  77042. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  77043. }
  77044. }
  77045. }
  77046. };
  77047. return GLTFLoaderBase;
  77048. }());
  77049. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  77050. /**
  77051. * glTF V1 Loader
  77052. */
  77053. var GLTFLoader = /** @class */ (function () {
  77054. function GLTFLoader() {
  77055. }
  77056. GLTFLoader.RegisterExtension = function (extension) {
  77057. if (GLTFLoader.Extensions[extension.name]) {
  77058. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  77059. return;
  77060. }
  77061. GLTFLoader.Extensions[extension.name] = extension;
  77062. };
  77063. GLTFLoader.prototype.dispose = function () {
  77064. // do nothing
  77065. };
  77066. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77067. var _this = this;
  77068. scene.useRightHandedSystem = true;
  77069. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77070. gltfRuntime.importOnlyMeshes = true;
  77071. if (meshesNames === "") {
  77072. gltfRuntime.importMeshesNames = [];
  77073. }
  77074. else if (typeof meshesNames === "string") {
  77075. gltfRuntime.importMeshesNames = [meshesNames];
  77076. }
  77077. else if (meshesNames && !(meshesNames instanceof Array)) {
  77078. gltfRuntime.importMeshesNames = [meshesNames];
  77079. }
  77080. else {
  77081. gltfRuntime.importMeshesNames = [];
  77082. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  77083. }
  77084. // Create nodes
  77085. _this._createNodes(gltfRuntime);
  77086. var meshes = new Array();
  77087. var skeletons = new Array();
  77088. // Fill arrays of meshes and skeletons
  77089. for (var nde in gltfRuntime.nodes) {
  77090. var node = gltfRuntime.nodes[nde];
  77091. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  77092. meshes.push(node.babylonNode);
  77093. }
  77094. }
  77095. for (var skl in gltfRuntime.skins) {
  77096. var skin = gltfRuntime.skins[skl];
  77097. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  77098. skeletons.push(skin.babylonSkeleton);
  77099. }
  77100. }
  77101. // Load buffers, shaders, materials, etc.
  77102. _this._loadBuffersAsync(gltfRuntime, function () {
  77103. _this._loadShadersAsync(gltfRuntime, function () {
  77104. importMaterials(gltfRuntime);
  77105. postLoad(gltfRuntime);
  77106. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77107. onSuccess(meshes, null, skeletons);
  77108. }
  77109. });
  77110. }, onProgress);
  77111. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77112. onSuccess(meshes, null, skeletons);
  77113. }
  77114. }, onError);
  77115. return true;
  77116. };
  77117. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77118. var _this = this;
  77119. scene.useRightHandedSystem = true;
  77120. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77121. // Load runtime extensios
  77122. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  77123. // Create nodes
  77124. _this._createNodes(gltfRuntime);
  77125. // Load buffers, shaders, materials, etc.
  77126. _this._loadBuffersAsync(gltfRuntime, function () {
  77127. _this._loadShadersAsync(gltfRuntime, function () {
  77128. importMaterials(gltfRuntime);
  77129. postLoad(gltfRuntime);
  77130. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  77131. onSuccess();
  77132. }
  77133. });
  77134. });
  77135. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  77136. onSuccess();
  77137. }
  77138. }, onError);
  77139. }, onError);
  77140. };
  77141. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  77142. var hasShaders = false;
  77143. var processShader = function (sha, shader) {
  77144. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  77145. gltfRuntime.loadedShaderCount++;
  77146. if (shaderString) {
  77147. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  77148. }
  77149. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  77150. onload();
  77151. }
  77152. }, function () {
  77153. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  77154. });
  77155. };
  77156. for (var sha in gltfRuntime.shaders) {
  77157. hasShaders = true;
  77158. var shader = gltfRuntime.shaders[sha];
  77159. if (shader) {
  77160. processShader.bind(this, sha, shader)();
  77161. }
  77162. else {
  77163. BABYLON.Tools.Error("No shader named: " + sha);
  77164. }
  77165. }
  77166. if (!hasShaders) {
  77167. onload();
  77168. }
  77169. };
  77170. ;
  77171. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  77172. var hasBuffers = false;
  77173. var processBuffer = function (buf, buffer) {
  77174. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  77175. gltfRuntime.loadedBufferCount++;
  77176. if (bufferView) {
  77177. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  77178. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  77179. }
  77180. gltfRuntime.loadedBufferViews[buf] = bufferView;
  77181. }
  77182. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  77183. onLoad();
  77184. }
  77185. }, function () {
  77186. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  77187. });
  77188. };
  77189. for (var buf in gltfRuntime.buffers) {
  77190. hasBuffers = true;
  77191. var buffer = gltfRuntime.buffers[buf];
  77192. if (buffer) {
  77193. processBuffer.bind(this, buf, buffer)();
  77194. }
  77195. else {
  77196. BABYLON.Tools.Error("No buffer named: " + buf);
  77197. }
  77198. }
  77199. if (!hasBuffers) {
  77200. onLoad();
  77201. }
  77202. };
  77203. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  77204. var currentScene = gltfRuntime.currentScene;
  77205. if (currentScene) {
  77206. // Only one scene even if multiple scenes are defined
  77207. for (var i = 0; i < currentScene.nodes.length; i++) {
  77208. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77209. }
  77210. }
  77211. else {
  77212. // Load all scenes
  77213. for (var thing in gltfRuntime.scenes) {
  77214. currentScene = gltfRuntime.scenes[thing];
  77215. for (var i = 0; i < currentScene.nodes.length; i++) {
  77216. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77217. }
  77218. }
  77219. }
  77220. };
  77221. GLTFLoader.Extensions = {};
  77222. return GLTFLoader;
  77223. }());
  77224. GLTF1.GLTFLoader = GLTFLoader;
  77225. ;
  77226. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  77227. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77228. })(BABYLON || (BABYLON = {}));
  77229. //# sourceMappingURL=babylon.glTFLoader.js.map
  77230. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77231. var BABYLON;
  77232. (function (BABYLON) {
  77233. var GLTF1;
  77234. (function (GLTF1) {
  77235. /**
  77236. * Utils functions for GLTF
  77237. */
  77238. var GLTFUtils = /** @class */ (function () {
  77239. function GLTFUtils() {
  77240. }
  77241. /**
  77242. * Sets the given "parameter" matrix
  77243. * @param scene: the {BABYLON.Scene} object
  77244. * @param source: the source node where to pick the matrix
  77245. * @param parameter: the GLTF technique parameter
  77246. * @param uniformName: the name of the shader's uniform
  77247. * @param shaderMaterial: the shader material
  77248. */
  77249. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  77250. var mat = null;
  77251. if (parameter.semantic === "MODEL") {
  77252. mat = source.getWorldMatrix();
  77253. }
  77254. else if (parameter.semantic === "PROJECTION") {
  77255. mat = scene.getProjectionMatrix();
  77256. }
  77257. else if (parameter.semantic === "VIEW") {
  77258. mat = scene.getViewMatrix();
  77259. }
  77260. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  77261. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  77262. }
  77263. else if (parameter.semantic === "MODELVIEW") {
  77264. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  77265. }
  77266. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  77267. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  77268. }
  77269. else if (parameter.semantic === "MODELINVERSE") {
  77270. mat = source.getWorldMatrix().invert();
  77271. }
  77272. else if (parameter.semantic === "VIEWINVERSE") {
  77273. mat = scene.getViewMatrix().invert();
  77274. }
  77275. else if (parameter.semantic === "PROJECTIONINVERSE") {
  77276. mat = scene.getProjectionMatrix().invert();
  77277. }
  77278. else if (parameter.semantic === "MODELVIEWINVERSE") {
  77279. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  77280. }
  77281. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  77282. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  77283. }
  77284. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  77285. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  77286. }
  77287. else {
  77288. debugger;
  77289. }
  77290. if (mat) {
  77291. switch (parameter.type) {
  77292. case GLTF1.EParameterType.FLOAT_MAT2:
  77293. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  77294. break;
  77295. case GLTF1.EParameterType.FLOAT_MAT3:
  77296. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  77297. break;
  77298. case GLTF1.EParameterType.FLOAT_MAT4:
  77299. shaderMaterial.setMatrix(uniformName, mat);
  77300. break;
  77301. default: break;
  77302. }
  77303. }
  77304. };
  77305. /**
  77306. * Sets the given "parameter" matrix
  77307. * @param shaderMaterial: the shader material
  77308. * @param uniform: the name of the shader's uniform
  77309. * @param value: the value of the uniform
  77310. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  77311. */
  77312. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  77313. switch (type) {
  77314. case GLTF1.EParameterType.FLOAT:
  77315. shaderMaterial.setFloat(uniform, value);
  77316. return true;
  77317. case GLTF1.EParameterType.FLOAT_VEC2:
  77318. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  77319. return true;
  77320. case GLTF1.EParameterType.FLOAT_VEC3:
  77321. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  77322. return true;
  77323. case GLTF1.EParameterType.FLOAT_VEC4:
  77324. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  77325. return true;
  77326. default: return false;
  77327. }
  77328. };
  77329. /**
  77330. * If the uri is a base64 string
  77331. * @param uri: the uri to test
  77332. */
  77333. GLTFUtils.IsBase64 = function (uri) {
  77334. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  77335. };
  77336. /**
  77337. * Decode the base64 uri
  77338. * @param uri: the uri to decode
  77339. */
  77340. GLTFUtils.DecodeBase64 = function (uri) {
  77341. var decodedString = atob(uri.split(",")[1]);
  77342. var bufferLength = decodedString.length;
  77343. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  77344. for (var i = 0; i < bufferLength; i++) {
  77345. bufferView[i] = decodedString.charCodeAt(i);
  77346. }
  77347. return bufferView.buffer;
  77348. };
  77349. /**
  77350. * Returns the wrap mode of the texture
  77351. * @param mode: the mode value
  77352. */
  77353. GLTFUtils.GetWrapMode = function (mode) {
  77354. switch (mode) {
  77355. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  77356. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  77357. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77358. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77359. }
  77360. };
  77361. /**
  77362. * Returns the byte stride giving an accessor
  77363. * @param accessor: the GLTF accessor objet
  77364. */
  77365. GLTFUtils.GetByteStrideFromType = function (accessor) {
  77366. // Needs this function since "byteStride" isn't requiered in glTF format
  77367. var type = accessor.type;
  77368. switch (type) {
  77369. case "VEC2": return 2;
  77370. case "VEC3": return 3;
  77371. case "VEC4": return 4;
  77372. case "MAT2": return 4;
  77373. case "MAT3": return 9;
  77374. case "MAT4": return 16;
  77375. default: return 1;
  77376. }
  77377. };
  77378. /**
  77379. * Returns the texture filter mode giving a mode value
  77380. * @param mode: the filter mode value
  77381. */
  77382. GLTFUtils.GetTextureFilterMode = function (mode) {
  77383. switch (mode) {
  77384. case GLTF1.ETextureFilterType.LINEAR:
  77385. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  77386. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  77387. case GLTF1.ETextureFilterType.NEAREST:
  77388. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  77389. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  77390. }
  77391. };
  77392. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  77393. var byteOffset = bufferView.byteOffset + byteOffset;
  77394. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  77395. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  77396. throw new Error("Buffer access is out of range");
  77397. }
  77398. var buffer = loadedBufferView.buffer;
  77399. byteOffset += loadedBufferView.byteOffset;
  77400. switch (componentType) {
  77401. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  77402. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  77403. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  77404. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  77405. default: return new Float32Array(buffer, byteOffset, byteLength);
  77406. }
  77407. };
  77408. /**
  77409. * Returns a buffer from its accessor
  77410. * @param gltfRuntime: the GLTF runtime
  77411. * @param accessor: the GLTF accessor
  77412. */
  77413. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  77414. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  77415. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  77416. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  77417. };
  77418. /**
  77419. * Decodes a buffer view into a string
  77420. * @param view: the buffer view
  77421. */
  77422. GLTFUtils.DecodeBufferToText = function (view) {
  77423. var result = "";
  77424. var length = view.byteLength;
  77425. for (var i = 0; i < length; ++i) {
  77426. result += String.fromCharCode(view[i]);
  77427. }
  77428. return result;
  77429. };
  77430. /**
  77431. * Returns the default material of gltf. Related to
  77432. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  77433. * @param scene: the Babylon.js scene
  77434. */
  77435. GLTFUtils.GetDefaultMaterial = function (scene) {
  77436. if (!GLTFUtils._DefaultMaterial) {
  77437. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  77438. "precision highp float;",
  77439. "",
  77440. "uniform mat4 worldView;",
  77441. "uniform mat4 projection;",
  77442. "",
  77443. "attribute vec3 position;",
  77444. "",
  77445. "void main(void)",
  77446. "{",
  77447. " gl_Position = projection * worldView * vec4(position, 1.0);",
  77448. "}"
  77449. ].join("\n");
  77450. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  77451. "precision highp float;",
  77452. "",
  77453. "uniform vec4 u_emission;",
  77454. "",
  77455. "void main(void)",
  77456. "{",
  77457. " gl_FragColor = u_emission;",
  77458. "}"
  77459. ].join("\n");
  77460. var shaderPath = {
  77461. vertex: "GLTFDefaultMaterial",
  77462. fragment: "GLTFDefaultMaterial"
  77463. };
  77464. var options = {
  77465. attributes: ["position"],
  77466. uniforms: ["worldView", "projection", "u_emission"],
  77467. samplers: new Array(),
  77468. needAlphaBlending: false
  77469. };
  77470. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  77471. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  77472. }
  77473. return GLTFUtils._DefaultMaterial;
  77474. };
  77475. // The GLTF default material
  77476. GLTFUtils._DefaultMaterial = null;
  77477. return GLTFUtils;
  77478. }());
  77479. GLTF1.GLTFUtils = GLTFUtils;
  77480. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77481. })(BABYLON || (BABYLON = {}));
  77482. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  77483. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77484. var BABYLON;
  77485. (function (BABYLON) {
  77486. var GLTF1;
  77487. (function (GLTF1) {
  77488. var GLTFLoaderExtension = /** @class */ (function () {
  77489. function GLTFLoaderExtension(name) {
  77490. this._name = name;
  77491. }
  77492. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  77493. get: function () {
  77494. return this._name;
  77495. },
  77496. enumerable: true,
  77497. configurable: true
  77498. });
  77499. /**
  77500. * Defines an override for loading the runtime
  77501. * Return true to stop further extensions from loading the runtime
  77502. */
  77503. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77504. return false;
  77505. };
  77506. /**
  77507. * Defines an onverride for creating gltf runtime
  77508. * Return true to stop further extensions from creating the runtime
  77509. */
  77510. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77511. return false;
  77512. };
  77513. /**
  77514. * Defines an override for loading buffers
  77515. * Return true to stop further extensions from loading this buffer
  77516. */
  77517. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77518. return false;
  77519. };
  77520. /**
  77521. * Defines an override for loading texture buffers
  77522. * Return true to stop further extensions from loading this texture data
  77523. */
  77524. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77525. return false;
  77526. };
  77527. /**
  77528. * Defines an override for creating textures
  77529. * Return true to stop further extensions from loading this texture
  77530. */
  77531. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77532. return false;
  77533. };
  77534. /**
  77535. * Defines an override for loading shader strings
  77536. * Return true to stop further extensions from loading this shader data
  77537. */
  77538. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77539. return false;
  77540. };
  77541. /**
  77542. * Defines an override for loading materials
  77543. * Return true to stop further extensions from loading this material
  77544. */
  77545. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77546. return false;
  77547. };
  77548. // ---------
  77549. // Utilities
  77550. // ---------
  77551. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77552. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77553. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  77554. }, function () {
  77555. setTimeout(function () {
  77556. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  77557. });
  77558. });
  77559. };
  77560. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77561. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77562. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  77563. }, function () {
  77564. setTimeout(function () {
  77565. onSuccess();
  77566. });
  77567. });
  77568. };
  77569. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77570. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77571. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  77572. }, function () {
  77573. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  77574. });
  77575. };
  77576. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  77577. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  77578. };
  77579. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77580. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77581. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  77582. }, function () {
  77583. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  77584. });
  77585. };
  77586. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77587. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77588. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  77589. }, function () {
  77590. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  77591. });
  77592. };
  77593. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77594. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77595. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  77596. }, function () {
  77597. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  77598. });
  77599. };
  77600. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77601. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77602. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  77603. }, function () {
  77604. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  77605. });
  77606. };
  77607. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  77608. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  77609. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  77610. if (func(loaderExtension)) {
  77611. return;
  77612. }
  77613. }
  77614. defaultFunc();
  77615. };
  77616. return GLTFLoaderExtension;
  77617. }());
  77618. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  77619. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77620. })(BABYLON || (BABYLON = {}));
  77621. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  77622. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77623. var BABYLON;
  77624. (function (BABYLON) {
  77625. var GLTF1;
  77626. (function (GLTF1) {
  77627. var BinaryExtensionBufferName = "binary_glTF";
  77628. ;
  77629. ;
  77630. var GLTFBinaryExtension = /** @class */ (function (_super) {
  77631. __extends(GLTFBinaryExtension, _super);
  77632. function GLTFBinaryExtension() {
  77633. return _super.call(this, "KHR_binary_glTF") || this;
  77634. }
  77635. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77636. var extensionsUsed = data.json.extensionsUsed;
  77637. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  77638. return false;
  77639. }
  77640. this._bin = data.bin;
  77641. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  77642. return true;
  77643. };
  77644. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77645. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  77646. return false;
  77647. }
  77648. if (id !== BinaryExtensionBufferName) {
  77649. return false;
  77650. }
  77651. onSuccess(this._bin);
  77652. return true;
  77653. };
  77654. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77655. var texture = gltfRuntime.textures[id];
  77656. var source = gltfRuntime.images[texture.source];
  77657. if (!source.extensions || !(this.name in source.extensions)) {
  77658. return false;
  77659. }
  77660. var sourceExt = source.extensions[this.name];
  77661. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  77662. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  77663. onSuccess(buffer);
  77664. return true;
  77665. };
  77666. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77667. var shader = gltfRuntime.shaders[id];
  77668. if (!shader.extensions || !(this.name in shader.extensions)) {
  77669. return false;
  77670. }
  77671. var binaryExtensionShader = shader.extensions[this.name];
  77672. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  77673. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  77674. setTimeout(function () {
  77675. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  77676. onSuccess(shaderString);
  77677. });
  77678. return true;
  77679. };
  77680. return GLTFBinaryExtension;
  77681. }(GLTF1.GLTFLoaderExtension));
  77682. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  77683. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  77684. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77685. })(BABYLON || (BABYLON = {}));
  77686. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  77687. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77688. var BABYLON;
  77689. (function (BABYLON) {
  77690. var GLTF1;
  77691. (function (GLTF1) {
  77692. ;
  77693. ;
  77694. ;
  77695. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  77696. __extends(GLTFMaterialsCommonExtension, _super);
  77697. function GLTFMaterialsCommonExtension() {
  77698. return _super.call(this, "KHR_materials_common") || this;
  77699. }
  77700. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77701. if (!gltfRuntime.extensions)
  77702. return false;
  77703. var extension = gltfRuntime.extensions[this.name];
  77704. if (!extension)
  77705. return false;
  77706. // Create lights
  77707. var lights = extension.lights;
  77708. if (lights) {
  77709. for (var thing in lights) {
  77710. var light = lights[thing];
  77711. switch (light.type) {
  77712. case "ambient":
  77713. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  77714. var ambient = light.ambient;
  77715. if (ambient) {
  77716. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  77717. }
  77718. break;
  77719. case "point":
  77720. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  77721. var point = light.point;
  77722. if (point) {
  77723. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  77724. }
  77725. break;
  77726. case "directional":
  77727. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  77728. var directional = light.directional;
  77729. if (directional) {
  77730. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  77731. }
  77732. break;
  77733. case "spot":
  77734. var spot = light.spot;
  77735. if (spot) {
  77736. 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);
  77737. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  77738. }
  77739. break;
  77740. default:
  77741. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  77742. break;
  77743. }
  77744. }
  77745. }
  77746. return false;
  77747. };
  77748. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77749. var material = gltfRuntime.materials[id];
  77750. if (!material || !material.extensions)
  77751. return false;
  77752. var extension = material.extensions[this.name];
  77753. if (!extension)
  77754. return false;
  77755. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  77756. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77757. if (extension.technique === "CONSTANT") {
  77758. standardMaterial.disableLighting = true;
  77759. }
  77760. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  77761. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  77762. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  77763. // Ambient
  77764. if (typeof extension.values.ambient === "string") {
  77765. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  77766. }
  77767. else {
  77768. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  77769. }
  77770. // Diffuse
  77771. if (typeof extension.values.diffuse === "string") {
  77772. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  77773. }
  77774. else {
  77775. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  77776. }
  77777. // Emission
  77778. if (typeof extension.values.emission === "string") {
  77779. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  77780. }
  77781. else {
  77782. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  77783. }
  77784. // Specular
  77785. if (typeof extension.values.specular === "string") {
  77786. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  77787. }
  77788. else {
  77789. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  77790. }
  77791. return true;
  77792. };
  77793. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  77794. // Create buffer from texture url
  77795. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  77796. // Create texture from buffer
  77797. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  77798. }, onError);
  77799. };
  77800. return GLTFMaterialsCommonExtension;
  77801. }(GLTF1.GLTFLoaderExtension));
  77802. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  77803. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  77804. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77805. })(BABYLON || (BABYLON = {}));
  77806. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  77807. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77808. var BABYLON;
  77809. (function (BABYLON) {
  77810. var GLTF2;
  77811. (function (GLTF2) {
  77812. /**
  77813. * Enums
  77814. */
  77815. var EComponentType;
  77816. (function (EComponentType) {
  77817. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  77818. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  77819. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  77820. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  77821. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  77822. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  77823. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  77824. var EMeshPrimitiveMode;
  77825. (function (EMeshPrimitiveMode) {
  77826. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  77827. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  77828. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  77829. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  77830. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  77831. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  77832. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  77833. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  77834. var ETextureMagFilter;
  77835. (function (ETextureMagFilter) {
  77836. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  77837. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  77838. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  77839. var ETextureMinFilter;
  77840. (function (ETextureMinFilter) {
  77841. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  77842. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  77843. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  77844. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  77845. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  77846. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  77847. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  77848. var ETextureWrapMode;
  77849. (function (ETextureWrapMode) {
  77850. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  77851. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  77852. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  77853. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  77854. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  77855. })(BABYLON || (BABYLON = {}));
  77856. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  77857. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77858. var BABYLON;
  77859. (function (BABYLON) {
  77860. var GLTF2;
  77861. (function (GLTF2) {
  77862. var GLTFLoaderTracker = /** @class */ (function () {
  77863. function GLTFLoaderTracker(onComplete) {
  77864. this._pendingCount = 0;
  77865. this._callback = onComplete;
  77866. }
  77867. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  77868. this._pendingCount++;
  77869. };
  77870. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  77871. if (--this._pendingCount === 0) {
  77872. this._callback();
  77873. }
  77874. };
  77875. return GLTFLoaderTracker;
  77876. }());
  77877. var GLTFLoader = /** @class */ (function () {
  77878. function GLTFLoader(parent) {
  77879. this._disposed = false;
  77880. this._renderReady = false;
  77881. this._requests = new Array();
  77882. this._renderReadyObservable = new BABYLON.Observable();
  77883. // Count of pending work that needs to complete before the asset is rendered.
  77884. this._renderPendingCount = 0;
  77885. // Count of pending work that needs to complete before the loader is disposed.
  77886. this._loaderPendingCount = 0;
  77887. this._loaderTrackers = new Array();
  77888. this._parent = parent;
  77889. }
  77890. GLTFLoader.RegisterExtension = function (extension) {
  77891. if (GLTFLoader.Extensions[extension.name]) {
  77892. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  77893. return;
  77894. }
  77895. GLTFLoader.Extensions[extension.name] = extension;
  77896. // Keep the order of registration so that extensions registered first are called first.
  77897. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  77898. };
  77899. GLTFLoader.prototype.dispose = function () {
  77900. if (this._disposed) {
  77901. return;
  77902. }
  77903. this._disposed = true;
  77904. // Abort requests that are not complete
  77905. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  77906. var request = _a[_i];
  77907. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  77908. request.abort();
  77909. }
  77910. }
  77911. // Revoke object urls created during load
  77912. if (this._gltf.textures) {
  77913. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  77914. var texture = _c[_b];
  77915. if (texture.url) {
  77916. URL.revokeObjectURL(texture.url);
  77917. }
  77918. }
  77919. }
  77920. this._gltf = undefined;
  77921. this._babylonScene = undefined;
  77922. this._parent = undefined;
  77923. this._rootUrl = undefined;
  77924. this._defaultMaterial = undefined;
  77925. this._rootNode = undefined;
  77926. this._successCallback = undefined;
  77927. this._progressCallback = undefined;
  77928. this._errorCallback = undefined;
  77929. this._renderReady = false;
  77930. this._requests = undefined;
  77931. this._renderReadyObservable = undefined;
  77932. this._renderPendingCount = 0;
  77933. this._loaderPendingCount = 0;
  77934. this._loaderTrackers = undefined;
  77935. };
  77936. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77937. var _this = this;
  77938. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  77939. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  77940. }, onProgress, onError);
  77941. };
  77942. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77943. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  77944. };
  77945. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77946. var _this = this;
  77947. this._tryCatchOnError(function () {
  77948. _this._loadData(data);
  77949. _this._babylonScene = scene;
  77950. _this._rootUrl = rootUrl;
  77951. _this._successCallback = onSuccess;
  77952. _this._progressCallback = onProgress;
  77953. _this._errorCallback = onError;
  77954. GLTF2.GLTFUtils.AssignIndices(_this._gltf.accessors);
  77955. GLTF2.GLTFUtils.AssignIndices(_this._gltf.animations);
  77956. GLTF2.GLTFUtils.AssignIndices(_this._gltf.buffers);
  77957. GLTF2.GLTFUtils.AssignIndices(_this._gltf.bufferViews);
  77958. GLTF2.GLTFUtils.AssignIndices(_this._gltf.images);
  77959. GLTF2.GLTFUtils.AssignIndices(_this._gltf.materials);
  77960. GLTF2.GLTFUtils.AssignIndices(_this._gltf.meshes);
  77961. GLTF2.GLTFUtils.AssignIndices(_this._gltf.nodes);
  77962. GLTF2.GLTFUtils.AssignIndices(_this._gltf.scenes);
  77963. GLTF2.GLTFUtils.AssignIndices(_this._gltf.skins);
  77964. GLTF2.GLTFUtils.AssignIndices(_this._gltf.textures);
  77965. _this._addPendingData(_this);
  77966. _this._loadDefaultScene(nodeNames);
  77967. _this._loadAnimations();
  77968. _this._removePendingData(_this);
  77969. });
  77970. };
  77971. GLTFLoader.prototype._onError = function (message) {
  77972. if (this._disposed) {
  77973. return;
  77974. }
  77975. BABYLON.Tools.Error("glTF Loader: " + message);
  77976. if (this._errorCallback) {
  77977. this._errorCallback(message);
  77978. }
  77979. this.dispose();
  77980. };
  77981. GLTFLoader.prototype._onProgress = function (event) {
  77982. if (this._disposed) {
  77983. return;
  77984. }
  77985. if (this._progressCallback) {
  77986. this._progressCallback(event);
  77987. }
  77988. };
  77989. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  77990. if (this._renderReady) {
  77991. func();
  77992. }
  77993. else {
  77994. this._renderReadyObservable.add(func);
  77995. }
  77996. };
  77997. GLTFLoader.prototype._onRenderReady = function () {
  77998. if (this._rootNode.babylonMesh) {
  77999. this._rootNode.babylonMesh.setEnabled(true);
  78000. }
  78001. this._startAnimations();
  78002. this._successCallback();
  78003. this._renderReadyObservable.notifyObservers(this);
  78004. };
  78005. GLTFLoader.prototype._onComplete = function () {
  78006. if (this._parent.onComplete) {
  78007. this._parent.onComplete();
  78008. }
  78009. this.dispose();
  78010. };
  78011. GLTFLoader.prototype._loadData = function (data) {
  78012. this._gltf = data.json;
  78013. if (data.bin) {
  78014. var buffers = this._gltf.buffers;
  78015. if (buffers && buffers[0] && !buffers[0].uri) {
  78016. var binaryBuffer = buffers[0];
  78017. if (binaryBuffer.byteLength != data.bin.byteLength) {
  78018. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  78019. }
  78020. binaryBuffer.loadedData = data.bin;
  78021. }
  78022. else {
  78023. BABYLON.Tools.Warn("Unexpected BIN chunk");
  78024. }
  78025. }
  78026. };
  78027. GLTFLoader.prototype._getMeshes = function () {
  78028. var meshes = [this._rootNode.babylonMesh];
  78029. var nodes = this._gltf.nodes;
  78030. if (nodes) {
  78031. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  78032. var node = nodes_1[_i];
  78033. if (node.babylonMesh) {
  78034. meshes.push(node.babylonMesh);
  78035. }
  78036. }
  78037. }
  78038. return meshes;
  78039. };
  78040. GLTFLoader.prototype._getSkeletons = function () {
  78041. var skeletons = new Array();
  78042. var skins = this._gltf.skins;
  78043. if (skins) {
  78044. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  78045. var skin = skins_1[_i];
  78046. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  78047. skeletons.push(skin.babylonSkeleton);
  78048. }
  78049. }
  78050. }
  78051. return skeletons;
  78052. };
  78053. GLTFLoader.prototype._getAnimationTargets = function () {
  78054. var targets = new Array();
  78055. var animations = this._gltf.animations;
  78056. if (animations) {
  78057. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  78058. var animation = animations_1[_i];
  78059. targets.push.apply(targets, animation.targets);
  78060. }
  78061. }
  78062. return targets;
  78063. };
  78064. GLTFLoader.prototype._startAnimations = function () {
  78065. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  78066. var target = _a[_i];
  78067. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  78068. }
  78069. };
  78070. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  78071. var scene = GLTF2.GLTFUtils.GetArrayItem(this._gltf.scenes, this._gltf.scene || 0);
  78072. if (!scene) {
  78073. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  78074. }
  78075. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  78076. };
  78077. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  78078. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  78079. switch (this._parent.coordinateSystemMode) {
  78080. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  78081. if (!this._babylonScene.useRightHandedSystem && this._rootNode.babylonMesh) {
  78082. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  78083. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  78084. }
  78085. break;
  78086. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  78087. // do nothing
  78088. break;
  78089. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  78090. this._babylonScene.useRightHandedSystem = true;
  78091. break;
  78092. default:
  78093. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  78094. return;
  78095. }
  78096. var nodeIndices = scene.nodes;
  78097. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  78098. node.parent = parentNode;
  78099. return true;
  78100. }, this._rootNode);
  78101. if (nodeNames) {
  78102. if (!(nodeNames instanceof Array)) {
  78103. nodeNames = [nodeNames];
  78104. }
  78105. var filteredNodeIndices_1 = new Array();
  78106. this._traverseNodes(context, nodeIndices, function (node) {
  78107. if (nodeNames.indexOf(node.name) !== -1) {
  78108. filteredNodeIndices_1.push(node.index);
  78109. return false;
  78110. }
  78111. return true;
  78112. }, this._rootNode);
  78113. nodeIndices = filteredNodeIndices_1;
  78114. }
  78115. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  78116. var index = nodeIndices_1[_i];
  78117. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  78118. if (!node) {
  78119. throw new Error(context + ": Failed to find node " + index);
  78120. }
  78121. this._loadNode("#/nodes/" + index, node);
  78122. }
  78123. // Disable the root mesh until the asset is ready to render.
  78124. if (this._rootNode.babylonMesh) {
  78125. this._rootNode.babylonMesh.setEnabled(false);
  78126. }
  78127. };
  78128. GLTFLoader.prototype._loadNode = function (context, node) {
  78129. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  78130. return;
  78131. }
  78132. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  78133. this._loadTransform(node);
  78134. if (node.mesh != null) {
  78135. var mesh = GLTF2.GLTFUtils.GetArrayItem(this._gltf.meshes, node.mesh);
  78136. if (!mesh) {
  78137. throw new Error(context + ": Failed to find mesh " + node.mesh);
  78138. }
  78139. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  78140. }
  78141. node.babylonMesh.parent = (node.parent ? node.parent.babylonMesh : null);
  78142. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  78143. node.babylonAnimationTargets.push(node.babylonMesh);
  78144. if (node.skin != null) {
  78145. var skin = GLTF2.GLTFUtils.GetArrayItem(this._gltf.skins, node.skin);
  78146. if (!skin) {
  78147. throw new Error(context + ": Failed to find skin " + node.skin);
  78148. }
  78149. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  78150. }
  78151. if (node.camera != null) {
  78152. // TODO: handle cameras
  78153. }
  78154. if (node.children) {
  78155. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  78156. var index = _a[_i];
  78157. var childNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  78158. if (!childNode) {
  78159. throw new Error(context + ": Failed to find child node " + index);
  78160. }
  78161. this._loadNode("#/nodes/" + index, childNode);
  78162. }
  78163. }
  78164. };
  78165. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  78166. var _this = this;
  78167. if (!node.babylonMesh) {
  78168. return;
  78169. }
  78170. node.babylonMesh.name = node.babylonMesh.name || mesh.name || "";
  78171. var primitives = mesh.primitives;
  78172. if (!primitives || primitives.length === 0) {
  78173. throw new Error(context + ": Primitives are missing");
  78174. }
  78175. this._createMorphTargets(context, node, mesh);
  78176. this._loadAllVertexDataAsync(context, mesh, function () {
  78177. if (!node.babylonMesh) {
  78178. return;
  78179. }
  78180. _this._loadMorphTargets(context, node, mesh);
  78181. var vertexData = new BABYLON.VertexData();
  78182. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  78183. var primitive = primitives_1[_i];
  78184. vertexData.merge(primitive.vertexData);
  78185. }
  78186. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  78187. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  78188. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  78189. node.babylonMesh.subMeshes = [];
  78190. var verticesStart = 0;
  78191. var indicesStart = 0;
  78192. for (var index = 0; index < primitives.length; index++) {
  78193. var vertexData_1 = primitives[index].vertexData;
  78194. var verticesCount = vertexData_1.positions.length;
  78195. var indicesCount = vertexData_1.indices.length;
  78196. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  78197. verticesStart += verticesCount;
  78198. indicesStart += indicesCount;
  78199. }
  78200. ;
  78201. });
  78202. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  78203. node.babylonMesh.material = multiMaterial;
  78204. var subMaterials = multiMaterial.subMaterials;
  78205. var _loop_1 = function (index) {
  78206. var primitive = primitives[index];
  78207. if (primitive.material == null) {
  78208. subMaterials[index] = this_1._getDefaultMaterial();
  78209. }
  78210. else {
  78211. var material_1 = GLTF2.GLTFUtils.GetArrayItem(this_1._gltf.materials, primitive.material);
  78212. if (!material_1) {
  78213. throw new Error(context + ": Failed to find material " + primitive.material);
  78214. }
  78215. this_1._loadMaterial("#/materials/" + material_1.index, material_1, function (babylonMaterial, isNew) {
  78216. if (isNew && _this._parent.onMaterialLoaded) {
  78217. _this._parent.onMaterialLoaded(babylonMaterial);
  78218. }
  78219. if (_this._parent.onBeforeMaterialReadyAsync) {
  78220. _this._addLoaderPendingData(material_1);
  78221. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  78222. _this._tryCatchOnError(function () {
  78223. subMaterials[index] = babylonMaterial;
  78224. _this._removeLoaderPendingData(material_1);
  78225. });
  78226. });
  78227. }
  78228. else {
  78229. subMaterials[index] = babylonMaterial;
  78230. }
  78231. });
  78232. }
  78233. };
  78234. var this_1 = this;
  78235. for (var index = 0; index < primitives.length; index++) {
  78236. _loop_1(index);
  78237. }
  78238. ;
  78239. };
  78240. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  78241. var primitives = mesh.primitives;
  78242. var numRemainingPrimitives = primitives.length;
  78243. var _loop_2 = function (index) {
  78244. var primitive = primitives[index];
  78245. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  78246. primitive.vertexData = vertexData;
  78247. if (--numRemainingPrimitives === 0) {
  78248. onSuccess();
  78249. }
  78250. });
  78251. };
  78252. var this_2 = this;
  78253. for (var index = 0; index < primitives.length; index++) {
  78254. _loop_2(index);
  78255. }
  78256. };
  78257. /**
  78258. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  78259. * @param {ArrayBufferView} data
  78260. * @param {IGLTFAccessor} accessor
  78261. */
  78262. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  78263. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  78264. return data;
  78265. }
  78266. var buffer = data;
  78267. var factor = 1;
  78268. switch (accessor.componentType) {
  78269. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78270. factor = 1 / 255;
  78271. break;
  78272. }
  78273. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78274. factor = 1 / 65535;
  78275. break;
  78276. }
  78277. default: {
  78278. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78279. }
  78280. }
  78281. var result = new Float32Array(accessor.count * 2);
  78282. for (var i = 0; i < result.length; ++i) {
  78283. result[i] = buffer[i] * factor;
  78284. }
  78285. return result;
  78286. };
  78287. /**
  78288. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  78289. * @param {ArrayBufferView} data
  78290. * @param {IGLTFAccessor} accessor
  78291. */
  78292. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  78293. var colorComponentCount = this._getNumComponentsOfType(accessor.type);
  78294. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  78295. return data;
  78296. }
  78297. var buffer = data;
  78298. var factor = 1;
  78299. switch (accessor.componentType) {
  78300. case GLTF2.EComponentType.FLOAT: {
  78301. factor = 1;
  78302. break;
  78303. }
  78304. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78305. factor = 1 / 255;
  78306. break;
  78307. }
  78308. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78309. factor = 1 / 65535;
  78310. break;
  78311. }
  78312. default: {
  78313. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78314. }
  78315. }
  78316. var result = new Float32Array(accessor.count * 4);
  78317. if (colorComponentCount === 4) {
  78318. for (var i = 0; i < result.length; ++i) {
  78319. result[i] = buffer[i] * factor;
  78320. }
  78321. }
  78322. else {
  78323. var offset = 0;
  78324. for (var i = 0; i < result.length; ++i) {
  78325. if ((i + 1) % 4 === 0) {
  78326. result[i] = 1;
  78327. }
  78328. else {
  78329. result[i] = buffer[offset++] * factor;
  78330. }
  78331. }
  78332. }
  78333. return result;
  78334. };
  78335. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  78336. var _this = this;
  78337. var attributes = primitive.attributes;
  78338. if (!attributes) {
  78339. throw new Error(context + ": Attributes are missing");
  78340. }
  78341. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  78342. // TODO: handle other primitive modes
  78343. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  78344. }
  78345. var vertexData = new BABYLON.VertexData();
  78346. var numRemainingAttributes = Object.keys(attributes).length;
  78347. var _loop_3 = function (attribute) {
  78348. var accessor = GLTF2.GLTFUtils.GetArrayItem(this_3._gltf.accessors, attributes[attribute]);
  78349. if (!accessor) {
  78350. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78351. }
  78352. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78353. switch (attribute) {
  78354. case "NORMAL":
  78355. vertexData.normals = data;
  78356. break;
  78357. case "POSITION":
  78358. vertexData.positions = data;
  78359. break;
  78360. case "TANGENT":
  78361. vertexData.tangents = data;
  78362. break;
  78363. case "TEXCOORD_0":
  78364. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  78365. break;
  78366. case "TEXCOORD_1":
  78367. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  78368. break;
  78369. case "JOINTS_0":
  78370. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  78371. break;
  78372. case "WEIGHTS_0":
  78373. //TODO: need to add support for normalized weights.
  78374. vertexData.matricesWeights = data;
  78375. break;
  78376. case "COLOR_0":
  78377. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  78378. break;
  78379. default:
  78380. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78381. break;
  78382. }
  78383. if (--numRemainingAttributes === 0) {
  78384. if (primitive.indices == null) {
  78385. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  78386. for (var i = 0; i < vertexData.indices.length; i++) {
  78387. vertexData.indices[i] = i;
  78388. }
  78389. onSuccess(vertexData);
  78390. }
  78391. else {
  78392. var indicesAccessor = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.accessors, primitive.indices);
  78393. if (!indicesAccessor) {
  78394. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  78395. }
  78396. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  78397. vertexData.indices = data;
  78398. onSuccess(vertexData);
  78399. });
  78400. }
  78401. }
  78402. });
  78403. };
  78404. var this_3 = this;
  78405. for (var attribute in attributes) {
  78406. _loop_3(attribute);
  78407. }
  78408. };
  78409. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  78410. var primitives = mesh.primitives;
  78411. var targets = primitives[0].targets;
  78412. if (!targets || !node.babylonMesh) {
  78413. return;
  78414. }
  78415. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  78416. var primitive = primitives_2[_i];
  78417. if (!primitive.targets || primitive.targets.length != targets.length) {
  78418. throw new Error(context + ": All primitives are required to list the same number of targets");
  78419. }
  78420. }
  78421. var morphTargetManager = new BABYLON.MorphTargetManager();
  78422. node.babylonMesh.morphTargetManager = morphTargetManager;
  78423. for (var index = 0; index < targets.length; index++) {
  78424. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  78425. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  78426. }
  78427. };
  78428. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  78429. if (!node.babylonMesh) {
  78430. return;
  78431. }
  78432. var morphTargetManager = node.babylonMesh.morphTargetManager;
  78433. if (!morphTargetManager) {
  78434. return;
  78435. }
  78436. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  78437. var numTargets = morphTargetManager.numTargets;
  78438. for (var index = 0; index < numTargets; index++) {
  78439. var vertexData = new BABYLON.VertexData();
  78440. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78441. var primitive = _a[_i];
  78442. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  78443. }
  78444. var target = morphTargetManager.getTarget(index);
  78445. target.setNormals(vertexData.normals);
  78446. target.setPositions(vertexData.positions);
  78447. target.setTangents(vertexData.tangents);
  78448. }
  78449. });
  78450. };
  78451. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  78452. if (!node.babylonMesh || !node.babylonMesh.morphTargetManager) {
  78453. return;
  78454. }
  78455. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  78456. var _loop_4 = function (primitive) {
  78457. var targets = primitive.targets;
  78458. if (!targets) {
  78459. return "continue";
  78460. }
  78461. primitive.targetsVertexData = new Array(targets.length);
  78462. var _loop_5 = function (index) {
  78463. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  78464. primitive.targetsVertexData[index] = vertexData;
  78465. if (--numRemainingTargets === 0) {
  78466. onSuccess();
  78467. }
  78468. });
  78469. };
  78470. for (var index = 0; index < targets.length; index++) {
  78471. _loop_5(index);
  78472. }
  78473. };
  78474. var this_4 = this;
  78475. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78476. var primitive = _a[_i];
  78477. _loop_4(primitive);
  78478. }
  78479. };
  78480. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  78481. var targetVertexData = new BABYLON.VertexData();
  78482. var numRemainingAttributes = Object.keys(attributes).length;
  78483. var _loop_6 = function (attribute) {
  78484. var accessor = GLTF2.GLTFUtils.GetArrayItem(this_5._gltf.accessors, attributes[attribute]);
  78485. if (!accessor) {
  78486. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78487. }
  78488. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78489. // glTF stores morph target information as deltas while babylon.js expects the final data.
  78490. // As a result we have to add the original data to the delta to calculate the final data.
  78491. var values = data;
  78492. switch (attribute) {
  78493. case "NORMAL":
  78494. for (var i = 0; i < values.length; i++) {
  78495. values[i] += vertexData.normals[i];
  78496. }
  78497. targetVertexData.normals = values;
  78498. break;
  78499. case "POSITION":
  78500. for (var i = 0; i < values.length; i++) {
  78501. values[i] += vertexData.positions[i];
  78502. }
  78503. targetVertexData.positions = values;
  78504. break;
  78505. case "TANGENT":
  78506. // Tangent data for morph targets is stored as xyz delta.
  78507. // The vertexData.tangent is stored as xyzw.
  78508. // So we need to skip every fourth vertexData.tangent.
  78509. for (var i = 0, j = 0; i < values.length; i++, j++) {
  78510. values[i] += vertexData.tangents[j];
  78511. if ((i + 1) % 3 == 0) {
  78512. j++;
  78513. }
  78514. }
  78515. targetVertexData.tangents = values;
  78516. break;
  78517. default:
  78518. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78519. break;
  78520. }
  78521. if (--numRemainingAttributes === 0) {
  78522. onSuccess(targetVertexData);
  78523. }
  78524. });
  78525. };
  78526. var this_5 = this;
  78527. for (var attribute in attributes) {
  78528. _loop_6(attribute);
  78529. }
  78530. };
  78531. GLTFLoader.prototype._loadTransform = function (node) {
  78532. if (!node.babylonMesh) {
  78533. return;
  78534. }
  78535. var position = BABYLON.Vector3.Zero();
  78536. var rotation = BABYLON.Quaternion.Identity();
  78537. var scaling = BABYLON.Vector3.One();
  78538. if (node.matrix) {
  78539. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  78540. matrix.decompose(scaling, rotation, position);
  78541. }
  78542. else {
  78543. if (node.translation)
  78544. position = BABYLON.Vector3.FromArray(node.translation);
  78545. if (node.rotation)
  78546. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  78547. if (node.scale)
  78548. scaling = BABYLON.Vector3.FromArray(node.scale);
  78549. }
  78550. node.babylonMesh.position = position;
  78551. node.babylonMesh.rotationQuaternion = rotation;
  78552. node.babylonMesh.scaling = scaling;
  78553. };
  78554. GLTFLoader.prototype._loadSkin = function (context, skin) {
  78555. var _this = this;
  78556. var skeletonId = "skeleton" + skin.index;
  78557. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  78558. if (skin.inverseBindMatrices == null) {
  78559. this._loadBones(context, skin, null);
  78560. }
  78561. else {
  78562. var accessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices);
  78563. if (!accessor) {
  78564. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  78565. }
  78566. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78567. _this._loadBones(context, skin, data);
  78568. });
  78569. }
  78570. return skin.babylonSkeleton;
  78571. };
  78572. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  78573. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  78574. node.babylonBones = node.babylonBones || {};
  78575. node.babylonBones[skin.index] = babylonBone;
  78576. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  78577. node.babylonAnimationTargets.push(babylonBone);
  78578. return babylonBone;
  78579. };
  78580. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  78581. var babylonBones = {};
  78582. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  78583. var index = _a[_i];
  78584. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  78585. if (!node) {
  78586. throw new Error(context + ": Failed to find joint " + index);
  78587. }
  78588. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  78589. }
  78590. };
  78591. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  78592. var babylonBone = babylonBones[node.index];
  78593. if (babylonBone) {
  78594. return babylonBone;
  78595. }
  78596. var boneIndex = skin.joints.indexOf(node.index);
  78597. var baseMatrix = BABYLON.Matrix.Identity();
  78598. if (inverseBindMatrixData && boneIndex !== -1) {
  78599. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  78600. baseMatrix.invertToRef(baseMatrix);
  78601. }
  78602. var babylonParentBone = null;
  78603. if (node.index !== skin.skeleton && node.parent !== this._rootNode) {
  78604. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  78605. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  78606. }
  78607. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  78608. babylonBones[node.index] = babylonBone;
  78609. return babylonBone;
  78610. };
  78611. GLTFLoader.prototype._getNodeMatrix = function (node) {
  78612. return node.matrix ?
  78613. BABYLON.Matrix.FromArray(node.matrix) :
  78614. 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());
  78615. };
  78616. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  78617. if (parentNode === void 0) { parentNode = null; }
  78618. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  78619. var index = indices_1[_i];
  78620. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  78621. if (!node) {
  78622. throw new Error(context + ": Failed to find node " + index);
  78623. }
  78624. this._traverseNode(context, node, action, parentNode);
  78625. }
  78626. };
  78627. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  78628. if (parentNode === void 0) { parentNode = null; }
  78629. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  78630. return;
  78631. }
  78632. if (!action(node, parentNode)) {
  78633. return;
  78634. }
  78635. if (node.children) {
  78636. this._traverseNodes(context, node.children, action, node);
  78637. }
  78638. };
  78639. GLTFLoader.prototype._loadAnimations = function () {
  78640. var animations = this._gltf.animations;
  78641. if (!animations) {
  78642. return;
  78643. }
  78644. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  78645. var animation = animations[animationIndex];
  78646. var context = "#/animations/" + animationIndex;
  78647. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  78648. var channel = GLTF2.GLTFUtils.GetArrayItem(animation.channels, channelIndex);
  78649. if (!channel) {
  78650. throw new Error(context + ": Failed to find channel " + channelIndex);
  78651. }
  78652. var sampler = GLTF2.GLTFUtils.GetArrayItem(animation.samplers, channel.sampler);
  78653. if (!sampler) {
  78654. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  78655. }
  78656. this._loadAnimationChannel(animation, context + "/channels/" + channelIndex, channel, context + "/samplers/" + channel.sampler, sampler);
  78657. }
  78658. }
  78659. };
  78660. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  78661. var targetNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node);
  78662. if (!targetNode) {
  78663. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  78664. }
  78665. var targetPath;
  78666. var animationType;
  78667. switch (channel.target.path) {
  78668. case "translation":
  78669. targetPath = "position";
  78670. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  78671. break;
  78672. case "rotation":
  78673. targetPath = "rotationQuaternion";
  78674. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  78675. break;
  78676. case "scale":
  78677. targetPath = "scaling";
  78678. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  78679. break;
  78680. case "weights":
  78681. targetPath = "influence";
  78682. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  78683. break;
  78684. default:
  78685. throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'");
  78686. }
  78687. var inputData;
  78688. var outputData;
  78689. var checkSuccess = function () {
  78690. if (!inputData || !outputData) {
  78691. return;
  78692. }
  78693. var outputBufferOffset = 0;
  78694. var getNextOutputValue;
  78695. switch (targetPath) {
  78696. case "position":
  78697. getNextOutputValue = function () {
  78698. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  78699. outputBufferOffset += 3;
  78700. return value;
  78701. };
  78702. break;
  78703. case "rotationQuaternion":
  78704. getNextOutputValue = function () {
  78705. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  78706. outputBufferOffset += 4;
  78707. return value;
  78708. };
  78709. break;
  78710. case "scaling":
  78711. getNextOutputValue = function () {
  78712. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  78713. outputBufferOffset += 3;
  78714. return value;
  78715. };
  78716. break;
  78717. case "influence":
  78718. getNextOutputValue = function () {
  78719. if (!targetNode.babylonMesh || !targetNode.babylonMesh.morphTargetManager) {
  78720. return BABYLON.Vector3.Zero();
  78721. }
  78722. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  78723. var value = new Array(numTargets);
  78724. for (var i = 0; i < numTargets; i++) {
  78725. value[i] = outputData[outputBufferOffset++];
  78726. }
  78727. return value;
  78728. };
  78729. break;
  78730. }
  78731. var getNextKey;
  78732. switch (sampler.interpolation) {
  78733. case "LINEAR":
  78734. getNextKey = function (frameIndex) { return ({
  78735. frame: inputData[frameIndex],
  78736. value: getNextOutputValue()
  78737. }); };
  78738. break;
  78739. case "CUBICSPLINE":
  78740. getNextKey = function (frameIndex) { return ({
  78741. frame: inputData[frameIndex],
  78742. inTangent: getNextOutputValue(),
  78743. value: getNextOutputValue(),
  78744. outTangent: getNextOutputValue()
  78745. }); };
  78746. break;
  78747. default:
  78748. throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'");
  78749. }
  78750. ;
  78751. var keys = new Array(inputData.length);
  78752. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  78753. keys[frameIndex] = getNextKey(frameIndex);
  78754. }
  78755. animation.targets = animation.targets || [];
  78756. if (targetPath === "influence" && targetNode.babylonMesh && targetNode.babylonMesh.morphTargetManager) {
  78757. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  78758. var _loop_7 = function (targetIndex) {
  78759. var morphTarget = morphTargetManager.getTarget(targetIndex);
  78760. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  78761. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  78762. babylonAnimation.setKeys(keys.map(function (key) { return ({
  78763. frame: key.frame,
  78764. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  78765. value: key.value[targetIndex],
  78766. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  78767. }); }));
  78768. morphTarget.animations.push(babylonAnimation);
  78769. animation.targets.push(morphTarget);
  78770. };
  78771. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  78772. _loop_7(targetIndex);
  78773. }
  78774. }
  78775. else if (targetNode.babylonAnimationTargets) {
  78776. var animationName = animation.name || "anim" + animation.index;
  78777. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  78778. babylonAnimation.setKeys(keys);
  78779. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  78780. var target = _a[_i];
  78781. target.animations.push(babylonAnimation.clone());
  78782. animation.targets.push(target);
  78783. }
  78784. }
  78785. };
  78786. var inputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input);
  78787. if (!inputAccessor) {
  78788. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  78789. }
  78790. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  78791. inputData = data;
  78792. checkSuccess();
  78793. });
  78794. var outputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output);
  78795. if (!outputAccessor) {
  78796. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  78797. }
  78798. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  78799. outputData = data;
  78800. checkSuccess();
  78801. });
  78802. };
  78803. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  78804. var _this = this;
  78805. this._addPendingData(buffer);
  78806. if (buffer.loadedData) {
  78807. onSuccess(buffer.loadedData);
  78808. this._removePendingData(buffer);
  78809. }
  78810. else if (buffer.loadedObservable) {
  78811. buffer.loadedObservable.add(function (buffer) {
  78812. onSuccess(buffer.loadedData);
  78813. _this._removePendingData(buffer);
  78814. });
  78815. }
  78816. else {
  78817. if (!buffer.uri) {
  78818. throw new Error(context + ": Uri is missing");
  78819. }
  78820. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  78821. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  78822. buffer.loadedData = new Uint8Array(data);
  78823. onSuccess(buffer.loadedData);
  78824. this._removePendingData(buffer);
  78825. }
  78826. else {
  78827. buffer.loadedObservable = new BABYLON.Observable();
  78828. buffer.loadedObservable.add(function (buffer) {
  78829. onSuccess(buffer.loadedData);
  78830. _this._removePendingData(buffer);
  78831. });
  78832. this._loadUri(context, buffer.uri, function (data) {
  78833. buffer.loadedData = data;
  78834. if (buffer.loadedObservable) {
  78835. buffer.loadedObservable.notifyObservers(buffer);
  78836. buffer.loadedObservable = undefined;
  78837. }
  78838. });
  78839. }
  78840. }
  78841. };
  78842. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  78843. var _this = this;
  78844. var buffer = GLTF2.GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer);
  78845. if (!buffer) {
  78846. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  78847. }
  78848. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  78849. if (_this._disposed || !bufferData) {
  78850. return;
  78851. }
  78852. var data;
  78853. try {
  78854. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  78855. }
  78856. catch (e) {
  78857. throw new Error(context + ": " + e.message);
  78858. }
  78859. onSuccess(data);
  78860. });
  78861. };
  78862. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  78863. var _this = this;
  78864. if (accessor.sparse) {
  78865. throw new Error(context + ": Sparse accessors are not currently supported");
  78866. }
  78867. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView);
  78868. if (!bufferView) {
  78869. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  78870. }
  78871. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  78872. var numComponents = _this._getNumComponentsOfType(accessor.type);
  78873. if (numComponents === 0) {
  78874. throw new Error(context + ": Invalid type (" + accessor.type + ")");
  78875. }
  78876. var data;
  78877. var byteOffset = accessor.byteOffset;
  78878. var byteStride = bufferView.byteStride;
  78879. try {
  78880. switch (accessor.componentType) {
  78881. case GLTF2.EComponentType.BYTE:
  78882. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78883. break;
  78884. case GLTF2.EComponentType.UNSIGNED_BYTE:
  78885. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78886. break;
  78887. case GLTF2.EComponentType.SHORT:
  78888. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78889. break;
  78890. case GLTF2.EComponentType.UNSIGNED_SHORT:
  78891. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78892. break;
  78893. case GLTF2.EComponentType.UNSIGNED_INT:
  78894. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78895. break;
  78896. case GLTF2.EComponentType.FLOAT:
  78897. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78898. break;
  78899. default:
  78900. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78901. }
  78902. }
  78903. catch (e) {
  78904. throw new Error(context + ": " + e);
  78905. }
  78906. onSuccess(data);
  78907. });
  78908. };
  78909. GLTFLoader.prototype._getNumComponentsOfType = function (type) {
  78910. switch (type) {
  78911. case "SCALAR": return 1;
  78912. case "VEC2": return 2;
  78913. case "VEC3": return 3;
  78914. case "VEC4": return 4;
  78915. case "MAT2": return 4;
  78916. case "MAT3": return 9;
  78917. case "MAT4": return 16;
  78918. }
  78919. return 0;
  78920. };
  78921. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  78922. byteOffset = data.byteOffset + (byteOffset || 0);
  78923. var targetLength = count * numComponents;
  78924. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  78925. return new typedArray(data.buffer, byteOffset, targetLength);
  78926. }
  78927. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  78928. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  78929. var targetBuffer = new typedArray(targetLength);
  78930. var sourceIndex = 0;
  78931. var targetIndex = 0;
  78932. while (targetIndex < targetLength) {
  78933. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  78934. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  78935. targetIndex++;
  78936. }
  78937. sourceIndex += elementStride;
  78938. }
  78939. return targetBuffer;
  78940. };
  78941. GLTFLoader.prototype._addPendingData = function (data) {
  78942. if (!this._renderReady) {
  78943. this._renderPendingCount++;
  78944. }
  78945. this._addLoaderPendingData(data);
  78946. };
  78947. GLTFLoader.prototype._removePendingData = function (data) {
  78948. if (!this._renderReady) {
  78949. if (--this._renderPendingCount === 0) {
  78950. this._renderReady = true;
  78951. this._onRenderReady();
  78952. }
  78953. }
  78954. this._removeLoaderPendingData(data);
  78955. };
  78956. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  78957. this._loaderPendingCount++;
  78958. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  78959. var tracker = _a[_i];
  78960. tracker._addPendingData(data);
  78961. }
  78962. };
  78963. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  78964. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  78965. var tracker = _a[_i];
  78966. tracker._removePendingData(data);
  78967. }
  78968. if (--this._loaderPendingCount === 0) {
  78969. this._onComplete();
  78970. }
  78971. };
  78972. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  78973. var _this = this;
  78974. var tracker = new GLTFLoaderTracker(function () {
  78975. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  78976. onComplete();
  78977. });
  78978. this._loaderTrackers.push(tracker);
  78979. this._addLoaderPendingData(tracker);
  78980. action();
  78981. this._removeLoaderPendingData(tracker);
  78982. };
  78983. GLTFLoader.prototype._getDefaultMaterial = function () {
  78984. if (!this._defaultMaterial) {
  78985. var id = "__gltf_default";
  78986. var material = this._babylonScene.getMaterialByName(id);
  78987. if (!material) {
  78988. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  78989. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78990. material.metallic = 1;
  78991. material.roughness = 1;
  78992. }
  78993. this._defaultMaterial = material;
  78994. }
  78995. return this._defaultMaterial;
  78996. };
  78997. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  78998. var babylonMaterial = material.babylonMaterial;
  78999. // Ensure metallic workflow
  79000. babylonMaterial.metallic = 1;
  79001. babylonMaterial.roughness = 1;
  79002. var properties = material.pbrMetallicRoughness;
  79003. if (!properties) {
  79004. return;
  79005. }
  79006. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  79007. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  79008. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  79009. if (properties.baseColorTexture) {
  79010. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index);
  79011. if (!texture) {
  79012. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  79013. }
  79014. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  79015. }
  79016. if (properties.metallicRoughnessTexture) {
  79017. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index);
  79018. if (!texture) {
  79019. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  79020. }
  79021. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  79022. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  79023. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  79024. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  79025. }
  79026. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  79027. };
  79028. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  79029. if (material.babylonMaterial) {
  79030. assign(material.babylonMaterial, false);
  79031. return;
  79032. }
  79033. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  79034. return;
  79035. }
  79036. this._createPbrMaterial(material);
  79037. this._loadMaterialBaseProperties(context, material);
  79038. this._loadMaterialMetallicRoughnessProperties(context, material);
  79039. if (material.babylonMaterial) {
  79040. assign(material.babylonMaterial, true);
  79041. }
  79042. };
  79043. GLTFLoader.prototype._createPbrMaterial = function (material) {
  79044. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  79045. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79046. material.babylonMaterial = babylonMaterial;
  79047. };
  79048. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  79049. var babylonMaterial = material.babylonMaterial;
  79050. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  79051. if (material.doubleSided) {
  79052. babylonMaterial.backFaceCulling = false;
  79053. babylonMaterial.twoSidedLighting = true;
  79054. }
  79055. if (material.normalTexture) {
  79056. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index);
  79057. if (!texture) {
  79058. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  79059. }
  79060. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  79061. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  79062. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  79063. if (material.normalTexture.scale != null) {
  79064. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  79065. }
  79066. }
  79067. if (material.occlusionTexture) {
  79068. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index);
  79069. if (!texture) {
  79070. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  79071. }
  79072. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  79073. babylonMaterial.useAmbientInGrayScale = true;
  79074. if (material.occlusionTexture.strength != null) {
  79075. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  79076. }
  79077. }
  79078. if (material.emissiveTexture) {
  79079. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index);
  79080. if (!texture) {
  79081. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  79082. }
  79083. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  79084. }
  79085. };
  79086. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  79087. var babylonMaterial = material.babylonMaterial;
  79088. var alphaMode = material.alphaMode || "OPAQUE";
  79089. switch (alphaMode) {
  79090. case "OPAQUE":
  79091. // default is opaque
  79092. break;
  79093. case "MASK":
  79094. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  79095. if (colorFactor) {
  79096. if (colorFactor[3] == 0) {
  79097. babylonMaterial.alphaCutOff = 1;
  79098. }
  79099. else {
  79100. babylonMaterial.alphaCutOff /= colorFactor[3];
  79101. }
  79102. }
  79103. if (babylonMaterial.albedoTexture) {
  79104. babylonMaterial.albedoTexture.hasAlpha = true;
  79105. }
  79106. break;
  79107. case "BLEND":
  79108. if (colorFactor) {
  79109. babylonMaterial.alpha = colorFactor[3];
  79110. }
  79111. if (babylonMaterial.albedoTexture) {
  79112. babylonMaterial.albedoTexture.hasAlpha = true;
  79113. babylonMaterial.useAlphaFromAlbedoTexture = true;
  79114. }
  79115. break;
  79116. default:
  79117. throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'");
  79118. }
  79119. };
  79120. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  79121. var _this = this;
  79122. if (coordinatesIndex === void 0) { coordinatesIndex = 0; }
  79123. var sampler = (texture.sampler == null ? {} : GLTF2.GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler));
  79124. if (!sampler) {
  79125. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  79126. }
  79127. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  79128. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  79129. this._addPendingData(texture);
  79130. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  79131. _this._tryCatchOnError(function () {
  79132. _this._removePendingData(texture);
  79133. });
  79134. }, function (message) {
  79135. _this._tryCatchOnError(function () {
  79136. throw new Error(context + ": " + message);
  79137. });
  79138. });
  79139. if (texture.url) {
  79140. babylonTexture.updateURL(texture.url);
  79141. }
  79142. else if (texture.dataReadyObservable) {
  79143. texture.dataReadyObservable.add(function (texture) {
  79144. babylonTexture.updateURL(texture.url);
  79145. });
  79146. }
  79147. else {
  79148. texture.dataReadyObservable = new BABYLON.Observable();
  79149. texture.dataReadyObservable.add(function (texture) {
  79150. babylonTexture.updateURL(texture.url);
  79151. });
  79152. var image_1 = GLTF2.GLTFUtils.GetArrayItem(this._gltf.images, texture.source);
  79153. if (!image_1) {
  79154. throw new Error(context + ": Failed to find source " + texture.source);
  79155. }
  79156. this._loadImage("#/images/" + image_1.index, image_1, function (data) {
  79157. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  79158. if (texture.dataReadyObservable) {
  79159. texture.dataReadyObservable.notifyObservers(texture);
  79160. }
  79161. });
  79162. }
  79163. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  79164. if (sampler.wrapS !== undefined) {
  79165. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  79166. }
  79167. if (sampler.wrapT !== undefined) {
  79168. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  79169. }
  79170. babylonTexture.name = texture.name || "texture" + texture.index;
  79171. if (this._parent.onTextureLoaded) {
  79172. this._parent.onTextureLoaded(babylonTexture);
  79173. }
  79174. return babylonTexture;
  79175. };
  79176. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  79177. if (image.uri) {
  79178. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  79179. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  79180. }
  79181. else {
  79182. this._loadUri(context, image.uri, onSuccess);
  79183. }
  79184. }
  79185. else {
  79186. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView);
  79187. if (!bufferView) {
  79188. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  79189. }
  79190. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  79191. }
  79192. };
  79193. GLTFLoader.prototype._loadUri = function (context, uri, onSuccess) {
  79194. var _this = this;
  79195. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  79196. throw new Error(context + ": Uri '" + uri + "' is invalid");
  79197. }
  79198. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  79199. _this._tryCatchOnError(function () {
  79200. onSuccess(new Uint8Array(data));
  79201. });
  79202. }, function (event) {
  79203. _this._tryCatchOnError(function () {
  79204. _this._onProgress(event);
  79205. });
  79206. }, this._babylonScene.database, true, function (request) {
  79207. _this._tryCatchOnError(function () {
  79208. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  79209. });
  79210. });
  79211. if (request) {
  79212. this._requests.push(request);
  79213. }
  79214. };
  79215. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  79216. try {
  79217. handler();
  79218. }
  79219. catch (e) {
  79220. this._onError(e.message);
  79221. }
  79222. };
  79223. GLTFLoader.Extensions = {};
  79224. return GLTFLoader;
  79225. }());
  79226. GLTF2.GLTFLoader = GLTFLoader;
  79227. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  79228. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79229. })(BABYLON || (BABYLON = {}));
  79230. //# sourceMappingURL=babylon.glTFLoader.js.map
  79231. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79232. var BABYLON;
  79233. (function (BABYLON) {
  79234. var GLTF2;
  79235. (function (GLTF2) {
  79236. /**
  79237. * Utils functions for GLTF
  79238. */
  79239. var GLTFUtils = /** @class */ (function () {
  79240. function GLTFUtils() {
  79241. }
  79242. /**
  79243. * If the uri is a base64 string
  79244. * @param uri: the uri to test
  79245. */
  79246. GLTFUtils.IsBase64 = function (uri) {
  79247. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  79248. };
  79249. /**
  79250. * Decode the base64 uri
  79251. * @param uri: the uri to decode
  79252. */
  79253. GLTFUtils.DecodeBase64 = function (uri) {
  79254. var decodedString = atob(uri.split(",")[1]);
  79255. var bufferLength = decodedString.length;
  79256. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  79257. for (var i = 0; i < bufferLength; i++) {
  79258. bufferView[i] = decodedString.charCodeAt(i);
  79259. }
  79260. return bufferView.buffer;
  79261. };
  79262. GLTFUtils.ValidateUri = function (uri) {
  79263. return (uri.indexOf("..") === -1);
  79264. };
  79265. GLTFUtils.AssignIndices = function (array) {
  79266. if (array) {
  79267. for (var index = 0; index < array.length; index++) {
  79268. array[index].index = index;
  79269. }
  79270. }
  79271. };
  79272. GLTFUtils.GetArrayItem = function (array, index) {
  79273. if (!array || !array[index]) {
  79274. return null;
  79275. }
  79276. return array[index];
  79277. };
  79278. GLTFUtils.GetTextureWrapMode = function (mode) {
  79279. // Set defaults if undefined
  79280. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  79281. switch (mode) {
  79282. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  79283. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  79284. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  79285. default:
  79286. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  79287. return BABYLON.Texture.WRAP_ADDRESSMODE;
  79288. }
  79289. };
  79290. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  79291. // Set defaults if undefined
  79292. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  79293. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  79294. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  79295. switch (minFilter) {
  79296. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  79297. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  79298. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  79299. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  79300. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  79301. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79302. default:
  79303. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79304. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79305. }
  79306. }
  79307. else {
  79308. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  79309. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  79310. }
  79311. switch (minFilter) {
  79312. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  79313. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  79314. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79315. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  79316. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  79317. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  79318. default:
  79319. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79320. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79321. }
  79322. }
  79323. };
  79324. return GLTFUtils;
  79325. }());
  79326. GLTF2.GLTFUtils = GLTFUtils;
  79327. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79328. })(BABYLON || (BABYLON = {}));
  79329. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  79330. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79331. var BABYLON;
  79332. (function (BABYLON) {
  79333. var GLTF2;
  79334. (function (GLTF2) {
  79335. var GLTFLoaderExtension = /** @class */ (function () {
  79336. function GLTFLoaderExtension() {
  79337. this.enabled = true;
  79338. }
  79339. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  79340. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  79341. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  79342. GLTFLoaderExtension.prototype._loadExtension = function (property, action) {
  79343. var _this = this;
  79344. if (!property.extensions) {
  79345. return false;
  79346. }
  79347. var extension = property.extensions[this.name];
  79348. if (!extension) {
  79349. return false;
  79350. }
  79351. // Clear out the extension before executing the action to avoid recursing into the same property.
  79352. property.extensions[this.name] = undefined;
  79353. action(extension, function () {
  79354. // Restore the extension after completing the action.
  79355. if (property.extensions) {
  79356. property.extensions[_this.name] = extension;
  79357. }
  79358. });
  79359. return true;
  79360. };
  79361. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  79362. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  79363. };
  79364. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  79365. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  79366. };
  79367. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  79368. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  79369. };
  79370. GLTFLoaderExtension._ApplyExtensions = function (action) {
  79371. var extensions = GLTFLoaderExtension._Extensions;
  79372. if (!extensions) {
  79373. return false;
  79374. }
  79375. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  79376. var extension = extensions_1[_i];
  79377. if (extension.enabled && action(extension)) {
  79378. return true;
  79379. }
  79380. }
  79381. return false;
  79382. };
  79383. //
  79384. // Utilities
  79385. //
  79386. GLTFLoaderExtension._Extensions = [];
  79387. return GLTFLoaderExtension;
  79388. }());
  79389. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  79390. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79391. })(BABYLON || (BABYLON = {}));
  79392. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  79393. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  79394. var BABYLON;
  79395. (function (BABYLON) {
  79396. var GLTF2;
  79397. (function (GLTF2) {
  79398. var Extensions;
  79399. (function (Extensions) {
  79400. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  79401. var MSFTLOD = /** @class */ (function (_super) {
  79402. __extends(MSFTLOD, _super);
  79403. function MSFTLOD() {
  79404. return _super !== null && _super.apply(this, arguments) || this;
  79405. }
  79406. Object.defineProperty(MSFTLOD.prototype, "name", {
  79407. get: function () {
  79408. return "MSFT_lod";
  79409. },
  79410. enumerable: true,
  79411. configurable: true
  79412. });
  79413. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  79414. return this._loadExtension(node, function (extension, onComplete) {
  79415. if (!loader._gltf.nodes) {
  79416. return;
  79417. }
  79418. for (var i = extension.ids.length - 1; i >= 0; i--) {
  79419. var lodNode = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.nodes, extension.ids[i]);
  79420. if (!lodNode) {
  79421. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  79422. }
  79423. loader._traverseNode(context, lodNode, action, parentNode);
  79424. }
  79425. loader._traverseNode(context, node, action, parentNode);
  79426. onComplete();
  79427. });
  79428. };
  79429. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  79430. var _this = this;
  79431. return this._loadExtension(node, function (extension, onComplete) {
  79432. var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; });
  79433. loader._addLoaderPendingData(node);
  79434. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  79435. loader._removeLoaderPendingData(node);
  79436. onComplete();
  79437. });
  79438. });
  79439. };
  79440. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  79441. var _this = this;
  79442. loader._whenAction(function () {
  79443. loader._loadNode(context, nodes[index]);
  79444. }, function () {
  79445. if (index !== nodes.length - 1) {
  79446. var previousNode = nodes[index + 1];
  79447. if (previousNode.babylonMesh) {
  79448. previousNode.babylonMesh.setEnabled(false);
  79449. }
  79450. }
  79451. if (index === 0) {
  79452. onComplete();
  79453. return;
  79454. }
  79455. setTimeout(function () {
  79456. loader._tryCatchOnError(function () {
  79457. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  79458. });
  79459. }, MSFTLOD.MinimalLODDelay);
  79460. });
  79461. };
  79462. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  79463. var _this = this;
  79464. return this._loadExtension(material, function (extension, onComplete) {
  79465. var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; });
  79466. loader._addLoaderPendingData(material);
  79467. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  79468. if (material.extensions) {
  79469. material.extensions[_this.name] = extension;
  79470. }
  79471. loader._removeLoaderPendingData(material);
  79472. onComplete();
  79473. });
  79474. });
  79475. };
  79476. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  79477. var _this = this;
  79478. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  79479. assign(babylonMaterial, isNew);
  79480. if (index === 0) {
  79481. onComplete();
  79482. return;
  79483. }
  79484. // Load the next LOD when the loader is ready to render and
  79485. // all active material textures of the current LOD are loaded.
  79486. loader._executeWhenRenderReady(function () {
  79487. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  79488. setTimeout(function () {
  79489. loader._tryCatchOnError(function () {
  79490. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  79491. });
  79492. }, MSFTLOD.MinimalLODDelay);
  79493. });
  79494. });
  79495. });
  79496. };
  79497. /**
  79498. * Specify the minimal delay between LODs in ms (default = 250)
  79499. */
  79500. MSFTLOD.MinimalLODDelay = 250;
  79501. return MSFTLOD;
  79502. }(GLTF2.GLTFLoaderExtension));
  79503. Extensions.MSFTLOD = MSFTLOD;
  79504. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  79505. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  79506. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79507. })(BABYLON || (BABYLON = {}));
  79508. //# sourceMappingURL=MSFT_lod.js.map
  79509. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  79510. var BABYLON;
  79511. (function (BABYLON) {
  79512. var GLTF2;
  79513. (function (GLTF2) {
  79514. var Extensions;
  79515. (function (Extensions) {
  79516. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  79517. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  79518. function KHRMaterialsPbrSpecularGlossiness() {
  79519. return _super !== null && _super.apply(this, arguments) || this;
  79520. }
  79521. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  79522. get: function () {
  79523. return "KHR_materials_pbrSpecularGlossiness";
  79524. },
  79525. enumerable: true,
  79526. configurable: true
  79527. });
  79528. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  79529. var _this = this;
  79530. return this._loadExtension(material, function (extension, onComplete) {
  79531. loader._createPbrMaterial(material);
  79532. loader._loadMaterialBaseProperties(context, material);
  79533. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  79534. if (material.babylonMaterial) {
  79535. assign(material.babylonMaterial, true);
  79536. }
  79537. });
  79538. };
  79539. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  79540. var babylonMaterial = material.babylonMaterial;
  79541. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  79542. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  79543. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  79544. if (loader._gltf.textures) {
  79545. if (properties.diffuseTexture) {
  79546. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.diffuseTexture.index);
  79547. if (!texture) {
  79548. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  79549. }
  79550. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  79551. }
  79552. if (properties.specularGlossinessTexture) {
  79553. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.specularGlossinessTexture.index);
  79554. if (!texture) {
  79555. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  79556. }
  79557. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  79558. babylonMaterial.reflectivityTexture.hasAlpha = true;
  79559. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  79560. }
  79561. }
  79562. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  79563. };
  79564. return KHRMaterialsPbrSpecularGlossiness;
  79565. }(GLTF2.GLTFLoaderExtension));
  79566. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  79567. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  79568. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  79569. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79570. })(BABYLON || (BABYLON = {}));
  79571. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  79572. (function universalModuleDefinition(root, factory) {
  79573. if (root && root["BABYLON"]) {
  79574. return;
  79575. }
  79576. if(typeof exports === 'object' && typeof module === 'object')
  79577. module.exports = factory();
  79578. else if(typeof define === 'function' && define.amd)
  79579. define([], factory);
  79580. else if(typeof exports === 'object')
  79581. exports["BABYLON"] = factory();
  79582. else {
  79583. root["BABYLON"] = factory();
  79584. }
  79585. })(this, function() {
  79586. return BABYLON;
  79587. });